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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
647 | spring-cloud/spring-cloud-dataflow/2439/2405 | spring-cloud | spring-cloud-dataflow | https://github.com/spring-cloud/spring-cloud-dataflow/issues/2405 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2439 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2439 | 1 | resolves | Command line arguments not passed to ScheduleRequest | When on the "Create Schedules" page in the dashboard, I can add a key and value to the "Task Arguments" but that value is not passed to the ScheduleRequest.commandLineArguments.
But If you create the task with say `timestamp --timestamp.format=YYYY` it will be mapped as a property in the AppDefinition so that is working, just a note.. | d946c8093550e87330803ebfbe2c2de15971ee47 | 07c8b6cfece369c577e0898691f19512aa47d4cd | https://github.com/spring-cloud/spring-cloud-dataflow/compare/d946c8093550e87330803ebfbe2c2de15971ee47...07c8b6cfece369c577e0898691f19512aa47d4cd | diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerService.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerService.java
index c5ed9f8f0..976892edc 100644
--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerService.java
+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerService.java
@@ -52,6 +52,7 @@ import org.springframework.util.StringUtils;
* for Scheduling tasks.
*
* @author Glenn Renfro
+ * @author Chris Schaefer
*/
public class DefaultSchedulerService implements SchedulerService {
@@ -133,9 +134,8 @@ public class DefaultSchedulerService implements SchedulerService {
appDeploymentProperties, whitelistProperties);
DeploymentPropertiesUtils.validateDeploymentProperties(taskDeploymentProperties);
taskDeploymentProperties = extractAndQualifySchedulerProperties(taskDeploymentProperties);
- ScheduleRequest scheduleRequest = new ScheduleRequest(revisedDefinition,
- taskDeploymentProperties,
- deployerDeploymentProperties, scheduleName, getTaskResource(taskDefinitionName));
+ ScheduleRequest scheduleRequest = new ScheduleRequest(revisedDefinition, taskDeploymentProperties,
+ deployerDeploymentProperties, commandLineArgs, scheduleName, getTaskResource(taskDefinitionName));
this.scheduler.schedule(scheduleRequest);
}
@@ -203,7 +203,7 @@ public class DefaultSchedulerService implements SchedulerService {
return result;
}
- private Resource getTaskResource(String taskDefinitionName) {
+ protected Resource getTaskResource(String taskDefinitionName) {
TaskDefinition taskDefinition = this.taskDefinitionRepository.findOne(taskDefinitionName);
if (taskDefinition == null) {
throw new NoSuchTaskDefinitionException(taskDefinitionName);
diff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java
index f2ddd3202..df1b3d7b3 100644
--- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java
+++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java
@@ -18,6 +18,7 @@ package org.springframework.cloud.dataflow.server.service.impl;
import java.net.URI;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -27,15 +28,19 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
+import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.cloud.dataflow.configuration.metadata.ApplicationConfigurationMetadataResolver;
import org.springframework.cloud.dataflow.core.ApplicationType;
import org.springframework.cloud.dataflow.core.TaskDefinition;
import org.springframework.cloud.dataflow.registry.AppRegistry;
+import org.springframework.cloud.dataflow.registry.AppRegistryCommon;
import org.springframework.cloud.dataflow.registry.domain.AppRegistration;
import org.springframework.cloud.dataflow.server.DockerValidatorProperties;
import org.springframework.cloud.dataflow.server.config.apps.CommonApplicationProperties;
@@ -43,21 +48,26 @@ import org.springframework.cloud.dataflow.server.configuration.TaskServiceDepend
import org.springframework.cloud.dataflow.server.repository.TaskDefinitionRepository;
import org.springframework.cloud.dataflow.server.service.SchedulerService;
import org.springframework.cloud.dataflow.server.service.SchedulerServiceProperties;
+import org.springframework.cloud.deployer.resource.docker.DockerResource;
import org.springframework.cloud.scheduler.spi.core.CreateScheduleException;
import org.springframework.cloud.scheduler.spi.core.ScheduleInfo;
+import org.springframework.cloud.scheduler.spi.core.ScheduleRequest;
import org.springframework.cloud.scheduler.spi.core.Scheduler;
import org.springframework.core.io.Resource;
+import org.springframework.core.io.ResourceLoader;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { EmbeddedDataSourceConfiguration.class, TaskServiceDependencies.class,
PropertyPlaceholderAutoConfiguration.class }, properties = {
@@ -255,6 +265,52 @@ public class DefaultSchedulerServiceTests {
assertThat(schedules.size()).isEqualTo(0);
}
+ @Test
+ @DirtiesContext
+ public void testScheduleWithCommandLineArguments() {
+ List<String> commandLineArguments = getCommandLineArguments(Arrays.asList("--myArg1", "--myArg2"));
+
+ assertNotNull("Command line arguments should not be null", commandLineArguments);
+ assertEquals("Invalid number of command line arguments", 2, commandLineArguments.size());
+ assertEquals("Invalid command line argument", "--myArg1", commandLineArguments.get(0));
+ assertEquals("Invalid command line argument", "--myArg2", commandLineArguments.get(1));
+ }
+
+ @Test
+ @DirtiesContext
+ public void testScheduleWithoutCommandLineArguments() {
+ List<String> commandLineArguments = getCommandLineArguments(null);
+
+ assertNotNull("Command line arguments should not be null", commandLineArguments);
+ assertEquals("Invalid number of command line arguments", 0, commandLineArguments.size());
+ }
+
+ private List<String> getCommandLineArguments(List<String> commandLineArguments) {
+ Scheduler mockScheduler = mock(TaskServiceDependencies.SimpleTestScheduler.class);
+ TaskDefinitionRepository mockTaskDefinitionRepository = mock(TaskDefinitionRepository.class);
+ AppRegistryCommon mockAppRegistryCommon = mock(AppRegistryCommon.class);
+
+ SchedulerService mockSchedulerService = new DefaultSchedulerService(mock(CommonApplicationProperties.class),
+ mockScheduler, mockTaskDefinitionRepository, mockAppRegistryCommon, mock(ResourceLoader.class),
+ mock(TaskConfigurationProperties.class), mock(DataSourceProperties.class), "uri",
+ mock(ApplicationConfigurationMetadataResolver.class), mock(SchedulerServiceProperties.class));
+
+ TaskDefinition taskDefinition = new TaskDefinition(BASE_DEFINITION_NAME, "timestamp");
+
+ when(mockTaskDefinitionRepository.findOne(BASE_DEFINITION_NAME)).thenReturn(taskDefinition);
+ when(mockAppRegistryCommon.find(taskDefinition.getRegisteredAppName(), ApplicationType.task))
+ .thenReturn(new AppRegistration());
+ when(((DefaultSchedulerService)mockSchedulerService).getTaskResource(BASE_DEFINITION_NAME))
+ .thenReturn(new DockerResource("springcloudtask/timestamp-task:latest"));
+
+ mockSchedulerService.schedule(BASE_SCHEDULE_NAME, BASE_DEFINITION_NAME, this.testProperties,
+ commandLineArguments);
+
+ ArgumentCaptor<ScheduleRequest> scheduleRequestArgumentCaptor = ArgumentCaptor.forClass(ScheduleRequest.class);
+ verify(mockScheduler).schedule(scheduleRequestArgumentCaptor.capture());
+
+ return scheduleRequestArgumentCaptor.getValue().getCommandlineArguments();
+ }
private void verifyScheduleExistsInScheduler(ScheduleInfo scheduleInfo) {
List<ScheduleInfo> scheduleInfos = ((TaskServiceDependencies.SimpleTestScheduler)simpleTestScheduler).getSchedules(); | ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerService.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,535,393 | 327,540 | 44,297 | 439 | 556 | 105 | 8 | 1 | 339 | 56 | 76 | 3 | 0 | 0 | 1970-01-01T00:25:37 | 1,007 | Java | {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190} | Apache License 2.0 |
645 | spring-cloud/spring-cloud-dataflow/3206/3192 | spring-cloud | spring-cloud-dataflow | https://github.com/spring-cloud/spring-cloud-dataflow/issues/3192 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/3206 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/3206 | 1 | resolves | Scheduled Task does not recognize multiple profiles | @chrisjs commented on [Wed Apr 24 2019](https://github.com/spring-cloud/spring-cloud-dataflow-ui/issues/1178)
@jsa4000 commented on [Wed Apr 24 2019](https://github.com/spring-cloud/spring-cloud-dataflow/issues/3187)
**Description:**
Creating a scheduled task using kubernetes Spring Cloud Dataflow server, it does not parse correctly the arguments with commas. for example `--spring.profiles.active=k8s,master`. It seems to interprete the profile composition as two arguments.
`2019-04-24 07:38:12.456 DEBUG 1 --- [ main] o.s.c.t.r.support.SimpleTaskRepository : Creating: TaskExecution{executionId=0, parentExecutionId=null, exitCode=null, taskName='batch-uploader-task', startTime=Wed Apr 24 07:38:12 GMT 2019, endTime=null, exitMessage='null', externalExecutionId='null', errorMessage='null', arguments=[--spring.datasource.username=postgres, --spring.datasource.url=jdbc:postgresql://eks-lab-dev-db.cwekrnapay4v.eu-west-2.rds.amazonaws.com:5432/dataflow, --spring.datasource.driverClassName=org.postgresql.Driver, --spring.cloud.task.name=batch-uploader-task, --version=0.0.1, --spring.datasource.password=password, --spring.profiles.active=k8s, master]}`
In this case the second profile is not recognized for the application.
This happens only creating scheduled tasks, since launching the tasks normally it work as expected.
**Release versions:**
Used docker version from docker hub.
- image: springcloud/spring-cloud-dataflow-server
- version: 2.0.2.RELEASE
**Custom apps:**
A custom App with a partitioner that needs two profiles to work.
**Steps to reproduce:**
1. Register the app
`app register --type task --name batch-uploader-app --uri docker:jsa4000/dataflow-batch-uploader-k8s:0.0.1-SNAPSHOT`
2. Create the task
`task create batch-uploader-task --definition "batch-uploader-app --version=0.0.1"`
3. Create a schedule task:
Task Name: `batch-uploader-task`
Schedule name: `myschedule`
Cron Expression: `*/1 * * * *`
Arguments: `--spring.profiles.active=k8s,master` or `--spring.profiles.active="k8s,master"`
---
@sabbyanandan commented on [Wed Apr 24 2019](https://github.com/spring-cloud/spring-cloud-dataflow/issues/3187#issuecomment-486232483)
@jsa4000: Thanks for the report. That seems like a disconnect between a manual launch vs. launching on a recurring schedule. We will have a look.
---
@chrisjs commented on [Wed Apr 24 2019](https://github.com/spring-cloud/spring-cloud-dataflow/issues/3187#issuecomment-486320460)
when `TaskSchedulerController.save` is called, `arguments` contain multiple entries, based on how many `,`'s it splits on, rather than a single value
---
@oodamien commented on [Mon Apr 29 2019](https://github.com/spring-cloud/spring-cloud-dataflow-ui/issues/1178#issuecomment-487611983)
The UI send the args as a string:
`--foo1=bar1, bar2, --foo2=bar3`
| aa39aeaaa3e8d8305cf74b8ac737660b02543117 | f4ce350549485eed99d650c17df369d2cb17b622 | https://github.com/spring-cloud/spring-cloud-dataflow/compare/aa39aeaaa3e8d8305cf74b8ac737660b02543117...f4ce350549485eed99d650c17df369d2cb17b622 | diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskSchedulerController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskSchedulerController.java
index 284cf08a4..4343dab82 100644
--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskSchedulerController.java
+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskSchedulerController.java
@@ -136,9 +136,10 @@ public class TaskSchedulerController {
public void save(@RequestParam("scheduleName") String scheduleName,
@RequestParam("taskDefinitionName") String taskDefinitionName,
@RequestParam String properties,
- @RequestParam(required = false) List<String> arguments) {
+ @RequestParam(required = false) String arguments) {
Map<String, String> propertiesToUse = DeploymentPropertiesUtils.parse(properties);
- schedulerService.schedule(scheduleName, taskDefinitionName, propertiesToUse, arguments);
+ List<String> argumentsToUse = DeploymentPropertiesUtils.parseParamList(arguments, " ");
+ schedulerService.schedule(scheduleName, taskDefinitionName, propertiesToUse, argumentsToUse);
}
/**
diff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/TaskSchedulerControllerTests.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/TaskSchedulerControllerTests.java
index 7035ddb5c..a05b8550c 100644
--- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/TaskSchedulerControllerTests.java
+++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/TaskSchedulerControllerTests.java
@@ -191,15 +191,35 @@ public class TaskSchedulerControllerTests {
@Test
public void testCreateScheduleWithSensitiveFields() throws Exception {
- AppRegistration registration = this.registry.save("testApp", ApplicationType.task,
- "1.0.0", new URI("file:src/test/resources/apps/foo-task"), null);
+ String auditData = createScheduleWithArguments("argument1=foo password=secret");
+
+ assertEquals(
+ "{\\"commandlineArguments\\":[\\"argument1=foo\\",\\"password=******\\"],\\"taskDefinitionName\\":\\"testDefinition\\","
+ + "\\"taskDefinitionProperties\\":{\\"prop1\\":\\"foo\\",\\"spring.datasource.username\\":null,\\"prop2.secret\\":\\"******\\",\\"spring.datasource.url\\":null,\\"spring.datasource.driverClassName\\":null,\\"spring.cloud.task.name\\":\\"testDefinition\\"},"
+ + "\\"deploymentProperties\\":{\\"spring.cloud.deployer.prop1.secret\\":\\"******\\",\\"spring.cloud.deployer.prop2.password\\":\\"******\\"}}",
+ auditData);
+ }
+
+ @Test
+ public void testCreateScheduleCommaDelimitedArgs() throws Exception {
+ String auditData = createScheduleWithArguments("argument1=foo spring.profiles.active=k8s,master argument3=bar");
+
+ assertEquals(
+ "{\\"commandlineArguments\\":[\\"argument1=foo\\",\\"spring.profiles.active=k8s,master\\",\\"argument3=bar\\"],\\"taskDefinitionName\\":\\"testDefinition\\","
+ + "\\"taskDefinitionProperties\\":{\\"prop1\\":\\"foo\\",\\"spring.datasource.username\\":null,\\"prop2.secret\\":\\"******\\",\\"spring.datasource.url\\":null,\\"spring.datasource.driverClassName\\":null,\\"spring.cloud.task.name\\":\\"testDefinition\\"},"
+ + "\\"deploymentProperties\\":{\\"spring.cloud.deployer.prop1.secret\\":\\"******\\",\\"spring.cloud.deployer.prop2.password\\":\\"******\\"}}",
+ auditData);
+ }
+
+ private String createScheduleWithArguments(String arguments) throws Exception {
+ this.registry.save("testApp", ApplicationType.task, "1.0.0", new URI("file:src/test/resources/apps/foo-task"), null);
repository.save(new TaskDefinition("testDefinition", "testApp"));
mockMvc.perform(post("/tasks/schedules/").param("taskDefinitionName", "testDefinition")
.param("scheduleName", "mySchedule")
.param("properties",
"scheduler.cron.expression=* * * * *,app.testApp.prop1=foo,app.testApp.prop2.secret=kenny,deployer.*.prop1.secret=cartman,deployer.*.prop2.password=kyle")
- .param("arguments", "argument1=foo,password=secret")
+ .param("arguments", arguments)
.accept(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isCreated());
assertEquals(1, simpleTestScheduler.list().size());
ScheduleInfo scheduleInfo = simpleTestScheduler.list().get(0);
@@ -216,12 +236,7 @@ public class TaskSchedulerControllerTests {
assertEquals(AuditActionType.CREATE, auditRecord.getAuditAction());
assertEquals("mySchedule", auditRecord.getCorrelationId());
- assertEquals(
- "{\\"commandlineArguments\\":[\\"argument1=foo\\",\\"password=******\\"],\\"taskDefinitionName\\":\\"testDefinition\\","
- + "\\"taskDefinitionProperties\\":{\\"prop1\\":\\"foo\\",\\"spring.datasource.username\\":null,\\"prop2.secret\\":\\"******\\",\\"spring.datasource.url\\":null,\\"spring.datasource.driverClassName\\":null,\\"spring.cloud.task.name\\":\\"testDefinition\\"},"
- + "\\"deploymentProperties\\":{\\"spring.cloud.deployer.prop1.secret\\":\\"******\\",\\"spring.cloud.deployer.prop2.password\\":\\"******\\"}}",
- auditRecord.getAuditData());
-
+ return auditRecord.getAuditData();
}
@Test | ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskSchedulerController.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/TaskSchedulerControllerTests.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,807,425 | 390,562 | 52,139 | 503 | 397 | 80 | 5 | 1 | 2,879 | 262 | 761 | 64 | 5 | 0 | 1970-01-01T00:25:57 | 1,007 | Java | {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190} | Apache License 2.0 |
649 | spring-cloud/spring-cloud-dataflow/2337/2336 | spring-cloud | spring-cloud-dataflow | https://github.com/spring-cloud/spring-cloud-dataflow/issues/2336 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2337 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2337 | 1 | resolves | DataFlow fails to schedule CTR | When dataflow creates a schedule for a CTR it fails because it the DefaultSchedulerService requests an AppRegistration for the CTR and the AppRegisty throws an exception. This is because the AppRegistry does not know how to handle CTRs (this is expected). So the DefaultSchedulerService needs to add code to support requesting the CTR App (not the definition) from the AppRegistry. | 0c55bfb86b8eeb9bfb32a876b0d50f006560d9ef | 1944a2b8378e3f9493a53f330c332e848eeea662 | https://github.com/spring-cloud/spring-cloud-dataflow/compare/0c55bfb86b8eeb9bfb32a876b0d50f006560d9ef...1944a2b8378e3f9493a53f330c332e848eeea662 | diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerService.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerService.java
index 41a6a6c05..c5ed9f8f0 100644
--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerService.java
+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerService.java
@@ -203,16 +203,27 @@ public class DefaultSchedulerService implements SchedulerService {
return result;
}
- private Resource getTaskResource(String taskDefinitionName ) {
+ private Resource getTaskResource(String taskDefinitionName) {
TaskDefinition taskDefinition = this.taskDefinitionRepository.findOne(taskDefinitionName);
if (taskDefinition == null) {
throw new NoSuchTaskDefinitionException(taskDefinitionName);
}
-
- AppRegistration appRegistration = this.registry.find(taskDefinition.getRegisteredAppName(),
- ApplicationType.task);
+ AppRegistration appRegistration = null;
+ if (isComposedDefinition(taskDefinition.getDslText())) {
+ appRegistration = this.registry.find(taskConfigurationProperties.getComposedTaskRunnerName(),
+ ApplicationType.task);
+ }
+ else {
+ appRegistration = this.registry.find(taskDefinition.getRegisteredAppName(),
+ ApplicationType.task);
+ }
Assert.notNull(appRegistration, "Unknown task app: " + taskDefinition.getRegisteredAppName());
return this.registry.getAppResource(appRegistration);
}
+ private boolean isComposedDefinition(String dsl) {
+ Assert.hasText(dsl, "dsl must not be empty nor null");
+ TaskParser taskParser = new TaskParser("__dummy", dsl, true, true);
+ return taskParser.parse().isComposed();
+ }
}
diff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java
index 32d3f7eaa..114e2e331 100644
--- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java
+++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java
@@ -73,6 +73,8 @@ public class DefaultSchedulerServiceTests {
private static final String BASE_DEFINITION_NAME = "myTaskDefinition";
+ private static final String CTR_DEFINITION_NAME= "myCtrDefinition";
+
@Autowired
private Scheduler simpleTestScheduler;
@@ -97,7 +99,10 @@ public class DefaultSchedulerServiceTests {
@Before
public void setup() throws Exception{
this.appRegistry.save("demo", ApplicationType.task, new URI("file:src/test/resources/apps/foo-task"), new URI("file:src/test/resources/apps/foo-task"));
+ this.appRegistry.save("demo2", ApplicationType.task, new URI("file:src/test/resources/apps/foo-task"), new URI("file:src/test/resources/apps/foo-task"));
+
taskDefinitionRepository.save(new TaskDefinition(BASE_DEFINITION_NAME, "demo"));
+ taskDefinitionRepository.save(new TaskDefinition(CTR_DEFINITION_NAME, "demo && demo2"));
initializeSuccessfulRegistry();
this.testProperties = new HashMap<>();
@@ -121,6 +126,13 @@ public class DefaultSchedulerServiceTests {
verifyScheduleExistsInScheduler(createScheduleInfo(BASE_SCHEDULE_NAME));
}
+ @Test
+ @DirtiesContext
+ public void testScheduleCTR(){
+ schedulerService.schedule(BASE_SCHEDULE_NAME, CTR_DEFINITION_NAME, this.testProperties, this.commandLineArgs);
+ verifyScheduleExistsInScheduler(createScheduleInfo(BASE_SCHEDULE_NAME, CTR_DEFINITION_NAME));
+ }
+
@Test(expected = CreateScheduleException.class)
@DirtiesContext
public void testDuplicate(){
@@ -266,9 +278,13 @@ public class DefaultSchedulerServiceTests {
}
private ScheduleInfo createScheduleInfo(String scheduleName) {
+ return createScheduleInfo(scheduleName, BASE_DEFINITION_NAME);
+ }
+
+ private ScheduleInfo createScheduleInfo(String scheduleName, String taskDefinitionName) {
ScheduleInfo scheduleInfo = new ScheduleInfo();
scheduleInfo.setScheduleName(scheduleName);
- scheduleInfo.setTaskDefinitionName(BASE_DEFINITION_NAME);
+ scheduleInfo.setTaskDefinitionName(taskDefinitionName);
scheduleInfo.setScheduleProperties(this.resolvedProperties);
return scheduleInfo;
} | ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerService.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/service/impl/DefaultSchedulerServiceTests.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,427,357 | 304,672 | 41,131 | 407 | 841 | 171 | 19 | 1 | 383 | 60 | 83 | 1 | 0 | 0 | 1970-01-01T00:25:32 | 1,007 | Java | {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190} | Apache License 2.0 |
653 | spring-cloud/spring-cloud-dataflow/2198/2196 | spring-cloud | spring-cloud-dataflow | https://github.com/spring-cloud/spring-cloud-dataflow/issues/2196 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2198 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2198 | 1 | resolves | Argument sanitizer regex requires some more fine tuning | The argument sanitizer fails on the following stream DSL:
```
twitterstream --twitter.stream.stream-type=filter --twitter.stream.track=java --twitter.credentials.access-token-secret= --twitter.credentials.consumer-secret= --twitter.credentials.consumer-key= --twitter.credentials.access-token= | filter --filter.expression=#jsonPath(payload,'$.lang')=='en' | log
``` | cc58c2e62308c44c157a86648564843a44bbf8f4 | 20b19cf43c6998c1fe4f2e882d3e212bfe4a1d92 | https://github.com/spring-cloud/spring-cloud-dataflow/compare/cc58c2e62308c44c157a86648564843a44bbf8f4...20b19cf43c6998c1fe4f2e882d3e212bfe4a1d92 | diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java
index 246093909..576c92897 100644
--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java
+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java
@@ -247,7 +247,7 @@ public class StreamDefinitionController {
@Override
public StreamDefinitionResource instantiateResource(StreamDefinition stream) {
final StreamDefinitionResource resource = new StreamDefinitionResource(stream.getName(),
- ArgumentSanitizer.sanitizeStream(stream.getDslText()));
+ new ArgumentSanitizer().sanitizeStream(stream));
DeploymentState deploymentState = streamDeploymentStates.get(stream);
if (deploymentState != null) {
final DeploymentStateResource deploymentStateResource = ControllerUtils
diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDeploymentController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDeploymentController.java
index 874362e5b..4e45d3ed2 100644
--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDeploymentController.java
+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDeploymentController.java
@@ -184,7 +184,7 @@ public class StreamDeploymentController {
deploymentProperties = streamDeployment.getDeploymentProperties();
}
return new StreamDeploymentResource(streamDeployment.getStreamName(),
- ArgumentSanitizer.sanitizeStream(this.dslText), deploymentProperties, this.status);
+ new ArgumentSanitizer().sanitizeStream(new StreamDefinition(streamDeployment.getStreamName(), this.dslText)), deploymentProperties, this.status);
}
private boolean canDisplayDeploymentProperties() {
diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/support/ArgumentSanitizer.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/support/ArgumentSanitizer.java
index 3bd7a8bc9..c90098ae9 100644
--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/support/ArgumentSanitizer.java
+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/support/ArgumentSanitizer.java
@@ -16,11 +16,14 @@
package org.springframework.cloud.dataflow.server.controller.support;
-import java.util.regex.Matcher;
+import java.util.List;
+import java.util.Map;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
-import org.springframework.util.Assert;
-import org.springframework.util.StringUtils;
+import org.springframework.cloud.dataflow.core.StreamAppDefinition;
+import org.springframework.cloud.dataflow.core.StreamDefinition;
+import org.springframework.cloud.dataflow.core.StreamDefinitionToDslConverter;
/**
* Sanitizes potentially sensitive keys for a specific command line arg.
@@ -34,24 +37,17 @@ public class ArgumentSanitizer {
private static final String[] KEYS_TO_SANITIZE = { "password", "secret", "key", "token", ".*credentials.*",
"vcap_services" };
- //used to find the passwords embedded in a stream definition
- private static Pattern passwordParameterPatternForStreams = Pattern.compile(
- //Search for the -- characters then look for unicode letters
- "(?i)(--[\\\\p{Z}]*[\\\\p{L}.]*[\\\\p{Pd}]*("
- //that match the following strings from the KEYS_TO_SANITIZE array
- + StringUtils.arrayToDelimitedString(KEYS_TO_SANITIZE, "|")
- //Following the equal sign (group1) accept any number of unicode characters(letters, open punctuation, close punctuation etc) for the value to be sanitized for group 3.
- + ")[\\\\p{L}-]*[\\\\p{Z}]*=[\\\\p{Z}]*)((\\"[\\\\p{L}-|\\\\p{Pd}|\\\\p{Ps}|\\\\p{Pe}|\\\\p{Pc}|\\\\p{S}|\\\\p{N}|\\\\p{Z}]*\\")|([\\\\p{N}|\\\\p{L}-|\\\\p{Po}|\\\\p{Pc}|\\\\p{S}]*))",
- Pattern.UNICODE_CASE);
-
private Pattern[] keysToSanitize;
+ private StreamDefinitionToDslConverter dslConverter;
+
public ArgumentSanitizer() {
this.keysToSanitize = new Pattern[KEYS_TO_SANITIZE.length];
for (int i = 0; i < keysToSanitize.length; i++) {
this.keysToSanitize[i] = getPattern(KEYS_TO_SANITIZE[i]);
}
+ this.dslConverter = new StreamDefinitionToDslConverter();
}
private Pattern getPattern(String value) {
@@ -107,38 +103,24 @@ public class ArgumentSanitizer {
}
/**
- * Redacts sensitive values in a stream.
+ * Redacts sensitive property values in a stream.
*
- * @param definition the definition to sanitize
- * @return Stream definition that has sensitive data redacted.
+ * @param streamDefinition the stream definition to sanitize
+ * @return Stream definition text that has sensitive data redacted.
*/
- public static String sanitizeStream(String definition) {
- Assert.hasText(definition, "definition must not be null nor empty");
- final StringBuffer output = new StringBuffer();
- final Matcher matcher = passwordParameterPatternForStreams.matcher(definition);
- while (matcher.find()) {
- String passwordValue = matcher.group(3);
-
- String maskedPasswordValue;
- boolean isPipeAppended = false;
- boolean isNameChannelAppended = false;
- if (passwordValue.endsWith("|")) {
- isPipeAppended = true;
- }
- if (passwordValue.endsWith(">")) {
- isNameChannelAppended = true;
- }
- maskedPasswordValue = REDACTION_STRING;
- if (isPipeAppended) {
- maskedPasswordValue = maskedPasswordValue + " |";
- }
- if (isNameChannelAppended) {
- maskedPasswordValue = maskedPasswordValue + " >";
- }
- matcher.appendReplacement(output, matcher.group(1) + maskedPasswordValue);
- }
- matcher.appendTail(output);
- return output.toString();
+ public String sanitizeStream(StreamDefinition streamDefinition) {
+ List<StreamAppDefinition> sanitizedAppDefinitions = streamDefinition.getAppDefinitions().stream()
+ .map(app -> StreamAppDefinition.Builder
+ .from(app)
+ .setProperties(this.sanitizeProperties(app.getProperties()))
+ .build(streamDefinition.getName())
+ ).collect(Collectors.toList());
+
+ return this.dslConverter.toDsl(sanitizedAppDefinitions);
}
+ private Map<String, String> sanitizeProperties(Map<String, String> properties) {
+ return properties.entrySet().stream()
+ .collect(Collectors.toMap(e -> e.getKey(), e -> this.sanitize(e.getKey(), e.getValue())));
+ }
}
diff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/StreamControllerTests.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/StreamControllerTests.java
index b6eb478a9..dc770c517 100644
--- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/StreamControllerTests.java
+++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/StreamControllerTests.java
@@ -30,7 +30,6 @@ import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.cloud.dataflow.configuration.metadata.ApplicationConfigurationMetadataResolver;
import org.springframework.cloud.dataflow.core.BindingPropertyKeys;
import org.springframework.cloud.dataflow.core.StreamAppDefinition;
import org.springframework.cloud.dataflow.core.StreamDefinition;
@@ -40,7 +39,6 @@ import org.springframework.cloud.dataflow.server.configuration.TestDependencies;
import org.springframework.cloud.dataflow.server.repository.DeploymentIdRepository;
import org.springframework.cloud.dataflow.server.repository.DeploymentKey;
import org.springframework.cloud.dataflow.server.repository.StreamDefinitionRepository;
-import org.springframework.cloud.dataflow.server.service.StreamService;
import org.springframework.cloud.deployer.resource.maven.MavenResource;
import org.springframework.cloud.deployer.spi.app.AppDeployer;
import org.springframework.cloud.deployer.spi.app.AppInstanceStatus;
@@ -95,9 +93,6 @@ public class StreamControllerTests {
@Autowired
private DeploymentIdRepository deploymentIdRepository;
- @Autowired
- private ApplicationConfigurationMetadataResolver metadataResolver;
-
private MockMvc mockMvc;
@Autowired
@@ -109,9 +104,6 @@ public class StreamControllerTests {
@Autowired
private CommonApplicationProperties appsProperties;
- @Autowired
- private StreamService defaultStreamService;
-
@Before
public void setupMocks() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
@@ -261,8 +253,8 @@ public class StreamControllerTests {
response = mockMvc
.perform(get("/streams/definitions/myStream5/related?nested=true").accept(MediaType.APPLICATION_JSON))
.andReturn().getResponse().getContentAsString();
- assertTrue(response.contains(":myStream5.time > log --password=******"));
- assertTrue(response.contains("time | log --secret=******"));
+ assertTrue(response.contains(":myStream5.time > log --password='******'"));
+ assertTrue(response.contains("time | log --secret='******'"));
assertTrue(response.contains("\\"totalElements\\":2"));
String response2 = mockMvc.perform(
@@ -313,7 +305,7 @@ public class StreamControllerTests {
.param("deploy", "false"))
.andExpect(status().isCreated());
mockMvc.perform(post("/streams/definitions").param("name", "timelogDoubleTick")
- .param("definition", "time --format=\\"YYYY MM DD\\" | log")
+ .param("definition", "a: time --format=\\"YYYY MM DD\\" | log")
.param("deploy", "false")).andExpect(status().isCreated());
mockMvc.perform(post("/streams/definitions/").param("name", "twoPassword")
.param("definition", "time --password='foo'| log --password=bar")
@@ -332,8 +324,8 @@ public class StreamControllerTests {
.perform(get("/streams/definitions/").accept(MediaType.APPLICATION_JSON))
.andReturn().getResponse().getContentAsString();
- assertTrue(response.contains("time --password=****** | log"));
- assertTrue(response.contains("time --foo=bar| log"));
+ assertTrue(response.contains("time --password='******' | log"));
+ assertTrue(response.contains("time --foo=bar | log"));
assertTrue(response.contains(":myStream1.time > log"));
assertTrue(response.contains("time | log"));
@@ -346,19 +338,18 @@ public class StreamControllerTests {
assertTrue(response.contains(":myStream2 > log"));
assertTrue(response.contains(":myStream3 > log"));
assertTrue(response.contains("time --format='YYYY MM DD' | log"));
- assertTrue(response.contains("time --format=\\\\\\"YYYY MM DD\\\\\\" | log"));
- assertTrue(response.contains("time --password=****** | log --password=******"));
- System.out.println(response);
- assertTrue(response.contains("time --password=****** > :foobar"));
- assertTrue(response.contains("time --password=****** --arg=foo | log"));
- assertTrue(response.contains("time --password=****** --arg=bar | log"));
+ assertTrue(response.contains("a: time --format='YYYY MM DD' | log"));
+ assertTrue(response.contains("time --password='******' | log --password='******'"));
+ assertTrue(response.contains("time --password='******' > :foobar"));
+ assertTrue(response.contains("time --password='******' --arg=foo | log"));
+ assertTrue(response.contains("time --password='******' --arg=bar | log"));
assertTrue(response.contains("\\"totalElements\\":15"));
}
@Test
- public void testSaveInvalidAppDefintions() throws Exception {
+ public void testSaveInvalidAppDefinitions() throws Exception {
mockMvc.perform(post("/streams/definitions/").param("name", "myStream").param("definition", "foo | bar")
.accept(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isBadRequest())
.andExpect(jsonPath("$[0].logref", is("InvalidStreamDefinitionException")))
@@ -369,7 +360,7 @@ public class StreamControllerTests {
}
@Test
- public void testSaveInvalidAppDefintionsDueToParseException() throws Exception {
+ public void testSaveInvalidAppDefinitionsDueToParseException() throws Exception {
mockMvc.perform(post("/streams/definitions/").param("name", "myStream")
.param("definition", "foo --.spring.cloud.stream.metrics.properties=spring* | bar")
.accept(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isBadRequest())
@@ -619,7 +610,7 @@ public class StreamControllerTests {
when(appDeployer.status("myStream.log")).thenReturn(status);
mockMvc.perform(get("/streams/definitions/myStream").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andExpect(content().json("{name: \\"myStream\\"}"))
- .andExpect(content().json("{dslText: \\"time --secret=****** | log\\"}"));
+ .andExpect(content().json("{dslText: \\"time --secret='******' | log\\"}"));
}
@Test
diff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/support/ArgumentSanitizerTest.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/support/ArgumentSanitizerTest.java
index a42ccd86f..add550db1 100644
--- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/support/ArgumentSanitizerTest.java
+++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/support/ArgumentSanitizerTest.java
@@ -20,6 +20,7 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.springframework.cloud.dataflow.core.StreamDefinition;
import org.springframework.cloud.dataflow.server.controller.support.ArgumentSanitizer;
/**
@@ -56,18 +57,23 @@ public class ArgumentSanitizerTest {
@Test
public void testHierarchicalPropertyNames() {
- Assert.assertEquals("time --password=****** | log", ArgumentSanitizer.sanitizeStream("time --password=bar | log"));
+ Assert.assertEquals("time --password='******' | log",
+ sanitizer.sanitizeStream(new StreamDefinition("stream", "time --password=bar | log")));
}
@Test
public void testStreamMatcherWithHyphenDotChar() {
- Assert.assertEquals("twitterstream --twitter.credentials.consumer-key=****** --twitter.credentials.consumer-secret=****** "
- + "--twitter.credentials.access-token=****** --twitter.credentials.access-token-secret=****** | filter --expression=#jsonPath(payload,'$.lang')=='en' | "
- + "twitter-sentiment --vocabulary=http://dl.bintray.com/test --model-fetch=output/test --model=http://dl.bintray.com/test | "
- + "field-value-counter --field-name=sentiment --name=sentiment", ArgumentSanitizer.sanitizeStream("twitterstream "
- + "--twitter.credentials.consumer-key=dadadfaf --twitter.credentials.consumer-secret=dadfdasfdads "
- + "--twitter.credentials.access-token=58849055-dfdae --twitter.credentials.access-token-secret=deteegdssa4466 | filter --expression=#jsonPath(payload,'$.lang')=='en' | "
- + "twitter-sentiment --vocabulary=http://dl.bintray.com/test --model-fetch=output/test --model=http://dl.bintray.com/test | "
- + "field-value-counter --field-name=sentiment --name=sentiment"));
+ Assert.assertEquals("twitterstream --twitter.credentials.access-token-secret='******' "
+ + "--twitter.credentials.access-token='******' --twitter.credentials.consumer-secret='******' "
+ + "--twitter.credentials.consumer-key='******' | "
+ + "filter --expression=#jsonPath(payload,'$.lang')=='en' | "
+ + "twitter-sentiment --vocabulary=http://dl.bintray.com/test --model-fetch=output/test "
+ + "--model=http://dl.bintray.com/test | field-value-counter --field-name=sentiment --name=sentiment",
+ sanitizer.sanitizeStream(new StreamDefinition("stream", "twitterstream "
+ + "--twitter.credentials.consumer-key=dadadfaf --twitter.credentials.consumer-secret=dadfdasfdads "
+ + "--twitter.credentials.access-token=58849055-dfdae "
+ + "--twitter.credentials.access-token-secret=deteegdssa4466 | filter --expression=#jsonPath(payload,'$.lang')=='en' | "
+ + "twitter-sentiment --vocabulary=http://dl.bintray.com/test --model-fetch=output/test --model=http://dl.bintray.com/test | "
+ + "field-value-counter --field-name=sentiment --name=sentiment")));
}
} | ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/StreamControllerTests.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/support/ArgumentSanitizerTest.java', 'spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDeploymentController.java', 'spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/support/ArgumentSanitizer.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 1,378,662 | 295,066 | 39,912 | 396 | 3,625 | 834 | 72 | 3 | 372 | 23 | 73 | 5 | 0 | 1 | 1970-01-01T00:25:25 | 1,007 | Java | {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190} | Apache License 2.0 |
657 | spring-cloud/spring-cloud-dataflow/1866/1864 | spring-cloud | spring-cloud-dataflow | https://github.com/spring-cloud/spring-cloud-dataflow/issues/1864 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/1866 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/1866 | 1 | resolves | HttpMessageNotReadableException should not return a 500 HTTP status code | A HttpMessageNotReadableException should not return a 500 HTTP status code. Instead a `HttpStatus.BAD_REQUEST` should be returned.
Task:
Add `HttpMessageNotReadableException` as `@ExceptionHandler` to `RestControllerAdvice#onClientGenericBadRequest`
Afterwards, fix `LocalServerSecurityWithSingleUserTests`
| 58bbc9b4d5dd777c881566c4c370a3b9fe40585d | b34e35f07c3a51817b7ba8e4b948ad7a92de9519 | https://github.com/spring-cloud/spring-cloud-dataflow/compare/58bbc9b4d5dd777c881566c4c370a3b9fe40585d...b34e35f07c3a51817b7ba8e4b948ad7a92de9519 | diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/RestControllerAdvice.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/RestControllerAdvice.java
index 803b7e7df..d1801797f 100644
--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/RestControllerAdvice.java
+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/RestControllerAdvice.java
@@ -39,6 +39,7 @@ import org.springframework.cloud.dataflow.server.repository.NoSuchTaskExecutionE
import org.springframework.cloud.dataflow.server.support.ApplicationDoesNotExistException;
import org.springframework.hateoas.VndErrors;
import org.springframework.http.HttpStatus;
+import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.UnsatisfiedServletRequestParameterException;
@@ -164,7 +165,7 @@ public class RestControllerAdvice {
* @return the error response in JSON format with media type
* application/vnd.error+json
*/
- @ExceptionHandler({ MissingServletRequestParameterException.class,
+ @ExceptionHandler({ MissingServletRequestParameterException.class, HttpMessageNotReadableException.class,
UnsatisfiedServletRequestParameterException.class, MethodArgumentTypeMismatchException.class,
InvalidStreamDefinitionException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
diff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/ToolsControllerTests.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/ToolsControllerTests.java
index 0aa26caf1..3832a8177 100644
--- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/ToolsControllerTests.java
+++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/ToolsControllerTests.java
@@ -65,7 +65,7 @@ public class ToolsControllerTests {
@Test
public void testMissingArgumentFailure() throws Exception {
mockMvc.perform(post("/tools/parseTaskTextToGraph").accept(MediaType.APPLICATION_JSON))
- .andExpect(status().isInternalServerError());
+ .andExpect(status().isBadRequest());
}
@Test
diff --git a/spring-cloud-starter-dataflow-server-local/src/test/java/org/springframework/cloud/dataflow/server/local/security/LocalServerSecurityWithSingleUserTests.java b/spring-cloud-starter-dataflow-server-local/src/test/java/org/springframework/cloud/dataflow/server/local/security/LocalServerSecurityWithSingleUserTests.java
index 2aea59482..c4312c377 100644
--- a/spring-cloud-starter-dataflow-server-local/src/test/java/org/springframework/cloud/dataflow/server/local/security/LocalServerSecurityWithSingleUserTests.java
+++ b/spring-cloud-starter-dataflow-server-local/src/test/java/org/springframework/cloud/dataflow/server/local/security/LocalServerSecurityWithSingleUserTests.java
@@ -171,11 +171,11 @@ public class LocalServerSecurityWithSingleUserTests {
{ HttpMethod.PUT, HttpStatus.FORBIDDEN, "/tools/convertTaskGraphToText", singleUser,
TestUtils.toImmutableMap("detailLevel", "2") },
- { HttpMethod.POST, HttpStatus.INTERNAL_SERVER_ERROR, "/tools/parseTaskTextToGraph", singleUser,
+ { HttpMethod.POST, HttpStatus.BAD_REQUEST, "/tools/parseTaskTextToGraph", singleUser,
TestUtils.toImmutableMap("name", "foo", "dsl", "t1 && t2")},
{ HttpMethod.POST, HttpStatus.UNAUTHORIZED, "/tools/parseTaskTextToGraph", null, null },
- { HttpMethod.POST, HttpStatus.INTERNAL_SERVER_ERROR, "/tools/convertTaskGraphToText", singleUser, null},
+ { HttpMethod.POST, HttpStatus.BAD_REQUEST, "/tools/convertTaskGraphToText", singleUser, null},
{ HttpMethod.POST, HttpStatus.UNAUTHORIZED, "/tools/convertTaskGraphToText", null, null },
/* FeaturesController */
@@ -399,8 +399,8 @@ public class LocalServerSecurityWithSingleUserTests {
/* LoginController */
- { HttpMethod.POST, HttpStatus.INTERNAL_SERVER_ERROR, "/authenticate", singleUser, null },
- { HttpMethod.POST, HttpStatus.INTERNAL_SERVER_ERROR, "/authenticate", null, null },
+ { HttpMethod.POST, HttpStatus.BAD_REQUEST, "/authenticate", singleUser, null },
+ { HttpMethod.POST, HttpStatus.BAD_REQUEST, "/authenticate", null, null },
/* SecurityController */
diff --git a/spring-cloud-starter-dataflow-server-local/src/test/java/org/springframework/cloud/dataflow/server/local/security/LocalServerSecurityWithUsersFileTests.java b/spring-cloud-starter-dataflow-server-local/src/test/java/org/springframework/cloud/dataflow/server/local/security/LocalServerSecurityWithUsersFileTests.java
index 0f3544df7..4cf4c8ab6 100644
--- a/spring-cloud-starter-dataflow-server-local/src/test/java/org/springframework/cloud/dataflow/server/local/security/LocalServerSecurityWithUsersFileTests.java
+++ b/spring-cloud-starter-dataflow-server-local/src/test/java/org/springframework/cloud/dataflow/server/local/security/LocalServerSecurityWithUsersFileTests.java
@@ -562,10 +562,10 @@ public class LocalServerSecurityWithUsersFileTests {
/* LoginController */
- { HttpMethod.POST, HttpStatus.INTERNAL_SERVER_ERROR, "/authenticate", manageOnlyUser, null },
- { HttpMethod.POST, HttpStatus.INTERNAL_SERVER_ERROR, "/authenticate", viewOnlyUser, null },
- { HttpMethod.POST, HttpStatus.INTERNAL_SERVER_ERROR, "/authenticate", createOnlyUser, null },
- { HttpMethod.POST, HttpStatus.INTERNAL_SERVER_ERROR, "/authenticate", null, null },
+ { HttpMethod.POST, HttpStatus.BAD_REQUEST, "/authenticate", manageOnlyUser, null },
+ { HttpMethod.POST, HttpStatus.BAD_REQUEST, "/authenticate", viewOnlyUser, null },
+ { HttpMethod.POST, HttpStatus.BAD_REQUEST, "/authenticate", createOnlyUser, null },
+ { HttpMethod.POST, HttpStatus.BAD_REQUEST, "/authenticate", null, null },
/* SecurityController */
| ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/RestControllerAdvice.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/ToolsControllerTests.java', 'spring-cloud-starter-dataflow-server-local/src/test/java/org/springframework/cloud/dataflow/server/local/security/LocalServerSecurityWithSingleUserTests.java', 'spring-cloud-starter-dataflow-server-local/src/test/java/org/springframework/cloud/dataflow/server/local/security/LocalServerSecurityWithUsersFileTests.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 1,275,760 | 273,606 | 37,095 | 369 | 252 | 38 | 3 | 1 | 318 | 26 | 67 | 8 | 0 | 0 | 1970-01-01T00:25:14 | 1,007 | Java | {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190} | Apache License 2.0 |
660 | spring-cloud/spring-cloud-dataflow/1186/1185 | spring-cloud | spring-cloud-dataflow | https://github.com/spring-cloud/spring-cloud-dataflow/issues/1185 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/1186 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/1186 | 1 | fixes | Docker deployment problem: Failed to list properties for Docker Resource | Trying to deploy a stream using deployment properties (with k8s server based on SCDF 1.2.0.M1) I get:
```
dataflow:>stream deploy --name ticktock --properties "deployer.log.count=2"
Command failed org.springframework.cloud.dataflow.rest.client.DataFlowClientException: Failed to list properties for Docker Resource [docker:springcloudstream/log-sink-kafka-10:1.1.1.RELEASE]
```
Stack trace:
```
2017-02-16 14:46:12.887 ERROR 1 --- [nio-9393-exec-4] o.s.c.d.s.c.RestControllerAdvice : Caught exception while handling a request
java.lang.RuntimeException: Failed to list properties for Docker Resource [docker:springcloudstream/log-sink-kafka-10:1.1.1.RELEASE]
at org.springframework.cloud.dataflow.configuration.metadata.BootApplicationConfigurationMetadataResolver.listProperties(BootApplicationConfigurationMetadataResolver.java:105) ~[spring-cloud-dataflow-configuration-metadata-1.2.0.M1.jar!/:1.2.0.M1]
at org.springframework.cloud.dataflow.server.controller.WhitelistProperties.qualifyProperties(WhitelistProperties.java:57) ~[spring-cloud-dataflow-server-core-1.2.0.M1.jar!/:1.2.0.M1]
at org.springframework.cloud.dataflow.server.controller.StreamDeploymentController.mergeAndExpandAppProperties(StreamDeploymentController.java:276) ~[spring-cloud-dataflow-server-core-1.2.0.M1.jar!/:1.2.0.M1]
at org.springframework.cloud.dataflow.server.controller.StreamDeploymentController.deployStream(StreamDeploymentController.java:253) ~[spring-cloud-dataflow-server-core-1.2.0.M1.jar!/:1.2.0.M1]
at org.springframework.cloud.dataflow.server.controller.StreamDeploymentController.deploy(StreamDeploymentController.java:181) ~[spring-cloud-dataflow-server-core-1.2.0.M1.jar!/:1.2.0.M1]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92-internal]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92-internal]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92-internal]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92-internal]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) ~[spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) ~[spring-webmvc-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) ~[spring-webmvc-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) ~[spring-webmvc-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [spring-webmvc-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) [spring-boot-1.4.1.RELEASE.jar!/:1.4.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:105) [spring-boot-actuator-1.4.1.RELEASE.jar!/:1.4.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:208) [spring-security-web-4.1.3.RELEASE.jar!/:4.1.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) [spring-security-web-4.1.3.RELEASE.jar!/:4.1.3.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:107) [spring-boot-actuator-1.4.1.RELEASE.jar!/:1.4.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_92-internal]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_92-internal]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.5.jar!/:8.5.5]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_92-internal]
Caused by: java.io.FileNotFoundException: Docker Resource [docker:springcloudstream/log-sink-kafka-10:1.1.1.RELEASE] cannot be resolved to absolute file path
at org.springframework.core.io.AbstractResource.getFile(AbstractResource.java:114) ~[spring-core-4.3.3.RELEASE.jar!/:4.3.3.RELEASE]
at org.springframework.cloud.dataflow.configuration.metadata.BootApplicationConfigurationMetadataResolver.resolveAsArchive(BootApplicationConfigurationMetadataResolver.java:159) ~[spring-cloud-dataflow-configuration-metadata-1.2.0.M1.jar!/:1.2.0.M1]
at org.springframework.cloud.dataflow.configuration.metadata.BootApplicationConfigurationMetadataResolver.listProperties(BootApplicationConfigurationMetadataResolver.java:101) ~[spring-cloud-dataflow-configuration-metadata-1.2.0.M1.jar!/:1.2.0.M1]
... 76 common frames omitted
```
| b3a6e67bd5516bdd20c52c9ed07515df92214132 | 6e49a93fbac61a5a4b7c505d555f0b05ec8f93cb | https://github.com/spring-cloud/spring-cloud-dataflow/compare/b3a6e67bd5516bdd20c52c9ed07515df92214132...6e49a93fbac61a5a4b7c505d555f0b05ec8f93cb | diff --git a/spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/ApplicationConfigurationMetadataResolver.java b/spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/ApplicationConfigurationMetadataResolver.java
index 27b6fcb75..12ddb12e2 100644
--- a/spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/ApplicationConfigurationMetadataResolver.java
+++ b/spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/ApplicationConfigurationMetadataResolver.java
@@ -30,12 +30,6 @@ import org.springframework.core.io.Resource;
*/
public abstract class ApplicationConfigurationMetadataResolver {
- /**
- * Returns whether this resolver supports the given app.
- */
- public abstract boolean supports(Resource app);
-
-
public List<ConfigurationMetadataProperty> listProperties(Resource metadataResource) {
return listProperties(metadataResource, false);
}
diff --git a/spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/BootApplicationConfigurationMetadataResolver.java b/spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/BootApplicationConfigurationMetadataResolver.java
index d03017296..74f9dc178 100644
--- a/spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/BootApplicationConfigurationMetadataResolver.java
+++ b/spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/BootApplicationConfigurationMetadataResolver.java
@@ -22,6 +22,7 @@ import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
@@ -78,17 +79,6 @@ public class BootApplicationConfigurationMetadataResolver extends ApplicationCon
}
}
- @Override
- public boolean supports(Resource app) {
- try {
- resolveAsArchive(app);
- return true;
- }
- catch (IOException | IllegalArgumentException e) {
- return false;
- }
- }
-
/**
* Return metadata about configuration properties that are documented via
* <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html">
@@ -102,7 +92,7 @@ public class BootApplicationConfigurationMetadataResolver extends ApplicationCon
return listProperties(archive, exhaustive);
}
catch (IOException e) {
- throw new RuntimeException("Failed to list properties for " + app, e);
+ return Collections.emptyList();
}
}
diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDeploymentController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDeploymentController.java
index f79121878..c59c2806d 100644
--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDeploymentController.java
+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDeploymentController.java
@@ -246,12 +246,13 @@ public class StreamDeploymentController {
isDownStreamAppPartitioned = isPartitionedConsumer(appDeployTimeProperties,
upstreamAppSupportsPartition);
+ Resource appResource = registration.getResource();
Resource metadataResource = registration.getMetadataResource();
// Merge *definition time* app properties with *deployment time* properties
// and expand them to their long form if applicable
AppDefinition revisedDefinition = mergeAndExpandAppProperties(currentApp, metadataResource, appDeployTimeProperties);
- AppDeploymentRequest request = new AppDeploymentRequest(revisedDefinition, metadataResource, deployerDeploymentProperties);
+ AppDeploymentRequest request = new AppDeploymentRequest(revisedDefinition, appResource, deployerDeploymentProperties);
try {
String id = this.deployer.deploy(request); | ['spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/ApplicationConfigurationMetadataResolver.java', 'spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDeploymentController.java', 'spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/BootApplicationConfigurationMetadataResolver.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 880,489 | 185,222 | 25,453 | 291 | 765 | 144 | 23 | 3 | 12,441 | 322 | 3,508 | 97 | 0 | 2 | 1970-01-01T00:24:47 | 1,007 | Java | {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190} | Apache License 2.0 |
656 | spring-cloud/spring-cloud-dataflow/1989/1978 | spring-cloud | spring-cloud-dataflow | https://github.com/spring-cloud/spring-cloud-dataflow/issues/1978 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/1989 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/1989 | 1 | resolves | RootController shows invalid value for AppInstanceController | Project: _spring-cloud-dataflow-server-core_
Billboard URL on **RootController** `@RequestMapping("/")`:
`http://localhost:9393/`
The problematic part of it:
`{
"rel": "runtime/apps/instances",
"href": "http://localhost:9393/runtime/apps/interface%20org.springframework.web.util.UriComponents%24UriTemplateVariables/instances"
}`
According the code the **RootController** pass the **UriComponents.UriTemplateVariables.SKIP_VALUE** parameter to get the link for **AppInstanceStatusResource** class, but instead of it the `href` should be something like this:
`/runtime/apps/{appId}/instances`
This part `interface%20org.springframework.web.util.UriComponents%24UriTemplateVariables` is inserted into the placeholder for `{appId}`.
This problem appears in the following versions:
Local Dataflow Server: 1.2.3
Newer implementations and milestones: 1.3.0 M3
I did not try with older versions. | b3c1bd6ea09091d3e63679aba04b9528753e47d0 | 0de2d7503433c77e215ae8cb0f5d135528aa76c6 | https://github.com/spring-cloud/spring-cloud-dataflow/compare/b3c1bd6ea09091d3e63679aba04b9528753e47d0...0de2d7503433c77e215ae8cb0f5d135528aa76c6 | diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/RootController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/RootController.java
index 5a7276f9f..c2ea71531 100644
--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/RootController.java
+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/RootController.java
@@ -105,7 +105,7 @@ public class RootController {
root.add(unescapeTemplateVariables(
entityLinks.linkForSingleResource(AppStatusResource.class, "{appId}").withRel("runtime/apps/app")));
root.add(unescapeTemplateVariables(
- entityLinks.linkFor(AppInstanceStatusResource.class, UriComponents.UriTemplateVariables.SKIP_VALUE)
+ entityLinks.linkFor(AppInstanceStatusResource.class, "{appId}")
.withRel("runtime/apps/instances")));
root.add(linkTo(MetricsController.class).withRel("metrics/streams"));
} | ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/RootController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,338,029 | 286,057 | 38,775 | 389 | 175 | 34 | 2 | 1 | 919 | 81 | 212 | 23 | 2 | 0 | 1970-01-01T00:25:16 | 1,007 | Java | {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190} | Apache License 2.0 |
655 | spring-cloud/spring-cloud-dataflow/1996/1974 | spring-cloud | spring-cloud-dataflow | https://github.com/spring-cloud/spring-cloud-dataflow/issues/1974 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/1996 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/1996 | 1 | resolves | When one app fails to deploy in a stream, the stream status is "all apps failed to deploy" | This is an incorrect message.
This is what was observed when testing with skipper and investigating the issue with escaping quote characters. The transformer app failed to start, the runtime apps command was accurate reporting what was running and what had failed. | 9899605ad1a04476899f94957ba48738b387789a | 7f6380dbdf5b5580823f89172d467106783c7fde | https://github.com/spring-cloud/spring-cloud-dataflow/compare/9899605ad1a04476899f94957ba48738b387789a...7f6380dbdf5b5580823f89172d467106783c7fde | diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java
index c13c32064..3f3b26596 100644
--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java
+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2015-2017 the original author or authors.
+ * Copyright 2015-2018 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.
@@ -146,6 +146,10 @@ public class StreamDefinitionController {
logger.debug("aggregateState: Returning " + DeploymentState.error);
return DeploymentState.error;
}
+ if (states.contains(DeploymentState.deployed) && states.contains(DeploymentState.failed)) {
+ logger.debug("aggregateState: Returning " + DeploymentState.partial);
+ return DeploymentState.partial;
+ }
if (states.contains(DeploymentState.failed)) {
logger.debug("aggregateState: Returning " + DeploymentState.failed);
return DeploymentState.failed;
diff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/StreamControllerTests.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/StreamControllerTests.java
index ffb734fc8..43a8bf4ba 100644
--- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/StreamControllerTests.java
+++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/StreamControllerTests.java
@@ -889,7 +889,7 @@ public class StreamControllerTests {
@Test
public void testAggregateState() {
- assertThat(StreamDefinitionController.aggregateState(EnumSet.of(deployed, failed)), is(failed));
+ assertThat(StreamDefinitionController.aggregateState(EnumSet.of(deployed, failed)), is(partial));
assertThat(StreamDefinitionController.aggregateState(EnumSet.of(unknown, failed)), is(failed));
assertThat(StreamDefinitionController.aggregateState(EnumSet.of(deployed, failed, error)), is(error));
assertThat(StreamDefinitionController.aggregateState(EnumSet.of(deployed, undeployed)), is(partial)); | ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/StreamDefinitionController.java', 'spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/StreamControllerTests.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,339,892 | 286,445 | 38,821 | 389 | 321 | 73 | 6 | 1 | 265 | 42 | 48 | 2 | 0 | 0 | 1970-01-01T00:25:16 | 1,007 | Java | {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190} | Apache License 2.0 |
654 | spring-cloud/spring-cloud-dataflow/2099/2033 | spring-cloud | spring-cloud-dataflow | https://github.com/spring-cloud/spring-cloud-dataflow/issues/2033 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2099 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2099 | 1 | resolves | StreamDefinitionToDslConverter may create unparsable dsl from valid definition | I have encountered an Exception on deploying a stream containing a jdbc source.
The stream definition looks similar to this:
jdbc-mssql --query='UPDATE top (100) ASSURANCE SET assurance_flag = 1 OUTPUT Inserted.* WHERE assurance_flag IS NULL' --password='******' --username='******' --url='jdbc:sqlserver://db:1433;databaseName=Spring' --cron='*/10 * * * * *' --max-messages=-1 | cust-processor | router --default-output-channel=out
On deployment the following exception is thrown:
org.springframework.cloud.dataflow.core.dsl.CheckPointedParseException: 100E:(pos x): Found unexpected data after stream definition: ';'
It appears it does not like the ';' symbol from the jdbc URL.
I am using Spring Cloud Dataflow v1.3.0.RELEASE with Skipper v1.0.0.RELEASE. The same definitions worked fine in v1.2.0.RELEASE | 15095222f7693b04573ae5aae678e0e991367758 | 7b09e3549fd7b2f96a7658ca486f114a041eca50 | https://github.com/spring-cloud/spring-cloud-dataflow/compare/15095222f7693b04573ae5aae678e0e991367758...7b09e3549fd7b2f96a7658ca486f114a041eca50 | diff --git a/spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/StreamDefinitionToDslConverter.java b/spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/StreamDefinitionToDslConverter.java
index ebc4f19ee..632de3d58 100644
--- a/spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/StreamDefinitionToDslConverter.java
+++ b/spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/StreamDefinitionToDslConverter.java
@@ -112,8 +112,10 @@ public class StreamDefinitionToDslConverter {
}
private String autoQuotes(String propertyValue) {
- if (propertyValue.contains(" ") && !propertyValue.contains("'")) {
- return "'" + propertyValue + "'";
+ if (!propertyValue.contains("'")) {
+ if (propertyValue.contains(" ") || propertyValue.contains(";") || propertyValue.contains("*")) {
+ return "'" + propertyValue + "'";
+ }
}
return propertyValue;
}
diff --git a/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/StreamDefinitionToDslConverterTests.java b/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/StreamDefinitionToDslConverterTests.java
index 0731adfde..101554042 100644
--- a/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/StreamDefinitionToDslConverterTests.java
+++ b/spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/StreamDefinitionToDslConverterTests.java
@@ -187,4 +187,49 @@ public class StreamDefinitionToDslConverterTests {
new StreamDefinitionToDslConverter().toDsl(Arrays.asList(foo2, bar2)));
}
+ @Test
+ public void autoQuotesOnSemicolonProperties() {
+
+ StreamDefinition streamDefinition = new StreamDefinition("streamName",
+ "http-source-kafka --server.port=9900 | couchbase-sink-kafka " +
+ "--inputType=\\"application/x-java-object;type=com.example.dto.InputDto\\"");
+
+ assertEquals("http-source-kafka --server.port=9900 | couchbase-sink-kafka " +
+ "--spring.cloud.stream.bindings.input.contentType='application/x-java-object;type=com.example.dto.InputDto'",
+ new StreamDefinitionToDslConverter().toDsl(streamDefinition));
+
+
+ streamDefinition = new StreamDefinition("stream2", "jdbc-mssql --cron='/10 * * * * *' " +
+ "--max-messages=-1 --password='******' --query='UPDATE top (100) ASSURANCE SET assurance_flag = 1 " +
+ "OUTPUT Inserted.* WHERE assurance_flag IS NULL' " +
+ "--url='jdbc:sqlserver://db:1433;databaseName=Spring' --username='*****' | " +
+ "cust-processor | router --default-output-channel=out");
+
+ assertEquals("jdbc-mssql --cron='/10 * * * * *' " +
+ "--max-messages=-1 --password='******' --query='UPDATE top (100) ASSURANCE SET assurance_flag = 1 " +
+ "OUTPUT Inserted.* WHERE assurance_flag IS NULL' " +
+ "--url='jdbc:sqlserver://db:1433;databaseName=Spring' --username='*****' | " +
+ "cust-processor | router --default-output-channel=out",
+ new StreamDefinitionToDslConverter().toDsl(streamDefinition));
+
+ }
+
+ @Test
+ public void autoQuotesOnStarProperties() {
+
+ StreamDefinition streamDefinition = new StreamDefinition("stream2", "jdbc-mssql --cron='/10 * * * * *' " +
+ "--max-messages=-1 --password='******' --query='UPDATE top (100) ASSURANCE SET assurance_flag = 1 " +
+ "OUTPUT Inserted.* WHERE assurance_flag IS NULL' " +
+ "--url='jdbc:sqlserver://db:1433;databaseName=Spring' --username='*****' | " +
+ "cust-processor | router --default-output-channel=out");
+
+ assertEquals("jdbc-mssql --cron='/10 * * * * *' " +
+ "--max-messages=-1 --password='******' --query='UPDATE top (100) ASSURANCE SET assurance_flag = 1 " +
+ "OUTPUT Inserted.* WHERE assurance_flag IS NULL' " +
+ "--url='jdbc:sqlserver://db:1433;databaseName=Spring' --username='*****' | " +
+ "cust-processor | router --default-output-channel=out",
+ new StreamDefinitionToDslConverter().toDsl(streamDefinition));
+
+ }
+
} | ['spring-cloud-dataflow-core/src/main/java/org/springframework/cloud/dataflow/core/StreamDefinitionToDslConverter.java', 'spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/StreamDefinitionToDslConverterTests.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,357,385 | 290,132 | 39,250 | 393 | 293 | 68 | 6 | 1 | 829 | 97 | 202 | 13 | 0 | 0 | 1970-01-01T00:25:20 | 1,007 | Java | {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190} | Apache License 2.0 |
652 | spring-cloud/spring-cloud-dataflow/2287/2277 | spring-cloud | spring-cloud-dataflow | https://github.com/spring-cloud/spring-cloud-dataflow/issues/2277 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2287 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2287 | 1 | resolves | Bad error message when app resource does not exist. | given
```
dataflow:>app import --uri http://bit.ly/Celsius-SR3-stream-applications-rabbit-maven
dataflow:>app register --name customLog --type sink --uri http://example.com/log.jar --force
dataflow:>stream create --name ticktock --definition "time | customLog" --deploy
Command failed org.springframework.cloud.dataflow.rest.client.DataFlowClientException: File /tmp/spring-cloud-deployer7977040175409109846/53c2def052b6377318f5faae705d5956f8e6693e must exist
```
The error message is not clear that the jar does not exist, it references some internal file.
Here is the stack trace
```java.lang.IllegalArgumentException: File /tmp/spring-cloud-deployer7977040175409109846/53c2def052b6377318f5faae705d5956f8e6693e must exist
at org.springframework.boot.loader.data.RandomAccessDataFile.<init>(RandomAccessDataFile.java:68) ~[spring-cloud-dataflow-server-local-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.loader.data.RandomAccessDataFile.<init>(RandomAccessDataFile.java:51) ~[spring-cloud-dataflow-server-local-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.loader.jar.JarFile.<init>(JarFile.java:83) ~[spring-cloud-dataflow-server-local-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.loader.archive.JarFileArchive.<init>(JarFileArchive.java:61) ~[spring-cloud-dataflow-server-local-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.loader.archive.JarFileArchive.<init>(JarFileArchive.java:57) ~[spring-cloud-dataflow-server-local-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.cloud.dataflow.configuration.metadata.BootApplicationConfigurationMetadataResolver.resolveAsArchive(BootApplicationConfigurationMetadataResolver.java:159) ~[spring-cloud-dataflow-configuration-metadata-1.5.1.RELEASE.jar!/:1.5.1.RELEASE]
at org.springframework.cloud.dataflow.configuration.metadata.BootApplicationConfigurationMetadataResolver.listProperties(BootApplicationConfigurationMetadataResolver.java:96) ~[spring-cloud-dataflow-configuration-metadata-1.5.1.RELEASE.jar!/:1.5.1.RELEASE]
at org.springframework.cloud.dataflow.server.controller.WhitelistProperties.qualifyProperties(WhitelistProperties.java:65) ~[spring-cloud-dataflow-server-core-1.5.1.RELEASE.jar!/:1.5.1.RELEASE]
at org.springframework.cloud.dataflow.server.service.impl.AppDeploymentRequestCreator.mergeAndExpandAppProperties(AppDeploymentRequestCreator.java:308) ~[spring-cloud-dataflow-server-core-1.5.1.RELEASE.jar!/:1.5.1.RELEASE]
at org.springframework.cloud.dataflow.server.service.impl.AppDeploymentRequestCreator.createRequests(AppDeploymentRequestCreator.java:208) ~[spring-cloud-dataflow-server-core-1.5.1.RELEASE.jar!/:1.5.1.RELEASE]
at org.springframework.cloud.dataflow.server.service.impl.AppDeployerStreamService.doDeployStream(AppDeployerStreamService.java:75) ~[spring-cloud-dataflow-server-core-1.5.1.RELEASE.jar!/:1.5.1.RELEASE]
``` | 503cc905109b8d636b72c9c77ba75e272bf21fb7 | 538558eb7b6342718148d4118ee8e737df254276 | https://github.com/spring-cloud/spring-cloud-dataflow/compare/503cc905109b8d636b72c9c77ba75e272bf21fb7...538558eb7b6342718148d4118ee8e737df254276 | diff --git a/spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/BootApplicationConfigurationMetadataResolver.java b/spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/BootApplicationConfigurationMetadataResolver.java
index b535a5a5e..8121409cc 100644
--- a/spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/BootApplicationConfigurationMetadataResolver.java
+++ b/spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/BootApplicationConfigurationMetadataResolver.java
@@ -98,7 +98,9 @@ public class BootApplicationConfigurationMetadataResolver extends ApplicationCon
}
}
catch (IOException e) {
+ throw new RuntimeException("Failed to resolve application resource: " + app.getDescription());
}
+
return Collections.emptyList();
}
@@ -150,7 +152,7 @@ public class BootApplicationConfigurationMetadataResolver extends ApplicationCon
return new BootClassLoaderFactory(resolveAsArchive(app), parent).createClassLoader();
}
catch (IOException e) {
- throw new RuntimeException(e);
+ throw new RuntimeException("Failed to resolve application resource: " + app.getDescription(), e);
}
}
| ['spring-cloud-dataflow-configuration-metadata/src/main/java/org/springframework/cloud/dataflow/configuration/metadata/BootApplicationConfigurationMetadataResolver.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,417,484 | 302,595 | 40,864 | 404 | 237 | 41 | 4 | 1 | 2,887 | 93 | 746 | 27 | 2 | 2 | 1970-01-01T00:25:30 | 1,007 | Java | {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190} | Apache License 2.0 |
651 | spring-cloud/spring-cloud-dataflow/2293/2292 | spring-cloud | spring-cloud-dataflow | https://github.com/spring-cloud/spring-cloud-dataflow/issues/2292 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2293 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2293 | 1 | resolves | Don't query for latest task executions when no task definitions are present | Depended on by https://github.com/spring-cloud/spring-cloud-dataflow-ui/issues/833 | b2de7a00c4355100931521b3cfadf0225fbfaac3 | 5471397b8bf069112571e20d16b5c6349faecba6 | https://github.com/spring-cloud/spring-cloud-dataflow/compare/b2de7a00c4355100931521b3cfadf0225fbfaac3...5471397b8bf069112571e20d16b5c6349faecba6 | diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskDefinitionController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskDefinitionController.java
index 96c130bd5..705aa3a23 100644
--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskDefinitionController.java
+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskDefinitionController.java
@@ -142,9 +142,18 @@ public class TaskDefinitionController {
for (TaskDefinition taskDefinition : taskDefinitions) {
taskDefinitionMap.put(taskDefinition.getName(), taskDefinition);
}
- List<TaskExecution> taskExecutions = explorer.getLatestTaskExecutionsByTaskNames(taskDefinitionMap.keySet().toArray(new String[taskDefinitionMap.size()]));
- Page<TaskExecutionAwareTaskDefinition> taskExecutionAwareTaskDefinitions = taskDefinitions.map(new TaskDefinitionConverter(taskExecutions));
+ final List<TaskExecution> taskExecutions;
+
+ if (!taskDefinitionMap.isEmpty()) {
+ taskExecutions =
+ explorer.getLatestTaskExecutionsByTaskNames(taskDefinitionMap.keySet().toArray(new String[taskDefinitionMap.size()]));
+ }
+ else {
+ taskExecutions = null;
+ }
+
+ final Page<TaskExecutionAwareTaskDefinition> taskExecutionAwareTaskDefinitions = taskDefinitions.map(new TaskDefinitionConverter(taskExecutions));
return assembler.toResource(taskExecutionAwareTaskDefinitions, taskAssembler);
} | ['spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskDefinitionController.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,418,607 | 302,863 | 40,884 | 404 | 733 | 150 | 13 | 1 | 82 | 4 | 20 | 1 | 1 | 0 | 1970-01-01T00:25:30 | 1,007 | Java | {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190} | Apache License 2.0 |
650 | spring-cloud/spring-cloud-dataflow/2325/2242 | spring-cloud | spring-cloud-dataflow | https://github.com/spring-cloud/spring-cloud-dataflow/issues/2242 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2325 | https://github.com/spring-cloud/spring-cloud-dataflow/pull/2325 | 1 | resolves | Review Task's handling of quotes in launch arguments | Currently Task's launch controller forcefully removes all quotes inside the input arguments. This could break some RegeEx or other task functionality. | 8a15f42c801e2c07731dd010fae2fb75f345753d | 5d823eebb3215e6d9fe098a213662d5592637d31 | https://github.com/spring-cloud/spring-cloud-dataflow/compare/8a15f42c801e2c07731dd010fae2fb75f345753d...5d823eebb3215e6d9fe098a213662d5592637d31 | diff --git a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskExecutionController.java b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskExecutionController.java
index 6b60ff567..a2e362823 100644
--- a/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskExecutionController.java
+++ b/spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskExecutionController.java
@@ -145,8 +145,7 @@ public class TaskExecutionController {
Map<String, String> propertiesToUse = DeploymentPropertiesUtils.parse(properties);
DeploymentPropertiesUtils.validateDeploymentProperties(propertiesToUse);
List<String> argumentsToUse = DeploymentPropertiesUtils.parseParamList(arguments, " ");
- return this.taskService.executeTask(taskName, propertiesToUse,
- DeploymentPropertiesUtils.removeQuoting(argumentsToUse));
+ return this.taskService.executeTask(taskName, propertiesToUse, argumentsToUse);
}
/**
diff --git a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/TaskControllerTests.java b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/TaskControllerTests.java
index 0c6b472dd..1aca8bb6b 100644
--- a/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/TaskControllerTests.java
+++ b/spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/TaskControllerTests.java
@@ -294,7 +294,7 @@ public class TaskControllerTests {
assertThat(request.getCommandlineArguments().size(), is(3 + 1)); // +1 for spring.cloud.task.executionid
assertThat(request.getCommandlineArguments().get(0), is("--foobar=jee"));
assertThat(request.getCommandlineArguments().get(1), is("--foobar2=jee2,foo=bar"));
- assertThat(request.getCommandlineArguments().get(2), is("--foobar3=jee3 jee3"));
+ assertThat(request.getCommandlineArguments().get(2), is("--foobar3='jee3 jee3'"));
assertEquals("myTask3", request.getDefinition().getProperties().get("spring.cloud.task.name"));
}
| ['spring-cloud-dataflow-server-core/src/test/java/org/springframework/cloud/dataflow/server/controller/TaskControllerTests.java', 'spring-cloud-dataflow-server-core/src/main/java/org/springframework/cloud/dataflow/server/controller/TaskExecutionController.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,425,435 | 304,296 | 41,078 | 406 | 211 | 44 | 3 | 1 | 150 | 21 | 26 | 1 | 0 | 0 | 1970-01-01T00:25:31 | 1,007 | Java | {'Java': 6711491, 'Shell': 131470, 'TypeScript': 51513, 'Starlark': 14704, 'Dockerfile': 1362, 'Mustache': 1297, 'XSLT': 863, 'Ruby': 846, 'Python': 477, 'JavaScript': 310, 'Vim Snippet': 190} | Apache License 2.0 |
1,447 | googlecloudplatform/dataflowtemplates/588/582 | googlecloudplatform | dataflowtemplates | https://github.com/GoogleCloudPlatform/DataflowTemplates/issues/582 | https://github.com/GoogleCloudPlatform/DataflowTemplates/pull/588 | https://github.com/GoogleCloudPlatform/DataflowTemplates/pull/588 | 2 | fixes | [Bug]: MongoDBtoBigQuery with UDF: ScriptObjectMirror cannot be cast to bson.Document | ### Related Template(s)
MongoDB to BigQuery
### What happened?
When creating a job with MongoDB to BigQuery template and specify a UDF javascript file and function, the job fails to start. See relevant logs below.
When UDF file and function are not specified, jobs with the same template can run normally.
### Beam Version
Newer than 2.43.0
### Relevant log output
```shell
com.google.cloud.teleport.v2.common.UncaughtExceptionLogger - The template launch failed.
java.lang.ClassCastException: class org.openjdk.nashorn.api.scripting.ScriptObjectMirror cannot be cast to class org.bson.Document (org.openjdk.nashorn.api.scripting.ScriptObjectMirror and org.bson.Document are in unnamed module of loader 'app')
at com.google.cloud.teleport.v2.mongodb.templates.MongoDbUtils.getTableFieldSchemaForUDF(MongoDbUtils.java:167)
at com.google.cloud.teleport.v2.mongodb.templates.MongoDbToBigQuery.run(MongoDbToBigQuery.java:95)
at com.google.cloud.teleport.v2.mongodb.templates.MongoDbToBigQuery.main(MongoDbToBigQuery.java:82)
```
| fb7bb460c1f9899d079b5e5474d645d10e6a2a4c | 317334cce8928565a6e52b9549f06096e68eae6e | https://github.com/googlecloudplatform/dataflowtemplates/compare/fb7bb460c1f9899d079b5e5474d645d10e6a2a4c...317334cce8928565a6e52b9549f06096e68eae6e | diff --git a/v2/common/src/main/java/com/google/cloud/teleport/v2/transforms/JavascriptDocumentTransformer.java b/v2/common/src/main/java/com/google/cloud/teleport/v2/transforms/JavascriptDocumentTransformer.java
index a95016ed..85460f1a 100644
--- a/v2/common/src/main/java/com/google/cloud/teleport/v2/transforms/JavascriptDocumentTransformer.java
+++ b/v2/common/src/main/java/com/google/cloud/teleport/v2/transforms/JavascriptDocumentTransformer.java
@@ -147,15 +147,17 @@ public abstract class JavascriptDocumentTransformer {
throw new RuntimeException("No udf was loaded");
}
- Object result = getInvocable().invokeFunction(functionName(), data);
+ Object result = getInvocable().invokeFunction(functionName(), data.toJson());
if (result == null || ScriptObjectMirror.isUndefined(result)) {
return null;
} else if (result instanceof Document) {
return (Document) result;
+ } else if (result instanceof String) {
+ return Document.parse(result.toString());
} else {
String className = result.getClass().getName();
throw new RuntimeException(
- "UDF Function did not return a String. Instead got: " + className);
+ "UDF Function did not return a valid Mongo Document. Instead got: " + className);
}
}
diff --git a/v2/mongodb-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/mongodb/templates/MongoDbUtils.java b/v2/mongodb-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/mongodb/templates/MongoDbUtils.java
index 0b7258e0..9e242f87 100644
--- a/v2/mongodb-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/mongodb/templates/MongoDbUtils.java
+++ b/v2/mongodb-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/mongodb/templates/MongoDbUtils.java
@@ -50,6 +50,7 @@ import org.apache.beam.sdk.io.fs.MatchResult.Metadata;
import org.apache.beam.sdk.io.fs.MatchResult.Status;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.io.CharStreams;
import org.bson.Document;
+import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -163,8 +164,23 @@ public class MongoDbUtils implements Serializable {
throw new RuntimeException("No udf was loaded");
}
- Object result = invocable.invokeFunction(udfFunctionName, document);
- Document doc = (Document) result;
+ Document doc;
+ Object result = invocable.invokeFunction(udfFunctionName, document.toJson());
+ if (result == null || ScriptObjectMirror.isUndefined(result)) {
+ return null;
+ } else if (result instanceof Document) {
+ doc = (Document) result;
+ } else if (result instanceof String) {
+ doc = Document.parse(result.toString());
+ } else {
+ String className = result.getClass().getName();
+ throw new RuntimeException(
+ "UDF Function did not return a valid Mongo Document. Instead got: "
+ + className
+ + ": "
+ + result);
+ }
+
if (userOption.equals("FLATTEN")) {
doc.forEach(
(key, value) -> {
diff --git a/v2/mongodb-to-googlecloud/src/test/java/com/google/cloud/teleport/v2/mongodb/templates/MongoDbToBigQueryIT.java b/v2/mongodb-to-googlecloud/src/test/java/com/google/cloud/teleport/v2/mongodb/templates/MongoDbToBigQueryIT.java
index 6def5429..03ccb5a3 100644
--- a/v2/mongodb-to-googlecloud/src/test/java/com/google/cloud/teleport/v2/mongodb/templates/MongoDbToBigQueryIT.java
+++ b/v2/mongodb-to-googlecloud/src/test/java/com/google/cloud/teleport/v2/mongodb/templates/MongoDbToBigQueryIT.java
@@ -132,6 +132,14 @@ public final class MongoDbToBigQueryIT extends TemplateTestBase {
mongoDbClient.insertDocuments(collectionName, mongoDocuments);
String bqTable = testName;
+ String udfFileName = "transform.js";
+ artifactClient.createArtifact(
+ "input/" + udfFileName,
+ "function transform(inJson) {\\n"
+ + " var outJson = JSON.parse(inJson);\\n"
+ + " outJson.udf = \\"out\\";\\n"
+ + " return JSON.stringify(outJson);\\n"
+ + "}");
List<Field> bqSchemaFields = new ArrayList<>();
bqSchemaFields.add(Field.of("timestamp", StandardSQLTypeName.TIMESTAMP));
mongoDocuments
@@ -148,7 +156,9 @@ public final class MongoDbToBigQueryIT extends TemplateTestBase {
.addParameter(MONGO_DB, mongoDbClient.getDatabaseName())
.addParameter(MONGO_COLLECTION, collectionName)
.addParameter(BIGQUERY_TABLE, toTableSpec(table))
- .addParameter(USER_OPTION, "FLATTEN");
+ .addParameter(USER_OPTION, "FLATTEN")
+ .addParameter("javascriptDocumentTransformGcsPath", getGcsPath("input/" + udfFileName))
+ .addParameter("javascriptDocumentTransformFunctionName", "transform");
// Act
LaunchInfo info = launchTemplate(options);
@@ -168,6 +178,7 @@ public final class MongoDbToBigQueryIT extends TemplateTestBase {
mongoDocument -> {
JSONObject mongoDbJson = new JSONObject(mongoDocument.toJson());
String mongoId = mongoDbJson.getJSONObject(MONGO_DB_ID).getString("$oid");
+ mongoDbJson.put("udf", "out");
mongoDbJson.put(MONGO_DB_ID, mongoId);
mongoMap.put(mongoId, mongoDbJson);
});
@@ -212,6 +223,7 @@ public final class MongoDbToBigQueryIT extends TemplateTestBase {
}
mongoDocumentKeys.add(randomFieldName.toLowerCase());
}
+ mongoDocumentKeys.add("udf");
for (int i = 0; i < numDocuments; i++) {
Document randomDocument = new Document().append(MONGO_DB_ID, new ObjectId());
@@ -220,6 +232,7 @@ public final class MongoDbToBigQueryIT extends TemplateTestBase {
randomDocument.append(
mongoDocumentKeys.get(j), RandomStringUtils.randomAlphanumeric(0, 20));
}
+ randomDocument.append("udf", "in");
mongoDocuments.add(randomDocument);
} | ['v2/mongodb-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/mongodb/templates/MongoDbUtils.java', 'v2/mongodb-to-googlecloud/src/test/java/com/google/cloud/teleport/v2/mongodb/templates/MongoDbToBigQueryIT.java', 'v2/common/src/main/java/com/google/cloud/teleport/v2/transforms/JavascriptDocumentTransformer.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 6,265,280 | 1,326,875 | 165,306 | 980 | 1,235 | 254 | 26 | 2 | 1,042 | 94 | 240 | 24 | 0 | 1 | 1970-01-01T00:27:56 | 1,005 | Java | {'Java': 9158571, 'Go': 39852, 'JavaScript': 34656, 'Python': 10437, 'Dockerfile': 925, 'PureBasic': 35} | Apache License 2.0 |
1,446 | googlecloudplatform/dataflowtemplates/668/667 | googlecloudplatform | dataflowtemplates | https://github.com/GoogleCloudPlatform/DataflowTemplates/issues/667 | https://github.com/GoogleCloudPlatform/DataflowTemplates/pull/668 | https://github.com/GoogleCloudPlatform/DataflowTemplates/pull/668 | 1 | fixes | [Bug]: <Please Replace with a Summary of the Bug> | ### Related Template(s)
MQTT to Pub/Sub template
### What happened?
Providing both username and password throws an IllegalArgumentException.
### Beam Version
Newer than 2.46.0
### Relevant log output
```shell
While username is provided, password is required for authentication
```
| a1538896321fd4ed499a8aa68f7f46316ca49f3c | 6f9fd2a106c8af5740b698c106a60dd060938052 | https://github.com/googlecloudplatform/dataflowtemplates/compare/a1538896321fd4ed499a8aa68f7f46316ca49f3c...6f9fd2a106c8af5740b698c106a60dd060938052 | diff --git a/v2/mqtt-to-pubsub/src/main/java/com/google/cloud/teleport/v2/templates/MqttToPubsub.java b/v2/mqtt-to-pubsub/src/main/java/com/google/cloud/teleport/v2/templates/MqttToPubsub.java
index 37f98fbc..9cbf6b21 100644
--- a/v2/mqtt-to-pubsub/src/main/java/com/google/cloud/teleport/v2/templates/MqttToPubsub.java
+++ b/v2/mqtt-to-pubsub/src/main/java/com/google/cloud/teleport/v2/templates/MqttToPubsub.java
@@ -15,6 +15,9 @@
*/
package com.google.cloud.teleport.v2.templates;
+import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;
+import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Strings.isNullOrEmpty;
+
import com.google.cloud.teleport.metadata.Template;
import com.google.cloud.teleport.metadata.TemplateCategory;
import com.google.cloud.teleport.metadata.TemplateParameter;
@@ -58,15 +61,25 @@ public class MqttToPubsub {
}
public static void validate(MqttToPubsubOptions options) {
- if (options != null) {
- if ((options.getUsername() != null
- && (!options.getUsername().isEmpty() || !options.getUsername().isBlank()))
- && (options.getPassword() != null
- || options.getPassword().isBlank()
- || options.getPassword().isEmpty())) {
- throw new IllegalArgumentException(
- "While username is provided, password is required for authentication");
- }
+ checkArgument(
+ options != null,
+ String.format("%s is required to run this template", MqttToPubsubOptions.class.getName()));
+ validateCredentials(options);
+ }
+
+ private static void validateCredentials(MqttToPubsubOptions options) {
+
+ boolean isUsernameNullOrEmpty = isNullOrEmpty(options.getUsername());
+ boolean isPasswordNullOrEmpty = isNullOrEmpty(options.getPassword());
+
+ // Validation passes when both username and password are provided together or neither provided.
+ // Uses xor operator '^' to simplify this evaluation. The following conditional is true when
+ // either are true but not when both are true or both are false.
+ if (isUsernameNullOrEmpty ^ isPasswordNullOrEmpty) {
+ throw new IllegalArgumentException(
+ String.format(
+ "%s expects either both a username and password or neither",
+ MqttToPubsubOptions.class.getName()));
}
}
@@ -99,6 +112,7 @@ public class MqttToPubsub {
}
static class ByteToStringTransform extends DoFn<byte[], String> {
+
@ProcessElement
public void processElement(@Element byte[] word, OutputReceiver<String> out) {
out.output(new String(word, StandardCharsets.UTF_8));
@@ -110,6 +124,7 @@ public class MqttToPubsub {
* executor at the command-line.
*/
public interface MqttToPubsubOptions extends PipelineOptions {
+
@TemplateParameter.Text(
order = 1,
optional = true,
@@ -138,7 +153,8 @@ public class MqttToPubsub {
order = 3,
description = "Output Pub/Sub topic",
helpText =
- "The name of the topic to which data should published, in the format of 'projects/your-project-id/topics/your-topic-name'",
+ "The name of the topic to which data should published, in the format of"
+ + " 'projects/your-project-id/topics/your-topic-name'",
example = "projects/your-project-id/topics/your-topic-name")
@Validation.Required
String getOutputTopic();
diff --git a/v2/mqtt-to-pubsub/src/test/java/com/google/cloud/teleport/v2/templates/MqttToPubsubTest.java b/v2/mqtt-to-pubsub/src/test/java/com/google/cloud/teleport/v2/templates/MqttToPubsubTest.java
index 3f68e5a2..73b9b8f7 100644
--- a/v2/mqtt-to-pubsub/src/test/java/com/google/cloud/teleport/v2/templates/MqttToPubsubTest.java
+++ b/v2/mqtt-to-pubsub/src/test/java/com/google/cloud/teleport/v2/templates/MqttToPubsubTest.java
@@ -15,6 +15,7 @@
*/
package com.google.cloud.teleport.v2.templates;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import java.nio.charset.StandardCharsets;
@@ -51,11 +52,94 @@ public class MqttToPubsubTest {
}
@Test
- public void testValidation() {
+ public void testValidation_emptyPassword_throwsIllegalArgumentException() {
MqttToPubsub.MqttToPubsubOptions options =
PipelineOptionsFactory.create().as(MqttToPubsub.MqttToPubsubOptions.class);
options.setUsername("test");
options.setPassword("");
- assertThrows(IllegalArgumentException.class, () -> MqttToPubsub.validate(options));
+
+ IllegalArgumentException e =
+ assertThrows(IllegalArgumentException.class, () -> MqttToPubsub.validate(options));
+
+ assertEquals(
+ "com.google.cloud.teleport.v2.templates.MqttToPubsub$MqttToPubsubOptions expects either both a username and password or neither",
+ e.getMessage());
+ }
+
+ @Test
+ public void testValidation_nullPassword_throwsIllegalArgumentException() {
+ MqttToPubsub.MqttToPubsubOptions options =
+ PipelineOptionsFactory.create().as(MqttToPubsub.MqttToPubsubOptions.class);
+ options.setUsername("test");
+ options.setPassword(null);
+
+ IllegalArgumentException e =
+ assertThrows(IllegalArgumentException.class, () -> MqttToPubsub.validate(options));
+
+ assertEquals(
+ "com.google.cloud.teleport.v2.templates.MqttToPubsub$MqttToPubsubOptions expects either both a username and password or neither",
+ e.getMessage());
+ }
+
+ @Test
+ public void testValidation_emptyUsername_throwsIllegalArgumentException() {
+ MqttToPubsub.MqttToPubsubOptions options =
+ PipelineOptionsFactory.create().as(MqttToPubsub.MqttToPubsubOptions.class);
+ options.setUsername("");
+ options.setPassword("password");
+
+ IllegalArgumentException e =
+ assertThrows(IllegalArgumentException.class, () -> MqttToPubsub.validate(options));
+
+ assertEquals(
+ "com.google.cloud.teleport.v2.templates.MqttToPubsub$MqttToPubsubOptions expects either both a username and password or neither",
+ e.getMessage());
+ }
+
+ @Test
+ public void testValidation_nullUsername_throwsIllegalArgumentException() {
+ MqttToPubsub.MqttToPubsubOptions options =
+ PipelineOptionsFactory.create().as(MqttToPubsub.MqttToPubsubOptions.class);
+ options.setUsername(null);
+ options.setPassword("password");
+
+ IllegalArgumentException e =
+ assertThrows(IllegalArgumentException.class, () -> MqttToPubsub.validate(options));
+
+ assertEquals(
+ "com.google.cloud.teleport.v2.templates.MqttToPubsub$MqttToPubsubOptions expects either both a username and password or neither",
+ e.getMessage());
+ }
+
+ @Test
+ public void testValidation_nonEmptyUsernamePassword_passes() {
+ MqttToPubsub.MqttToPubsubOptions options =
+ PipelineOptionsFactory.create().as(MqttToPubsub.MqttToPubsubOptions.class);
+ options.setUsername("username");
+ options.setPassword("password");
+
+ // validates with no errors
+ MqttToPubsub.validate(options);
+ }
+
+ @Test
+ public void testValidation_emptyUsernamePassword_passes() {
+ MqttToPubsub.MqttToPubsubOptions options =
+ PipelineOptionsFactory.create().as(MqttToPubsub.MqttToPubsubOptions.class);
+ options.setUsername("");
+ options.setPassword("");
+
+ // validates with no errors
+ MqttToPubsub.validate(options);
+ }
+
+ @Test
+ public void run_nullMqttToPubsubOptions_throwsIllegalStateException() {
+ IllegalArgumentException e =
+ assertThrows(IllegalArgumentException.class, () -> MqttToPubsub.run(null));
+
+ assertEquals(
+ "com.google.cloud.teleport.v2.templates.MqttToPubsub$MqttToPubsubOptions is required to run this template",
+ e.getMessage());
}
} | ['v2/mqtt-to-pubsub/src/main/java/com/google/cloud/teleport/v2/templates/MqttToPubsub.java', 'v2/mqtt-to-pubsub/src/test/java/com/google/cloud/teleport/v2/templates/MqttToPubsubTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 5,212,183 | 1,103,778 | 137,880 | 912 | 1,898 | 360 | 36 | 1 | 288 | 39 | 61 | 18 | 0 | 1 | 1970-01-01T00:28:02 | 1,005 | Java | {'Java': 9158571, 'Go': 39852, 'JavaScript': 34656, 'Python': 10437, 'Dockerfile': 925, 'PureBasic': 35} | Apache License 2.0 |
1,445 | googlecloudplatform/dataflowtemplates/858/842 | googlecloudplatform | dataflowtemplates | https://github.com/GoogleCloudPlatform/DataflowTemplates/issues/842 | https://github.com/GoogleCloudPlatform/DataflowTemplates/pull/858 | https://github.com/GoogleCloudPlatform/DataflowTemplates/pull/858 | 1 | fixes | [Bug]: PubSubToMongoDB (V2) does not store data as UTF-8 | ### Related Template(s)
PubSubToMongoDB
### What happened?
The pipeline does not store special characters (e.g. ®) as UTF-8 in MongoDB, causing them to turn into ��.
I think the root cause is this line of code:
https://github.com/GoogleCloudPlatform/DataflowTemplates/blob/main/v2/pubsub-to-mongodb/src/main/java/com/google/cloud/teleport/v2/templates/PubSubToMongoDB.java#L471
Adjusting it like this seems to fix the issue:
```
messageObject = gson.fromJson(new String(pubsubMessage.getPayload(), StandardCharsets.UTF_8), JsonObject.class);
```
### Beam Version
Newer than 2.46.0
### Relevant log output
_No response_ | 00755b443aafd4803a117cac5fa3c152fb60d321 | 4757d3467b9c9194c32c7ebeba22be0949d19283 | https://github.com/googlecloudplatform/dataflowtemplates/compare/00755b443aafd4803a117cac5fa3c152fb60d321...4757d3467b9c9194c32c7ebeba22be0949d19283 | diff --git a/v1/src/main/java/com/google/cloud/teleport/templates/common/ErrorConverters.java b/v1/src/main/java/com/google/cloud/teleport/templates/common/ErrorConverters.java
index 36a6fe29..656578b0 100644
--- a/v1/src/main/java/com/google/cloud/teleport/templates/common/ErrorConverters.java
+++ b/v1/src/main/java/com/google/cloud/teleport/templates/common/ErrorConverters.java
@@ -279,7 +279,7 @@ public class ErrorConverters {
// Only set the payload if it's populated on the message.
if (message.getPayload() != null) {
failedRow
- .set("payloadString", new String(message.getPayload()))
+ .set("payloadString", new String(message.getPayload(), StandardCharsets.UTF_8))
.set("payloadBytes", message.getPayload());
}
diff --git a/v2/common/src/main/java/com/google/cloud/teleport/v2/transforms/ErrorConverters.java b/v2/common/src/main/java/com/google/cloud/teleport/v2/transforms/ErrorConverters.java
index 10d5da95..3fa81373 100644
--- a/v2/common/src/main/java/com/google/cloud/teleport/v2/transforms/ErrorConverters.java
+++ b/v2/common/src/main/java/com/google/cloud/teleport/v2/transforms/ErrorConverters.java
@@ -331,7 +331,7 @@ public class ErrorConverters {
PubsubMessage pubsubMessage = failsafeElement.getOriginalPayload();
String message =
pubsubMessage.getPayload().length > 0
- ? new String(pubsubMessage.getPayload())
+ ? new String(pubsubMessage.getPayload(), StandardCharsets.UTF_8)
: pubsubMessage.getAttributeMap().toString();
// Format the timestamp for insertion
diff --git a/v2/googlecloud-to-elasticsearch/src/main/java/com/google/cloud/teleport/v2/elasticsearch/transforms/FailedPubsubMessageToPubsubTopicFn.java b/v2/googlecloud-to-elasticsearch/src/main/java/com/google/cloud/teleport/v2/elasticsearch/transforms/FailedPubsubMessageToPubsubTopicFn.java
index 821a878a..7ff5e8c5 100644
--- a/v2/googlecloud-to-elasticsearch/src/main/java/com/google/cloud/teleport/v2/elasticsearch/transforms/FailedPubsubMessageToPubsubTopicFn.java
+++ b/v2/googlecloud-to-elasticsearch/src/main/java/com/google/cloud/teleport/v2/elasticsearch/transforms/FailedPubsubMessageToPubsubTopicFn.java
@@ -51,7 +51,7 @@ public class FailedPubsubMessageToPubsubTopicFn
PubsubMessage pubsubMessage = failsafeElement.getOriginalPayload();
String message =
pubsubMessage.getPayload().length > 0
- ? new String(pubsubMessage.getPayload())
+ ? new String(pubsubMessage.getPayload(), StandardCharsets.UTF_8)
: pubsubMessage.getAttributeMap().toString();
// Format the timestamp for insertion
diff --git a/v2/googlecloud-to-elasticsearch/src/main/java/com/google/cloud/teleport/v2/elasticsearch/transforms/ProcessFailsafePubSubFn.java b/v2/googlecloud-to-elasticsearch/src/main/java/com/google/cloud/teleport/v2/elasticsearch/transforms/ProcessFailsafePubSubFn.java
index 6247dc10..2ac49e9e 100644
--- a/v2/googlecloud-to-elasticsearch/src/main/java/com/google/cloud/teleport/v2/elasticsearch/transforms/ProcessFailsafePubSubFn.java
+++ b/v2/googlecloud-to-elasticsearch/src/main/java/com/google/cloud/teleport/v2/elasticsearch/transforms/ProcessFailsafePubSubFn.java
@@ -20,6 +20,7 @@ import com.google.cloud.teleport.v2.values.FailsafeElement;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
+import java.nio.charset.StandardCharsets;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubMessage;
import org.apache.beam.sdk.metrics.Counter;
import org.apache.beam.sdk.metrics.Metrics;
@@ -54,7 +55,9 @@ public class ProcessFailsafePubSubFn
try {
if (pubsubMessage.getPayload().length > 0) {
- messageObject = gson.fromJson(new String(pubsubMessage.getPayload()), JsonObject.class);
+ messageObject =
+ gson.fromJson(
+ new String(pubsubMessage.getPayload(), StandardCharsets.UTF_8), JsonObject.class);
}
// If message attributes are present they will be serialized along with the message payload
diff --git a/v2/googlecloud-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/templates/TextIOToBigQuery.java b/v2/googlecloud-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/templates/TextIOToBigQuery.java
index 592e4b66..711dae83 100644
--- a/v2/googlecloud-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/templates/TextIOToBigQuery.java
+++ b/v2/googlecloud-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/templates/TextIOToBigQuery.java
@@ -30,6 +30,7 @@ import com.google.cloud.teleport.v2.utils.BigQueryIOUtils;
import com.google.common.annotations.VisibleForTesting;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
@@ -270,7 +271,8 @@ public class TextIOToBigQuery {
FileSystems.open(FileSystems.matchNewResource(pathToJson, false));
String json =
new String(
- StreamUtils.getBytesWithoutClosing(Channels.newInputStream(readableByteChannel)));
+ StreamUtils.getBytesWithoutClosing(Channels.newInputStream(readableByteChannel)),
+ StandardCharsets.UTF_8);
return new JSONObject(json);
} catch (Exception e) {
throw new RuntimeException(e);
diff --git a/v2/googlecloud-to-googlecloud/src/test/java/com/google/cloud/teleport/v2/templates/SpannerChangeStreamsToPubSubTest.java b/v2/googlecloud-to-googlecloud/src/test/java/com/google/cloud/teleport/v2/templates/SpannerChangeStreamsToPubSubTest.java
index 342f0d3b..506754b7 100644
--- a/v2/googlecloud-to-googlecloud/src/test/java/com/google/cloud/teleport/v2/templates/SpannerChangeStreamsToPubSubTest.java
+++ b/v2/googlecloud-to-googlecloud/src/test/java/com/google/cloud/teleport/v2/templates/SpannerChangeStreamsToPubSubTest.java
@@ -28,6 +28,7 @@ import com.google.cloud.teleport.v2.spanner.SpannerServerResource;
import com.google.cloud.teleport.v2.spanner.SpannerTestHelper;
import com.google.cloud.teleport.v2.transforms.FileFormatFactorySpannerChangeStreamsToPubSub;
import com.google.gson.Gson;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@@ -705,7 +706,7 @@ public final class SpannerChangeStreamsToPubSubTest extends SpannerTestHelper {
@Override
public String apply(PubsubMessage message) {
- return new String(message.getPayload());
+ return new String(message.getPayload(), StandardCharsets.UTF_8);
}
}
}
diff --git a/v2/pubsub-to-mongodb/src/main/java/com/google/cloud/teleport/v2/templates/PubSubToMongoDB.java b/v2/pubsub-to-mongodb/src/main/java/com/google/cloud/teleport/v2/templates/PubSubToMongoDB.java
index 1e2db824..028275b2 100644
--- a/v2/pubsub-to-mongodb/src/main/java/com/google/cloud/teleport/v2/templates/PubSubToMongoDB.java
+++ b/v2/pubsub-to-mongodb/src/main/java/com/google/cloud/teleport/v2/templates/PubSubToMongoDB.java
@@ -468,7 +468,9 @@ public class PubSubToMongoDB {
try {
if (pubsubMessage.getPayload().length > 0) {
- messageObject = gson.fromJson(new String(pubsubMessage.getPayload()), JsonObject.class);
+ messageObject =
+ gson.fromJson(
+ new String(pubsubMessage.getPayload(), StandardCharsets.UTF_8), JsonObject.class);
}
// If message attributes are present they will be serialized along with the message payload | ['v2/googlecloud-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/templates/TextIOToBigQuery.java', 'v2/googlecloud-to-googlecloud/src/test/java/com/google/cloud/teleport/v2/templates/SpannerChangeStreamsToPubSubTest.java', 'v1/src/main/java/com/google/cloud/teleport/templates/common/ErrorConverters.java', 'v2/googlecloud-to-elasticsearch/src/main/java/com/google/cloud/teleport/v2/elasticsearch/transforms/FailedPubsubMessageToPubsubTopicFn.java', 'v2/pubsub-to-mongodb/src/main/java/com/google/cloud/teleport/v2/templates/PubSubToMongoDB.java', 'v2/googlecloud-to-elasticsearch/src/main/java/com/google/cloud/teleport/v2/elasticsearch/transforms/ProcessFailsafePubSubFn.java', 'v2/common/src/main/java/com/google/cloud/teleport/v2/transforms/ErrorConverters.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 5,731,735 | 1,214,849 | 151,896 | 1,032 | 1,255 | 222 | 19 | 6 | 639 | 66 | 157 | 25 | 1 | 1 | 1970-01-01T00:28:08 | 1,005 | Java | {'Java': 9158571, 'Go': 39852, 'JavaScript': 34656, 'Python': 10437, 'Dockerfile': 925, 'PureBasic': 35} | Apache License 2.0 |
1,448 | googlecloudplatform/dataflowtemplates/469/464 | googlecloudplatform | dataflowtemplates | https://github.com/GoogleCloudPlatform/DataflowTemplates/issues/464 | https://github.com/GoogleCloudPlatform/DataflowTemplates/pull/469 | https://github.com/GoogleCloudPlatform/DataflowTemplates/pull/469 | 1 | fixes | [Bug]: Datastream to BigQuery MERGE not running in correct project | ### Related Template(s)
Datastream to BigQuery
### What happened?
I'm running this template using a different BigQuery project than the Datastream/GCS/Dataflow resources. I'm supplying it as the `--outputProjectId` value and data is flowing into my temporary table, just the MERGE fails:
```
2022-09-09T20:40:23.171ZMerge Job Failed: Exception: com.google.cloud.bigquery.BigQueryException: Access Denied: Project <dataflowproject>: User does not have bigquery.jobs.create permission in project <dataflowproject>.
```
I'm not super familiar with the code, but should this [line](https://github.com/GoogleCloudPlatform/DataflowTemplates/blob/4a0664a0d7559ba81353f48dc1cd7e2e928a3fd1/v2/datastream-to-bigquery/src/main/java/com/google/cloud/teleport/v2/templates/DataStreamToBigQuery.java#L422) use the `options.getOutputProjectId()` value instead of the variable?
### Beam Version
Newer than 2.35.0
### Relevant log output
_No response_ | 9ad9285922b1911b2dda75bea4ece13ed75ef53b | a3e2433dbc5a00c142d143f99faa8348cb38ea6b | https://github.com/googlecloudplatform/dataflowtemplates/compare/9ad9285922b1911b2dda75bea4ece13ed75ef53b...a3e2433dbc5a00c142d143f99faa8348cb38ea6b | diff --git a/v2/common/src/main/java/com/google/cloud/teleport/v2/cdc/merge/BigQueryMerger.java b/v2/common/src/main/java/com/google/cloud/teleport/v2/cdc/merge/BigQueryMerger.java
index 083478a5..ad6e0781 100644
--- a/v2/common/src/main/java/com/google/cloud/teleport/v2/cdc/merge/BigQueryMerger.java
+++ b/v2/common/src/main/java/com/google/cloud/teleport/v2/cdc/merge/BigQueryMerger.java
@@ -171,7 +171,11 @@ public class BigQueryMerger extends PTransform<PCollection<MergeInfo>, PCollecti
@Setup
public void setUp() {
if (bigQueryClient == null) {
- bigQueryClient = BigQueryOptions.getDefaultInstance().getService();
+ BigQueryOptions.Builder optionsBuilder = BigQueryOptions.newBuilder();
+ if (mergeConfiguration.projectId() != null && !mergeConfiguration.projectId().isEmpty()) {
+ optionsBuilder = optionsBuilder.setProjectId(mergeConfiguration.projectId());
+ }
+ bigQueryClient = optionsBuilder.build().getService();
}
}
diff --git a/v2/common/src/main/java/com/google/cloud/teleport/v2/cdc/merge/MergeConfiguration.java b/v2/common/src/main/java/com/google/cloud/teleport/v2/cdc/merge/MergeConfiguration.java
index f796823a..14914ab3 100644
--- a/v2/common/src/main/java/com/google/cloud/teleport/v2/cdc/merge/MergeConfiguration.java
+++ b/v2/common/src/main/java/com/google/cloud/teleport/v2/cdc/merge/MergeConfiguration.java
@@ -19,6 +19,7 @@ import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Prec
import com.google.auto.value.AutoValue;
import java.io.Serializable;
+import javax.annotation.Nullable;
import org.joda.time.Duration;
/** Class {@link MergeConfiguration}. */
@@ -64,6 +65,9 @@ public abstract class MergeConfiguration implements Serializable {
// BigQuery-specific properties
public static final String BIGQUERY_QUOTE_CHARACTER = "`";
+ @Nullable
+ public abstract String projectId();
+
public abstract String quoteCharacter();
public abstract Boolean supportPartitionedTables();
@@ -82,6 +86,10 @@ public abstract class MergeConfiguration implements Serializable {
return MergeConfiguration.builder().setQuoteCharacter(BIGQUERY_QUOTE_CHARACTER).build();
}
+ public MergeConfiguration withProjectId(String projectId) {
+ return this.toBuilder().setProjectId(projectId).build();
+ }
+
public MergeConfiguration withPartitionRetention(int partitionRetention) {
checkArgument(partitionRetention > 0, "partitionRetention must be greater than 0");
return this.toBuilder().setPartitionRetention(Integer.valueOf(partitionRetention)).build();
@@ -115,6 +123,8 @@ public abstract class MergeConfiguration implements Serializable {
@AutoValue.Builder
abstract static class Builder {
+ abstract Builder setProjectId(String projectId);
+
abstract Builder setQuoteCharacter(String quote);
abstract Builder setSupportPartitionedTables(Boolean supportPartitionedTables);
diff --git a/v2/datastream-to-bigquery/src/main/java/com/google/cloud/teleport/v2/templates/DataStreamToBigQuery.java b/v2/datastream-to-bigquery/src/main/java/com/google/cloud/teleport/v2/templates/DataStreamToBigQuery.java
index b030e8ba..4096c287 100644
--- a/v2/datastream-to-bigquery/src/main/java/com/google/cloud/teleport/v2/templates/DataStreamToBigQuery.java
+++ b/v2/datastream-to-bigquery/src/main/java/com/google/cloud/teleport/v2/templates/DataStreamToBigQuery.java
@@ -571,6 +571,7 @@ public class DataStreamToBigQuery {
"BigQuery Merge/Merge into Replica Tables",
BigQueryMerger.of(
MergeConfiguration.bigQueryConfiguration()
+ .withProjectId(bigqueryProjectId)
.withMergeWindowDuration(
Duration.standardMinutes(options.getMergeFrequencyMinutes()))
.withMergeConcurrency(options.getMergeConcurrency()) | ['v2/common/src/main/java/com/google/cloud/teleport/v2/cdc/merge/BigQueryMerger.java', 'v2/common/src/main/java/com/google/cloud/teleport/v2/cdc/merge/MergeConfiguration.java', 'v2/datastream-to-bigquery/src/main/java/com/google/cloud/teleport/v2/templates/DataStreamToBigQuery.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 6,066,423 | 1,284,319 | 159,928 | 935 | 751 | 135 | 17 | 3 | 949 | 92 | 244 | 21 | 1 | 1 | 1970-01-01T00:27:43 | 1,005 | Java | {'Java': 9158571, 'Go': 39852, 'JavaScript': 34656, 'Python': 10437, 'Dockerfile': 925, 'PureBasic': 35} | Apache License 2.0 |
259 | apache/jena/1935/1934 | apache | jena | https://github.com/apache/jena/issues/1934 | https://github.com/apache/jena/pull/1935 | https://github.com/apache/jena/pull/1935 | 1 | resolved | NaN should not be same-value NaN | ### Version
4.8.0
### What happened?
sameValue(NaN, NaN) is false.
notSameValue(NaN, NaN) is true.
### Relevant output and stacktrace
_No response_
### Are you interested in making a pull request?
Yes | 5ac50472cc8e9e93c4041fb1b30503d16617427f | 96d3a4b804f8bb10ec6a5b235b18937abf48962d | https://github.com/apache/jena/compare/5ac50472cc8e9e93c4041fb1b30503d16617427f...96d3a4b804f8bb10ec6a5b235b18937abf48962d | diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprNode.java b/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprNode.java
index bf70c052d5..26e89aca24 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprNode.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprNode.java
@@ -18,103 +18,107 @@
package org.apache.jena.sparql.expr;
-import java.util.Set ;
+import java.util.Set;
-import org.apache.jena.sparql.algebra.Op ;
-import org.apache.jena.sparql.core.Var ;
-import org.apache.jena.sparql.engine.binding.Binding ;
-import org.apache.jena.sparql.expr.nodevalue.XSDFuncOp ;
-import org.apache.jena.sparql.function.FunctionEnv ;
+import org.apache.jena.sparql.algebra.Op;
+import org.apache.jena.sparql.core.Var;
+import org.apache.jena.sparql.engine.binding.Binding;
+import org.apache.jena.sparql.expr.nodevalue.XSDFuncOp;
+import org.apache.jena.sparql.function.FunctionEnv;
import org.apache.jena.sparql.graph.NodeTransform;
-import org.apache.jena.sparql.sse.writers.WriterExpr ;
+import org.apache.jena.sparql.sse.writers.WriterExpr;
-/**
+/**
* A node that is a constraint expression that can be evaluated
* An {@link Expr} is already a Constraint - ExprNode is the base implementation
* of all {@link Expr} classes that provides the Constraint machinery.
*/
-
+
public abstract class ExprNode implements Expr
{
@Override
public boolean isSatisfied(Binding binding, FunctionEnv funcEnv) {
try {
- NodeValue v = eval(binding, funcEnv) ;
- boolean b = XSDFuncOp.booleanEffectiveValue(v) ;
- return b ;
+ NodeValue v = eval(binding, funcEnv);
+ boolean b = XSDFuncOp.booleanEffectiveValue(v);
+ return b;
}
- catch (ExprEvalException ex) {
- return false ;
+ catch (ExprEvalException ex) {
+ return false;
}
}
- public boolean isExpr() { return true ; }
- public final Expr getExpr() { return this ; }
-
+ public boolean isExpr() { return true; }
+ public final Expr getExpr() { return this; }
+
// --- interface Constraint
-
+
@Override
- public abstract NodeValue eval(Binding binding, FunctionEnv env) ;
-
+ public abstract NodeValue eval(Binding binding, FunctionEnv env);
+
@Override
- public final Set<Var> getVarsMentioned() { return ExprVars.getVarsMentioned(this) ; }
+ public final Set<Var> getVarsMentioned() { return ExprVars.getVarsMentioned(this); }
@Override
- public abstract int hashCode() ;
+ public abstract int hashCode();
+
@Override
public final boolean equals(Object other) {
- if ( other == null ) return false ;
- if ( this == other ) return true ;
- if ( ! ( other instanceof Expr ) ) return false ;
- return equals((Expr)other, false) ;
+ if ( other == null )
+ return false;
+ if ( this == other )
+ return true;
+ if ( !(other instanceof Expr) )
+ return false;
+ return equals((Expr)other, false);
}
-
+
@Override
public final boolean equalsBySyntax(Expr other) {
- if ( other == null ) return false ;
- if ( this == other ) return true ;
- return equals(other, true) ;
+ if ( other == null ) return false;
+ if ( this == other ) return true;
+ return equals(other, true);
}
-
+
@Override
- public abstract boolean equals(Expr other, boolean bySyntax) ;
-
- protected static NodeValue eval(Binding binding, FunctionEnv funcEnv, Expr expr) {
- if ( expr == null ) return null ;
- return expr.eval(binding, funcEnv) ;
+ public abstract boolean equals(Expr other, boolean bySyntax);
+
+ protected static NodeValue eval(Binding binding, FunctionEnv funcEnv, Expr expr) {
+ if ( expr == null ) return null;
+ return expr.eval(binding, funcEnv);
}
-
+
@Override
- final public Expr deepCopy() { return copySubstitute(null) ; }
-
+ final public Expr deepCopy() { return copySubstitute(null); }
+
@Override
- public abstract Expr copySubstitute(Binding binding) ;
-
+ public abstract Expr copySubstitute(Binding binding);
+
@Override
- public abstract Expr applyNodeTransform(NodeTransform transform) ;
-
+ public abstract Expr applyNodeTransform(NodeTransform transform);
+
// ---- Default implementations
@Override
- public boolean isVariable() { return false ; }
+ public boolean isVariable() { return false; }
@Override
- public String getVarName() { return null ; } //throw new ExprException("Expr.getVarName called on non-variable") ; }
+ public String getVarName() { return null; } //throw new ExprException("Expr.getVarName called on non-variable"); }
@Override
- public ExprVar getExprVar() { return null ; } //throw new ExprException("Expr.getVar called on non-variable") ; }
+ public ExprVar getExprVar() { return null; } //throw new ExprException("Expr.getVar called on non-variable"); }
@Override
- public Var asVar() { return null ; } //throw new ExprException("Expr.getVar called on non-variable") ; }
-
+ public Var asVar() { return null; } //throw new ExprException("Expr.getVar called on non-variable"); }
+
@Override
- public boolean isConstant() { return false ; }
+ public boolean isConstant() { return false; }
@Override
- public NodeValue getConstant() { return null ; } // throw new ExprException("Expr.getConstant called on non-constant") ; }
-
+ public NodeValue getConstant() { return null; } // throw new ExprException("Expr.getConstant called on non-constant"); }
+
@Override
- public boolean isFunction() { return false ; }
+ public boolean isFunction() { return false; }
@Override
- public ExprFunction getFunction() { return null ; }
+ public ExprFunction getFunction() { return null; }
- public boolean isGraphPattern() { return false ; }
- public Op getGraphPattern() { return null ; }
+ public boolean isGraphPattern() { return false; }
+ public Op getGraphPattern() { return null; }
@Override
- public String toString() { return WriterExpr.asString(this) ; }
+ public String toString() { return WriterExpr.asString(this); }
}
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValue.java b/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValue.java
index d323019e6c..826f96f8da 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValue.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValue.java
@@ -487,7 +487,7 @@ public abstract class NodeValue extends ExprNode
* the two NodeValues are known to be the same, else throw ExprEvalException
*/
public static boolean notSameValueAs(NodeValue nv1, NodeValue nv2) {
- return !sameValueAs(nv1, nv2);
+ return NodeValueCmp.notSameValueAs(nv1, nv2);
}
/** @deprecated Use {@link #sameValueAs(NodeValue, NodeValue)}. */
@@ -844,28 +844,25 @@ public abstract class NodeValue extends ExprNode
public final String asQuotedString()
{ return asQuotedString(new SerializationContext()) ; }
- public final String asQuotedString(SerializationContext context)
- {
+ public final String asQuotedString(SerializationContext context) {
// If possible, make a node and use that as the formatted output.
if ( node == null )
- node = asNode() ;
+ node = asNode();
if ( node != null )
- return FmtUtils.stringForNode(node, context) ;
- return toString() ;
+ return FmtUtils.stringForNode(node, context);
+ return toString();
}
- // Convert to a string - usually overridden.
- public String asString()
- {
+ // Convert to a string - usually overridden.
+ public String asString() {
// Do not call .toString()
- forceToNode() ;
- return NodeFunctions.str(node) ;
+ forceToNode();
+ return NodeFunctions.str(node);
}
@Override
- public int hashCode()
- {
- return asNode().hashCode() ;
+ public int hashCode() {
+ return asNode().hashCode();
}
@Override
@@ -873,7 +870,6 @@ public abstract class NodeValue extends ExprNode
if ( other == null ) return false ;
if ( this == other ) return true ;
// This is the equality condition Jena uses - lang tags are different by case.
-
if ( ! ( other instanceof NodeValue ) )
return false ;
NodeValue nv = (NodeValue)other ;
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValueCmp.java b/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValueCmp.java
index 9cf3993dc1..cfa40d2036 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValueCmp.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValueCmp.java
@@ -55,12 +55,10 @@ public class NodeValueCmp {
ValueSpace compType = NodeValue.classifyValueOp(nv1, nv2);
- if ( nv1 == nv2 )
- return true;
- if ( nv1.hasNode() && nv2.hasNode() ) {
- // Fast path - same RDF term => sameValue
- if ( nv1.getNode().equals(nv2.getNode()) )
- return true;
+ if ( nv1.equals(nv2) ) {
+ // Fast path - same RDF term => sameValue (except NaN).
+ if ( nv1.getNode() != null && nv2.getNode() != null && nv1.getNode().equals(nv2.asNode()) )
+ return sameExceptNaN(nv1, nv2);
}
// Special case - date/dateTime comparison is affected by timezones and may
@@ -152,6 +150,15 @@ public class NodeValueCmp {
throw new ARQInternalErrorException("sameValueAs failure " + nv1 + " and " + nv2);
}
+ // When nv1 and nv1 are known to be the sameTerm, including java ==
+ private static boolean sameExceptNaN(NodeValue nv1, NodeValue nv2) {
+ if ( nv1.isDouble() && Double.isNaN(nv1.getDouble()) )
+ return false;
+ if ( nv1.isFloat() && Float.isNaN(nv1.getFloat()) )
+ return false;
+ return true;
+ }
+
/** Worker for sameAs. */
private static boolean nSameValueAs(Node n1, Node n2) {
NodeValue nv1 = NodeValue.makeNode(n1);
@@ -171,8 +178,9 @@ public class NodeValueCmp {
* Return true if the two NodeValues are known to be different, return false if
* the two NodeValues are known to be the same, else throw ExprEvalException
*/
- /*package*/private static boolean notSameValueAs(NodeValue nv1, NodeValue nv2) {
- return !sameValueAs(nv1, nv2);
+ /*package*/ static boolean notSameValueAs(NodeValue nv1, NodeValue nv2) {
+ // Works for NaN as well.
+ return !sameValueAs(nv1, nv2);
}
// ==== Compare
diff --git a/jena-arq/src/test/java/org/apache/jena/sparql/expr/LibTestExpr.java b/jena-arq/src/test/java/org/apache/jena/sparql/expr/LibTestExpr.java
index 7b01f8a38b..4a57eb62b0 100644
--- a/jena-arq/src/test/java/org/apache/jena/sparql/expr/LibTestExpr.java
+++ b/jena-arq/src/test/java/org/apache/jena/sparql/expr/LibTestExpr.java
@@ -92,6 +92,16 @@ public class LibTestExpr {
assertTrue("Expected = " + expected + " : Actual = " + actual, sameValueSameDatatype(expected, actual));
}
+ public static void testIsNaN(String exprStr) {
+ testSameObject(exprStr, NodeValue.nvNaN);
+ }
+
+ public static void testSameObject(String exprStr, NodeValue expected) {
+ Expr expr = parse(exprStr);
+ NodeValue actual = expr.eval(null, LibTestExpr.createTest());
+ assertTrue("Expected = " + expected + " : Actual = " + actual, expected.equals(actual));
+ }
+
private static boolean sameValueSameDatatype(NodeValue nv1, NodeValue nv2) {
if ( ! NodeValue.sameValueAs(nv1, nv2) )
return false;
diff --git a/jena-arq/src/test/java/org/apache/jena/sparql/expr/TestExpressionsMath.java b/jena-arq/src/test/java/org/apache/jena/sparql/expr/TestExpressionsMath.java
index c323bb4993..32cb43375c 100644
--- a/jena-arq/src/test/java/org/apache/jena/sparql/expr/TestExpressionsMath.java
+++ b/jena-arq/src/test/java/org/apache/jena/sparql/expr/TestExpressionsMath.java
@@ -36,7 +36,7 @@ public class TestExpressionsMath
@Test public void exp_04() { test("math:exp(1e0/0)", "'INF'^^xsd:double") ; }
@Test public void exp_05() { test("math:exp('INF'^^xsd:double)", "'INF'^^xsd:double") ; }
@Test public void exp_06() { test("math:exp('-INF'^^xsd:double)", "'0.0e0'^^xsd:double") ; }
- @Test public void exp_07() { test("math:exp('NaN'^^xsd:double)", "'NaN'^^xsd:double") ; }
+ @Test public void exp_07() { testIsNaN("math:exp('NaN'^^xsd:double)") ; }
@Test public void exp10_01() { test("math:exp10(2)", "100") ; }
@Test public void exp10_02() { testDouble("math:exp10(-1)", 0.1, 0.00001) ; }
@@ -50,7 +50,7 @@ public class TestExpressionsMath
@Test public void log_04() { test("math:log(0)", "'-INF'^^xsd:double") ; }
@Test public void log_05() { test("math:exp('INF'^^xsd:double)", "'INF'^^xsd:double") ; }
@Test public void log_06() { test("math:exp('-INF'^^xsd:double)", "'0.0e0'^^xsd:double") ; }
- @Test public void log_07() { test("math:exp('NaN'^^xsd:double)", "'NaN'^^xsd:double") ; }
+ @Test public void log_07() { testIsNaN("math:exp('NaN'^^xsd:double)") ; }
@Test public void pow_01() { test("math:pow(2,2)", "4") ; }
@Test public void pow_02() { testDouble("math:pow(2,-2)", 0.25, 0.00001) ; }
@@ -62,19 +62,19 @@ public class TestExpressionsMath
@Test public void pow_13() { test("math:pow('INF'^^xsd:double,0)", "'1.0e0'^^xsd:double") ; }
@Test public void pow_14() { test("math:pow('-INF'^^xsd:double, 0)", "'1.0e0'^^xsd:double") ; }
- @Test public void pow_15() { test("math:pow('NaN'^^xsd:double, 1)", "'NaN'^^xsd:double") ; }
- @Test public void pow_16() { test("math:pow(1, 'NaN'^^xsd:double)", "'NaN'^^xsd:double") ; }
+ @Test public void pow_15() { testIsNaN("math:pow('NaN'^^xsd:double, 1)") ; }
+ @Test public void pow_16() { testIsNaN("math:pow(1, 'NaN'^^xsd:double)") ; }
@Test public void sqrt_01() { test("math:sqrt(1)", "'1.0e0'^^xsd:double") ; }
@Test public void sqrt_02() { testDouble("math:sqrt(2)", Math.sqrt(2), 0.000001) ; }
- @Test public void sqrt_03() { test("math:sqrt(-2)", "'NaN'^^xsd:double") ; }
+ @Test public void sqrt_03() { testIsNaN("math:sqrt(-2)"); }
@Test(expected=ARQException.class)
public void sqrt_04() { test("math:sqrt('TWO')", "'dummy'") ; }
@Test public void sqrt_10() { test("math:sqrt('INF'^^xsd:double)", "'INF'^^xsd:double") ; }
- @Test public void sqrt_11() { test("math:sqrt('-INF'^^xsd:double)", "'NaN'^^xsd:double") ; }
- @Test public void sqrt_12() { test("math:sqrt('NaN'^^xsd:double)", "'NaN'^^xsd:double") ; }
+ @Test public void sqrt_11() { testIsNaN("math:sqrt('-INF'^^xsd:double)") ; }
+ @Test public void sqrt_12() { testIsNaN("math:sqrt('NaN'^^xsd:double)") ; }
// 4.8.7 math:sqrt
// 4.8.8 math:sin
diff --git a/jena-arq/src/test/java/org/apache/jena/sparql/expr/TestLeviathanFunctions.java b/jena-arq/src/test/java/org/apache/jena/sparql/expr/TestLeviathanFunctions.java
index 6bbdda0556..0e3b6ed447 100644
--- a/jena-arq/src/test/java/org/apache/jena/sparql/expr/TestLeviathanFunctions.java
+++ b/jena-arq/src/test/java/org/apache/jena/sparql/expr/TestLeviathanFunctions.java
@@ -21,6 +21,7 @@ package org.apache.jena.sparql.expr;
import static org.apache.jena.sparql.expr.LibTestExpr.test ;
import static org.apache.jena.sparql.expr.LibTestExpr.testDouble ;
import static org.apache.jena.sparql.expr.LibTestExpr.testError ;
+import static org.junit.Assert.assertTrue;
import org.apache.jena.sparql.util.NodeFactoryExtra ;
import org.junit.AfterClass;
@@ -130,7 +131,9 @@ public class TestLeviathanFunctions {
@Test
public void log_03() {
- test("lfn:log(-1)", NodeFactoryExtra.doubleToNode(Double.NaN));
+ NodeValue actual = LibTestExpr.eval("lfn:log(-1)");
+ // Test the object, not the value.
+ assertTrue(NodeValue.nvNaN.equals(actual));
}
@Test
diff --git a/jena-arq/src/test/java/org/apache/jena/sparql/expr/TestNodeValue.java b/jena-arq/src/test/java/org/apache/jena/sparql/expr/TestNodeValue.java
index 8da966aa31..ff2134a1d4 100644
--- a/jena-arq/src/test/java/org/apache/jena/sparql/expr/TestNodeValue.java
+++ b/jena-arq/src/test/java/org/apache/jena/sparql/expr/TestNodeValue.java
@@ -1067,6 +1067,51 @@ public class TestNodeValue
assertFalse("Different values - notNotSame (" + nv1 + "," + nv3 + ")", NodeValue.notSameValueAs(nv1, nv3));
}
+ @Test
+ public void testSameValueNaN_double_1() {
+ NodeValue nv1 = NodeValue.makeNode("NaN", XSDDatatype.XSDdouble);
+ NodeValue nv2 = NodeValue.makeNode("NaN", XSDDatatype.XSDdouble);
+ assertEquals(nv1, nv2);
+ assertFalse(NodeValue.sameValueAs(nv1, nv2));
+ assertTrue(NodeValue.notSameValueAs(nv1, nv2));
+ }
+
+ @Test
+ public void testSameValueNaN_float_1() {
+ NodeValue nv1 = NodeValue.makeNode("NaN", XSDDatatype.XSDfloat);
+ NodeValue nv2 = NodeValue.makeNode("NaN", XSDDatatype.XSDfloat);
+ assertEquals(nv1, nv2);
+ assertFalse(NodeValue.sameValueAs(nv1, nv2));
+ assertTrue(NodeValue.notSameValueAs(nv1, nv2));
+ // NaN is weird.
+ assertFalse(NodeValue.sameValueAs(nv1, nv1));
+ assertTrue(NodeValue.notSameValueAs(nv1, nv1));
+ }
+
+ @Test
+ public void testSameValueNaN_double_2() {
+ NodeValue nv1 = NodeValue.makeDouble(Double.NaN);
+ NodeValue nv2 = NodeValue.makeDouble(Double.NaN);
+ assertEquals(nv1, nv2);
+ assertFalse(NodeValue.sameValueAs(nv1, nv2));
+ assertTrue(NodeValue.notSameValueAs(nv1, nv2));
+
+ assertFalse(NodeValue.sameValueAs(nv1, nv1));
+ assertTrue(NodeValue.notSameValueAs(nv1, nv1));
+ }
+
+ @Test
+ public void testSameValueNaN_float_2() {
+ NodeValue nv1 = NodeValue.makeFloat(Float.NaN);
+ NodeValue nv2 = NodeValue.makeFloat(Float.NaN);
+ assertEquals(nv1, nv2);
+ assertFalse(NodeValue.sameValueAs(nv1, nv2));
+ assertTrue(NodeValue.notSameValueAs(nv1, nv2));
+
+ assertFalse(NodeValue.sameValueAs(nv1, nv1));
+ assertTrue(NodeValue.notSameValueAs(nv1, nv1));
+ }
+
@Test
public void testLang1() {
Node n1 = org.apache.jena.graph.NodeFactory.createLiteral("xyz", "en");
diff --git a/jena-arq/src/test/java/org/apache/jena/sparql/function/library/TestFnFunctionsString.java b/jena-arq/src/test/java/org/apache/jena/sparql/function/library/TestFnFunctionsString.java
index 67dce3e37f..af91d6ab0f 100644
--- a/jena-arq/src/test/java/org/apache/jena/sparql/function/library/TestFnFunctionsString.java
+++ b/jena-arq/src/test/java/org/apache/jena/sparql/function/library/TestFnFunctionsString.java
@@ -92,7 +92,7 @@ public class TestFnFunctionsString {
@Test public void exprStrNormalizeSpace0() { test("fn:normalize-space(' The wealthy curled darlings of our nation. ')",
NodeValue.makeString("The wealthy curled darlings of our nation.")) ; }
- @Test public void exprStrNormalizeSpace1() { test("fn:normalize-space('')",NodeValue.nvEmptyString) ; }
+ @Test public void exprStrNormalizeSpace1() { test("fn:normalize-space('')", NodeValue.nvEmptyString) ; }
@Test public void exprStrNormalizeSpace2() { test("fn:normalize-space(' Aaa ')",NodeValue.makeString("Aaa")) ; }
@Test public void exprStrNormalizeSpace3() { test("fn:normalize-space('A a a a a ')",NodeValue.makeString("A a a a a")) ; }
| ['jena-arq/src/test/java/org/apache/jena/sparql/expr/TestExpressionsMath.java', 'jena-arq/src/main/java/org/apache/jena/sparql/expr/ExprNode.java', 'jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValue.java', 'jena-arq/src/test/java/org/apache/jena/sparql/expr/TestLeviathanFunctions.java', 'jena-arq/src/test/java/org/apache/jena/sparql/function/library/TestFnFunctionsString.java', 'jena-arq/src/test/java/org/apache/jena/sparql/expr/TestNodeValue.java', 'jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValueCmp.java', 'jena-arq/src/test/java/org/apache/jena/sparql/expr/LibTestExpr.java'] | {'.java': 8} | 8 | 8 | 0 | 0 | 8 | 26,223,436 | 5,993,471 | 743,904 | 4,689 | 7,354 | 1,648 | 166 | 3 | 216 | 31 | 57 | 20 | 0 | 0 | 1970-01-01T00:28:08 | 975 | Java | {'Java': 37296473, 'Shell': 270724, 'Ruby': 216471, 'Vue': 104500, 'Lex': 82672, 'JavaScript': 81879, 'HTML': 66939, 'XSLT': 65126, 'Perl': 34501, 'Haml': 30030, 'Batchfile': 25854, 'C++': 5877, 'SCSS': 4242, 'Thrift': 3755, 'Dockerfile': 3528, 'AspectJ': 3446, 'CSS': 3241, 'Elixir': 2548, 'Python': 416, 'Makefile': 198} | Apache License 2.0 |
260 | apache/jena/1903/1902 | apache | jena | https://github.com/apache/jena/issues/1902 | https://github.com/apache/jena/pull/1903 | https://github.com/apache/jena/pull/1903 | 1 | fixes | HttpLib throws NullPointerException if body is null. | ### Version
4.7.0
### What happened?
This bug not only affect 4.7 but also 4.8 and the main branch.
Executing a certain query results in a httpStatusCode in the range of 400 to 499. This results in the call of the [exception()](https://github.com/apache/jena/blob/main/jena-arq/src/main/java/org/apache/jena/http/HttpLib.java#L233) method which expects a response body in [line 241](https://github.com/apache/jena/blob/main/jena-arq/src/main/java/org/apache/jena/http/HttpLib.java#L241). However the body is null which results in the _NullPointerException_ in the attached stacktrace.
### Relevant output and stacktrace
```shell
2023-04-13 16:27:33,289 : ERROR : KNIME-Worker-1-SPARQL Query 3:1 : : Node : SPARQL Query : 3:1 : Execute failed: ("TripleStoreException"): null
org.knime.semanticweb.utility.TripleStoreException
at org.knime.semanticweb.utility.SemanticWebUtility.executeQuery(SemanticWebUtility.java:405)
at org.knime.semanticweb.nodes.query.SPARQLQueryNodeModel.run(SPARQLQueryNodeModel.java:170)
at org.knime.semanticweb.nodes.query.SPARQLQueryNodeModel.execute(SPARQLQueryNodeModel.java:203)
at org.knime.core.node.NodeModel.executeModel(NodeModel.java:549)
at org.knime.core.node.Node.invokeFullyNodeModelExecute(Node.java:1267)
at org.knime.core.node.Node.execute(Node.java:1041)
at org.knime.core.node.workflow.NativeNodeContainer.performExecuteNode(NativeNodeContainer.java:595)
at org.knime.core.node.exec.LocalNodeExecutionJob.mainExecute(LocalNodeExecutionJob.java:98)
at org.knime.core.node.workflow.NodeExecutionJob.internalRun(NodeExecutionJob.java:201)
at org.knime.core.node.workflow.NodeExecutionJob.run(NodeExecutionJob.java:117)
at org.knime.core.util.ThreadUtils$RunnableWithContextImpl.runWithContext(ThreadUtils.java:367)
at org.knime.core.util.ThreadUtils$RunnableWithContext.run(ThreadUtils.java:221)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
at org.knime.core.util.ThreadPool$MyFuture.run(ThreadPool.java:123)
at org.knime.core.util.ThreadPool$Worker.run(ThreadPool.java:246)
Caused by: java.lang.NullPointerException
at java.base/java.io.Reader.<init>(Unknown Source)
at java.base/java.io.InputStreamReader.<init>(Unknown Source)
at org.apache.jena.atlas.io.IO.asUTF8(IO.java:207)
at org.apache.jena.atlas.io.IO.readWholeFileAsUTF8(IO.java:456)
at org.apache.jena.http.HttpLib.exception(HttpLib.java:241)
at org.apache.jena.http.HttpLib.handleHttpStatusCode(HttpLib.java:173)
at org.apache.jena.sparql.exec.http.QueryExecHTTP.executeQuery(QueryExecHTTP.java:546)
at org.apache.jena.sparql.exec.http.QueryExecHTTP.execRowSet(QueryExecHTTP.java:172)
at org.apache.jena.sparql.exec.http.QueryExecHTTP.select(QueryExecHTTP.java:163)
at org.apache.jena.sparql.exec.QueryExecutionAdapter.execSelect(QueryExecutionAdapter.java:117)
at org.knime.semanticweb.utility.SemanticWebUtility.executeQuery(SemanticWebUtility.java:396)
... 15 more
```
### Are you interested in making a pull request?
Maybe | ba8b2b7ed07912e7e11819715c3274ec7b0c0e59 | 25969e433a4064a38639061fffcd4d6c73882364 | https://github.com/apache/jena/compare/ba8b2b7ed07912e7e11819715c3274ec7b0c0e59...25969e433a4064a38639061fffcd4d6c73882364 | diff --git a/jena-arq/src/main/java/org/apache/jena/http/HttpLib.java b/jena-arq/src/main/java/org/apache/jena/http/HttpLib.java
index 96099669fb..5a16f13b41 100644
--- a/jena-arq/src/main/java/org/apache/jena/http/HttpLib.java
+++ b/jena-arq/src/main/java/org/apache/jena/http/HttpLib.java
@@ -232,9 +232,9 @@ public class HttpLib {
*/
static HttpException exception(HttpResponse<InputStream> response, int httpStatusCode) {
URI uri = response.request().uri();
- //long length = HttpLib.getContentLength(response);
- // Not critical path code. Read body regardless.
InputStream in = response.body();
+ if ( in == null )
+ return new HttpException(httpStatusCode, HttpSC.getMessage(httpStatusCode));
try {
String msg;
try {
diff --git a/jena-arq/src/main/java/org/apache/jena/riot/other/G.java b/jena-arq/src/main/java/org/apache/jena/riot/other/G.java
index bac5b2bc68..9becc261ad 100644
--- a/jena-arq/src/main/java/org/apache/jena/riot/other/G.java
+++ b/jena-arq/src/main/java/org/apache/jena/riot/other/G.java
@@ -941,7 +941,6 @@ public class G {
// Predicate<Triple> predicate = (t) -> sameTermMatch(o, t.getObject()) ;
// iter = iter.filterKeep(predicate) ;
// }
-
}
/**
@@ -963,11 +962,14 @@ public class G {
public static boolean sameTermMatch(Node match, Node data) {
if ( isNullOrAny(match) )
return true;
+ if ( ! match.isLiteral() )
+ // Only literals have values
+ return match.equals(data);
// Allow for case-insensitive language tag comparison.
if ( ! Util.isLangString(data) || ! Util.isLangString(match) )
// Any mix of node types except both strings with lang tags.
- return match.equals(data) ;
+ return match.equals(data);
// Both nodes with language tags : compare languages case insensitively.
String lex1 = match.getLiteralLexicalForm();
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/SystemARQ.java b/jena-arq/src/main/java/org/apache/jena/sparql/SystemARQ.java
index 17054964cd..4c10668c7f 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/SystemARQ.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/SystemARQ.java
@@ -50,7 +50,7 @@ public class SystemARQ
public static boolean ValueExtensions = true ;
/**
- * Under strict {@literal F&O}, dateTimes and dates with no timezone have one magically applied.
+ * Under strict {@literal F&O}, dateTimes and dates that have no timezone have one magically applied.
* This default timezone is implementation dependent and can lead to different answers
* to queries depending on the timezone. Normally, ARQ uses XMLSchema dateTime comparisons,
* which an yield "indeterminate", which in turn is an evaluation error.
@@ -58,7 +58,7 @@ public class SystemARQ
*/
public static boolean StrictDateTimeFO = false ;
- /** Whether support for roman numerals (datatype http://rome.example.org/Numeral).
+ /** Whether support for Roman numerals (datatype http://rome.example.org/Numeral).
* Mainly a test of datatype extension.
*/
public static boolean EnableRomanNumerals = true ;
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/exec/http/QueryExecHTTP.java b/jena-arq/src/main/java/org/apache/jena/sparql/exec/http/QueryExecHTTP.java
index bfa08bf570..616f379e97 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/exec/http/QueryExecHTTP.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/exec/http/QueryExecHTTP.java
@@ -246,6 +246,8 @@ public class QueryExecHTTP implements QueryExec {
}
private String removeCharset(String contentType) {
+ if ( contentType == null )
+ return contentType;
int idx = contentType.indexOf(';');
if ( idx < 0 )
return contentType;
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValueCmp.java b/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValueCmp.java
index da6748be36..9cf3993dc1 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValueCmp.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValueCmp.java
@@ -226,7 +226,7 @@ public class NodeValueCmp {
// Must be same URI
if ( nv1.getDatatypeURI().equals(nv2.getDatatypeURI()) )
// Indeterminate possible.
- return XSDFuncOp.compareDateTimeXSD(nv1, nv2);
+ return XSDFuncOp.compareDateTime(nv1, nv2);
raise(new ExprNotComparableException("Can't compare (incompatible temporal value spaces) "+nv1+" and "+nv2)) ;
// case VSPACE_DURATION_DAYTIME:
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/XSDFuncOp.java b/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/XSDFuncOp.java
index ce5c1d17a7..c1e5a7609d 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/XSDFuncOp.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/XSDFuncOp.java
@@ -1141,14 +1141,13 @@ public class XSDFuncOp
// "Comparison operators on xs:date, xs:gYearMonth and xs:gYear compare their
// starting instants. These xs:dateTime values are calculated as described
// below."
- if ( SystemARQ.StrictDateTimeFO )
+ if ( SystemARQ.StrictDateTimeFO )
return compareDateTimeFO(nv1, nv2) ;
- return compareDateTimeXSD(nv1, nv2); //getXMLGregorianCalendarXSD(nv1), getXMLGregorianCalendarXSD(nv2)) ;
+ return compareDateTimeXSD(nv1, nv2);
}
/** Compare two date/times by XSD rules (dateTimes, one with and one without timezone can be indeterminate) */
public static int compareDateTimeXSD(NodeValue nv1, NodeValue nv2) {
-
XMLGregorianCalendar dt1 = getXMLGregorianCalendarXSD(nv1);
XMLGregorianCalendar dt2 = getXMLGregorianCalendarXSD(nv2);
int x = compareDateTime(dt1, dt2) ;
@@ -1669,7 +1668,6 @@ public class XSDFuncOp
return XSDDuration.durationCompare(duration1, duration2);
}
-
public static final String implicitTimezoneStr = "Z" ;
private static final NodeValue implicitTimezone_ = NodeValue.makeNode("PT0S", XSDDatatype.XSDdayTimeDuration);
diff --git a/jena-cmds/src/main/java/arq/qexpr.java b/jena-cmds/src/main/java/arq/qexpr.java
index fb46163c00..5b66138a23 100644
--- a/jena-cmds/src/main/java/arq/qexpr.java
+++ b/jena-cmds/src/main/java/arq/qexpr.java
@@ -64,9 +64,9 @@ public class qexpr
if ( ex.getCause() != null )
ex.getCause().printStackTrace(System.err) ;
}
-
+
}
-
+
public static void execAndReturn(String... argv)
{
try {
@@ -80,21 +80,21 @@ public class qexpr
ex.getCause().printStackTrace(System.err) ;
}
}
-
+
public static void main2(String... argv)
{
-
+
CmdLineArgs cl = new CmdLineArgs(argv) ;
-
+
ArgDecl helpDecl = new ArgDecl(ArgDecl.NoValue, "h", "help") ;
cl.add(helpDecl) ;
-
+
ArgDecl verboseDecl = new ArgDecl(ArgDecl.NoValue, "v", "verbose") ;
cl.add(verboseDecl) ;
-
+
ArgDecl versionDecl = new ArgDecl(ArgDecl.NoValue, "ver", "version", "V") ;
cl.add(versionDecl) ;
-
+
ArgDecl quietDecl = new ArgDecl(ArgDecl.NoValue, "q", "quiet") ;
cl.add(quietDecl) ;
@@ -103,7 +103,7 @@ public class qexpr
ArgDecl strictDecl = new ArgDecl(ArgDecl.NoValue, "strict") ;
cl.add(strictDecl) ;
-
+
ArgDecl printDecl = new ArgDecl(ArgDecl.HasValue, "print") ;
cl.add(printDecl) ;
@@ -121,23 +121,23 @@ public class qexpr
usage() ;
throw new TerminationException(0) ;
}
-
+
if ( cl.contains(versionDecl) )
{
System.out.println("ARQ Version: "+ARQ.VERSION+" (Jena: "+Jena.VERSION+")") ;
throw new TerminationException(0) ;
}
-
+
// ==== General things
boolean verbose = cl.contains(verboseDecl) ;
boolean quiet = cl.contains(quietDecl) ;
if ( cl.contains(strictDecl) )
ARQ.setStrictMode() ;
-
+
boolean actionCopySubstitute = cl.contains(reduceDecl) ;
boolean actionPrintPrefix = false ;
- boolean actionPrintSPARQL = false ;
+ boolean actionPrintSPARQL = false ;
boolean actionPrint = cl.contains(printDecl) ;
for ( String v : cl.getValues( printDecl ) )
@@ -158,12 +158,12 @@ public class qexpr
}
// ==== Do it
-
+
for ( int i = 0 ; i < cl.getNumPositional() ; i++ )
{
String exprStr = cl.getPositionalArg(i) ;
exprStr = cl.indirect(exprStr) ;
-
+
try {
PrefixMapping pmap = PrefixMapping.Factory.create() ;
pmap.setNsPrefixes(ARQConstants.getGlobalPrefixMap()) ;
@@ -174,7 +174,7 @@ public class qexpr
if ( actionPrint )
{
IndentedWriter iOut = IndentedWriter.stdout;
-
+
if ( actionPrintSPARQL ) {
ExprUtils.fmtSPARQL(iOut, expr);
iOut.ensureStartOfLine();
@@ -200,7 +200,7 @@ public class qexpr
{
// Default action
ARQ.getContext().set(ARQConstants.sysCurrentTime, NodeFactoryExtra.nowAsDateTime()) ;
- FunctionEnv env = new ExecutionContext(ARQ.getContext(), null, null, null) ;
+ FunctionEnv env = new ExecutionContext(ARQ.getContext(), null, null, null) ;
NodeValue r = expr.eval(null, env) ;
//System.out.println(r.asQuotedString()) ;
Node n = r.asNode() ;
@@ -209,6 +209,8 @@ public class qexpr
}
} catch (ExprEvalException ex)
{
+ ex.printStackTrace();
+
System.out.println("Exception: "+ex.getMessage()) ;
throw new TerminationException(2) ;
}
@@ -219,9 +221,9 @@ public class qexpr
}
}
}
-
+
static void usage() { usage(System.out) ; }
-
+
static void usage(java.io.PrintStream out)
{
out.println("Usage: [--print=[prefix|expr]] expression") ; | ['jena-arq/src/main/java/org/apache/jena/riot/other/G.java', 'jena-arq/src/main/java/org/apache/jena/sparql/expr/nodevalue/XSDFuncOp.java', 'jena-arq/src/main/java/org/apache/jena/sparql/exec/http/QueryExecHTTP.java', 'jena-arq/src/main/java/org/apache/jena/sparql/SystemARQ.java', 'jena-cmds/src/main/java/arq/qexpr.java', 'jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValueCmp.java', 'jena-arq/src/main/java/org/apache/jena/http/HttpLib.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 26,040,521 | 5,953,778 | 738,502 | 4,646 | 1,810 | 369 | 64 | 7 | 3,240 | 168 | 801 | 49 | 2 | 1 | 1970-01-01T00:28:06 | 975 | Java | {'Java': 37296473, 'Shell': 270724, 'Ruby': 216471, 'Vue': 104500, 'Lex': 82672, 'JavaScript': 81879, 'HTML': 66939, 'XSLT': 65126, 'Perl': 34501, 'Haml': 30030, 'Batchfile': 25854, 'C++': 5877, 'SCSS': 4242, 'Thrift': 3755, 'Dockerfile': 3528, 'AspectJ': 3446, 'CSS': 3241, 'Elixir': 2548, 'Python': 416, 'Makefile': 198} | Apache License 2.0 |
261 | apache/jena/1831/1830 | apache | jena | https://github.com/apache/jena/issues/1830 | https://github.com/apache/jena/pull/1831 | https://github.com/apache/jena/pull/1831 | 1 | resolved | Fuseki/webapp writes the configuration file with unnecessary additional triples | ### Version
4.7.0
### What happened?
When a new database is created in the UI, the configuration file is written to `run/configuration/<nbame>.ttl`. This contains the instantiated template but also additional triples (system definitions, some RDF statements). The latter are unnecessary.
### Relevant output and stacktrace
_No response_
### Are you interested in making a pull request?
Yes | ef902284ede904adc1a132e829de16c4447cd487 | 7e347a574a579a24a6eaf6f7f474983c4b3274b3 | https://github.com/apache/jena/compare/ef902284ede904adc1a132e829de16c4447cd487...7e347a574a579a24a6eaf6f7f474983c4b3274b3 | diff --git a/jena-fuseki2/jena-fuseki-webapp/src/main/java/org/apache/jena/fuseki/mgt/ActionDatasets.java b/jena-fuseki2/jena-fuseki-webapp/src/main/java/org/apache/jena/fuseki/mgt/ActionDatasets.java
index f7c6a4b176..ef08684388 100644
--- a/jena-fuseki2/jena-fuseki-webapp/src/main/java/org/apache/jena/fuseki/mgt/ActionDatasets.java
+++ b/jena-fuseki2/jena-fuseki-webapp/src/main/java/org/apache/jena/fuseki/mgt/ActionDatasets.java
@@ -141,8 +141,8 @@ public class ActionDatasets extends ActionContainerItem {
try {
// Where to build the templated service/database.
- Model model = ModelFactory.createDefaultModel();
- StreamRDF dest = StreamRDFLib.graph(model.getGraph());
+ Model modelData = ModelFactory.createDefaultModel();
+ StreamRDF dest = StreamRDFLib.graph(modelData.getGraph());
if ( hasParams || WebContent.isHtmlForm(ct) )
assemblerFromForm(action, dest);
@@ -151,6 +151,8 @@ public class ActionDatasets extends ActionContainerItem {
else
assemblerFromBody(action, dest);
+ Model model = ModelFactory.createDefaultModel();
+ model.add(modelData);
AssemblerUtils.addRegistered(model);
// ----
@@ -158,7 +160,7 @@ public class ActionDatasets extends ActionContainerItem {
// anything other than being "for the record".
systemFileCopy = FusekiWebapp.dirSystemFileArea.resolve(uuid.toString()).toString();
try ( OutputStream outCopy = IO.openOutputFile(systemFileCopy) ) {
- RDFDataMgr.write(outCopy, model, Lang.TURTLE);
+ RDFDataMgr.write(outCopy, modelData, Lang.TURTLE);
}
// ----
// Process configuration.
@@ -202,7 +204,7 @@ public class ActionDatasets extends ActionContainerItem {
// Write to configuration directory.
try ( OutputStream outCopy = IO.openOutputFile(configFile) ) {
- RDFDataMgr.write(outCopy, model, Lang.TURTLE);
+ RDFDataMgr.write(outCopy, modelData, Lang.TURTLE);
}
// Currently do nothing with the system database.
@@ -538,8 +540,6 @@ public class ActionDatasets extends ActionContainerItem {
return stmt;
}
- // TODO Merge with Upload.incomingData
-
private static void bodyAsGraph(HttpAction action, StreamRDF dest) {
HttpServletRequest request = action.getRequest();
String base = ActionLib.wholeRequestURL(request);
@@ -549,18 +549,6 @@ public class ActionDatasets extends ActionContainerItem {
ServletOps.errorBadRequest("Unknown content type for triples: " + ct);
return;
}
- // Don't log - assemblers are typically small.
- // Adding this to the log confuses things.
- // Reserve logging for data uploads.
-// long len = request.getContentLengthLong();
-// if ( action.verbose ) {
-// if ( len >= 0 )
-// alog.info(format("[%d] Body: Content-Length=%d, Content-Type=%s, Charset=%s => %s", action.id, len,
-// ct.getContentType(), ct.getCharset(), lang.getName()));
-// else
-// alog.info(format("[%d] Body: Content-Type=%s, Charset=%s => %s", action.id, ct.getContentType(),
-// ct.getCharset(), lang.getName()));
-// }
dest.prefix("root", base+"#");
ActionLib.parseOrError(action, dest, lang, base);
}
diff --git a/jena-fuseki2/jena-fuseki-webapp/src/test/java/org/apache/jena/fuseki/AbstractTestWebappAuth_JDK.java b/jena-fuseki2/jena-fuseki-webapp/src/test/java/org/apache/jena/fuseki/AbstractTestWebappAuth_JDK.java
index 6758061207..c1b4255042 100644
--- a/jena-fuseki2/jena-fuseki-webapp/src/test/java/org/apache/jena/fuseki/AbstractTestWebappAuth_JDK.java
+++ b/jena-fuseki2/jena-fuseki-webapp/src/test/java/org/apache/jena/fuseki/AbstractTestWebappAuth_JDK.java
@@ -47,7 +47,7 @@ public class AbstractTestWebappAuth_JDK {
protected static final String authServiceREST = "http://localhost:"+authPort+authDatasetPath+"/data";
private static File realmFile;
- private static final String FusekiTestHome = "target/FusekiHome";
+ private static final String FusekiTestHome = "target/FusekiTest";
private static final String FusekiTestBase = FusekiTestHome+"/run";
// False when in TS_FusekiWebapp
diff --git a/jena-fuseki2/jena-fuseki-webapp/src/test/java/org/apache/jena/fuseki/TS_FusekiWebapp.java b/jena-fuseki2/jena-fuseki-webapp/src/test/java/org/apache/jena/fuseki/TS_FusekiWebapp.java
index d412c05352..86ff041b6e 100644
--- a/jena-fuseki2/jena-fuseki-webapp/src/test/java/org/apache/jena/fuseki/TS_FusekiWebapp.java
+++ b/jena-fuseki2/jena-fuseki-webapp/src/test/java/org/apache/jena/fuseki/TS_FusekiWebapp.java
@@ -42,7 +42,7 @@ import org.junit.runners.Suite;
public class TS_FusekiWebapp extends ServerTest
{
- public static String FusekiTestHome = "target/FusekiHome";
+ public static String FusekiTestHome = "target/FusekiTest";
public static String FusekiTestBase = FusekiTestHome+"/run";
@BeforeClass public static void setupForFusekiServer() { | ['jena-fuseki2/jena-fuseki-webapp/src/test/java/org/apache/jena/fuseki/AbstractTestWebappAuth_JDK.java', 'jena-fuseki2/jena-fuseki-webapp/src/main/java/org/apache/jena/fuseki/mgt/ActionDatasets.java', 'jena-fuseki2/jena-fuseki-webapp/src/test/java/org/apache/jena/fuseki/TS_FusekiWebapp.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 25,669,879 | 5,847,705 | 726,017 | 4,640 | 1,381 | 293 | 24 | 1 | 396 | 57 | 81 | 15 | 0 | 0 | 1970-01-01T00:28:00 | 975 | Java | {'Java': 37296473, 'Shell': 270724, 'Ruby': 216471, 'Vue': 104500, 'Lex': 82672, 'JavaScript': 81879, 'HTML': 66939, 'XSLT': 65126, 'Perl': 34501, 'Haml': 30030, 'Batchfile': 25854, 'C++': 5877, 'SCSS': 4242, 'Thrift': 3755, 'Dockerfile': 3528, 'AspectJ': 3446, 'CSS': 3241, 'Elixir': 2548, 'Python': 416, 'Makefile': 198} | Apache License 2.0 |
1,095 | beehive-lab/tornadovm/82/57 | beehive-lab | tornadovm | https://github.com/beehive-lab/TornadoVM/issues/57 | https://github.com/beehive-lab/TornadoVM/pull/82 | https://github.com/beehive-lab/TornadoVM/pull/82#issuecomment-817727284 | 1 | solves | TestArrays#testInitParallel on AMD - failed with '[REASON] [ERROR] reset() was called after warmup()' | When running `TestArrays#testInitParallel` I get '[REASON] [ERROR] reset() was called after warmup()' exception thrown from `TornadoVM.compileTaskFromBytecodeToBinary`.
In fact, `TornadoTestBase.before` indeed reset ALL devices, but `TornadoVM.warmup` validates only one (VM-default ???) device. And if this device is different from SCHEDULE.TASK-device than it leads to an error (task device is changed via `s0.t0.device=0:1` command arg).
| 093aeb80ef295e8396be282451ee47ff9058953b | f3c5ba9870a5114e5dc4a2a26f50f773be7291fa | https://github.com/beehive-lab/tornadovm/compare/093aeb80ef295e8396be282451ee47ff9058953b...f3c5ba9870a5114e5dc4a2a26f50f773be7291fa | diff --git a/examples/src/main/java/uk/ac/manchester/tornado/examples/compute/MatrixMultiplication1D.java b/examples/src/main/java/uk/ac/manchester/tornado/examples/compute/MatrixMultiplication1D.java
index 403293a56..f36a5bf4c 100644
--- a/examples/src/main/java/uk/ac/manchester/tornado/examples/compute/MatrixMultiplication1D.java
+++ b/examples/src/main/java/uk/ac/manchester/tornado/examples/compute/MatrixMultiplication1D.java
@@ -20,11 +20,12 @@ package uk.ac.manchester.tornado.examples.compute;
import java.util.Random;
import java.util.stream.IntStream;
+import uk.ac.manchester.tornado.api.GridTask;
import uk.ac.manchester.tornado.api.TaskSchedule;
import uk.ac.manchester.tornado.api.WorkerGrid;
import uk.ac.manchester.tornado.api.WorkerGrid1D;
-import uk.ac.manchester.tornado.api.GridTask;
import uk.ac.manchester.tornado.api.annotations.Parallel;
+import uk.ac.manchester.tornado.api.enums.TornadoDeviceType;
public class MatrixMultiplication1D {
@@ -110,8 +111,10 @@ public class MatrixMultiplication1D {
String formatGPUFGlops = String.format("%.2f", gpuGigaFlops);
String formatCPUFGlops = String.format("%.2f", cpuGigaFlops);
- System.out.println("\\tCPU Execution: " + formatCPUFGlops + " GFlops, Total time = " + (endSequential - startSequential) + " ms");
- System.out.println("\\tGPU Execution: " + formatGPUFGlops + " GFlops, Total Time = " + (end - start) + " ms");
+ TornadoDeviceType deviceType = t.getDevice().getDeviceType();
+
+ System.out.println("\\tSingle Threaded CPU Execution: " + formatCPUFGlops + " GFlops, Total time = " + (endSequential - startSequential) + " ms");
+ System.out.println("\\tTornadoVM Execution on " + deviceType + " (Accelerated): " + formatGPUFGlops + " GFlops, Total Time = " + (end - start) + " ms");
System.out.println("\\tSpeedup: " + speedup + "x");
System.out.println("\\tVerification " + verify(matrixC, resultSeq, size));
}
diff --git a/examples/src/main/java/uk/ac/manchester/tornado/examples/compute/MatrixMultiplication2D.java b/examples/src/main/java/uk/ac/manchester/tornado/examples/compute/MatrixMultiplication2D.java
index f9b3877f1..452712e7a 100644
--- a/examples/src/main/java/uk/ac/manchester/tornado/examples/compute/MatrixMultiplication2D.java
+++ b/examples/src/main/java/uk/ac/manchester/tornado/examples/compute/MatrixMultiplication2D.java
@@ -17,14 +17,15 @@
*/
package uk.ac.manchester.tornado.examples.compute;
-import java.util.Random;
-
import uk.ac.manchester.tornado.api.GridTask;
import uk.ac.manchester.tornado.api.TaskSchedule;
import uk.ac.manchester.tornado.api.WorkerGrid;
import uk.ac.manchester.tornado.api.WorkerGrid2D;
import uk.ac.manchester.tornado.api.annotations.Parallel;
import uk.ac.manchester.tornado.api.collections.types.Matrix2DFloat;
+import uk.ac.manchester.tornado.api.enums.TornadoDeviceType;
+
+import java.util.Random;
public class MatrixMultiplication2D {
@@ -113,8 +114,9 @@ public class MatrixMultiplication2D {
String formatGPUFGlops = String.format("%.2f", gpuGigaFlops);
String formatCPUFGlops = String.format("%.2f", cpuGigaFlops);
- System.out.println("\\tCPU Execution: " + formatCPUFGlops + " GFlops, Total time = " + (endSequential - startSequential) + " ms");
- System.out.println("\\tGPU Execution: " + formatGPUFGlops + " GFlops, Total Time = " + (end - start) + " ms");
+ TornadoDeviceType deviceType = t.getDevice().getDeviceType();
+ System.out.println("\\tSingle Threaded CPU Execution: " + formatCPUFGlops + " GFlops, Total time = " + (endSequential - startSequential) + " ms");
+ System.out.println("\\tTornadoVM Execution on " + deviceType + " (Accelerated): " + formatGPUFGlops + " GFlops, Total Time = " + (end - start) + " ms");
System.out.println("\\tSpeedup: " + speedup + "x");
System.out.println("\\tVerification " + verify(matrixC, resultSeq, size));
}
diff --git a/runtime/src/main/java/uk/ac/manchester/tornado/runtime/graph/TornadoExecutionContext.java b/runtime/src/main/java/uk/ac/manchester/tornado/runtime/graph/TornadoExecutionContext.java
index e0a00adea..4075442f4 100644
--- a/runtime/src/main/java/uk/ac/manchester/tornado/runtime/graph/TornadoExecutionContext.java
+++ b/runtime/src/main/java/uk/ac/manchester/tornado/runtime/graph/TornadoExecutionContext.java
@@ -257,6 +257,7 @@ public class TornadoExecutionContext {
*
* @return {@link TornadoAcceleratorDevice}
*/
+ @Deprecated
public TornadoAcceleratorDevice getDefaultDevice() {
return meta.getLogicDevice();
}
diff --git a/runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/TornadoTaskSchedule.java b/runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/TornadoTaskSchedule.java
index 74c96a677..136dd0c6a 100644
--- a/runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/TornadoTaskSchedule.java
+++ b/runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/TornadoTaskSchedule.java
@@ -252,9 +252,17 @@ public class TornadoTaskSchedule implements AbstractTaskGraph {
return executionContext.getTask(id);
}
+ /**
+ * Returns the device attached to any of the tasks. Currently, TornadoVM
+ * executes all tasks that belong to the same task-schedule on the same device.
+ * Therefore, this call returns the device attached to the first task or the
+ * first task is planning to be executed.
+ *
+ * @return {@link TornadoDevice}
+ */
@Override
public TornadoDevice getDevice() {
- return meta().getLogicDevice();
+ return executionContext.getDeviceFirstTask();
}
private void triggerRecompile() {
diff --git a/runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/meta/AbstractMetaData.java b/runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/meta/AbstractMetaData.java
index a9a090942..90441abdd 100644
--- a/runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/meta/AbstractMetaData.java
+++ b/runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/meta/AbstractMetaData.java
@@ -99,6 +99,7 @@ public abstract class AbstractMetaData implements TaskMetaDataInterface {
* Set a device in the default driver in Tornado.
*
* @param device
+ * {@link TornadoDevice}
*/
public void setDevice(TornadoDevice device) {
this.driverIndex = device.getDriverIndex();
@@ -113,7 +114,9 @@ public abstract class AbstractMetaData implements TaskMetaDataInterface {
* Set a device from a specific Tornado driver.
*
* @param driverIndex
+ * Driver Index
* @param device
+ * {@link TornadoAcceleratorDevice}
*/
public void setDriverDevice(int driverIndex, TornadoAcceleratorDevice device) {
this.driverIndex = driverIndex;
diff --git a/runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/meta/TaskMetaData.java b/runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/meta/TaskMetaData.java
index 2f538d394..b4dae8bdf 100644
--- a/runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/meta/TaskMetaData.java
+++ b/runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/meta/TaskMetaData.java
@@ -234,9 +234,7 @@ public class TaskMetaData extends AbstractMetaData {
@Override
public TornadoAcceleratorDevice getLogicDevice() {
- if (scheduleMetaData.isDeviceManuallySet()) {
- return scheduleMetaData.getLogicDevice();
- } else if (scheduleMetaData.isDeviceDefined() && !isDeviceDefined()) {
+ if (scheduleMetaData.isDeviceManuallySet() || (scheduleMetaData.isDeviceDefined() && !isDeviceDefined())) {
return scheduleMetaData.getLogicDevice();
}
return super.getLogicDevice(); | ['examples/src/main/java/uk/ac/manchester/tornado/examples/compute/MatrixMultiplication1D.java', 'runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/TornadoTaskSchedule.java', 'runtime/src/main/java/uk/ac/manchester/tornado/runtime/graph/TornadoExecutionContext.java', 'runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/meta/TaskMetaData.java', 'examples/src/main/java/uk/ac/manchester/tornado/examples/compute/MatrixMultiplication2D.java', 'runtime/src/main/java/uk/ac/manchester/tornado/runtime/tasks/meta/AbstractMetaData.java'] | {'.java': 6} | 6 | 6 | 0 | 0 | 6 | 4,553,281 | 1,047,609 | 122,869 | 901 | 2,462 | 598 | 37 | 6 | 446 | 53 | 116 | 4 | 0 | 0 | 1970-01-01T00:26:58 | 925 | Java | {'Java': 7205361, 'C': 419399, 'C++': 274701, 'Python': 94263, 'Shell': 16800, 'CMake': 3336, 'JavaScript': 3316, 'Makefile': 1586, 'R': 896} | Apache License 2.0 |
640 | spring-cloud/spring-cloud-stream/742/741 | spring-cloud | spring-cloud-stream | https://github.com/spring-cloud/spring-cloud-stream/issues/741 | https://github.com/spring-cloud/spring-cloud-stream/pull/742 | https://github.com/spring-cloud/spring-cloud-stream/pull/742 | 1 | fixes | Allow for binders without embedded headers to process 'originalContentType' | As part of the changes that led to support for native serialization/deserialization we've made the assumption that any payload that is not a `byte[]` is already fully processed and so will skip `deserializePayloadIfNecessary`. However, if the binder is based on endpoints that do their own deserialization and populate headers (as for example RabbitMQ and the upcoming JMS), the current changes skip the part where `originalContentType` is processed. We should be more lenient and allow `deserializePayloadIfNecessary` to execute if we have an `originalContentType` header. | 38ba0d3941bb67899097ed9d5626901eeabc8eb9 | 4d74212932856a7d269ce155679715979df9a423 | https://github.com/spring-cloud/spring-cloud-stream/compare/38ba0d3941bb67899097ed9d5626901eeabc8eb9...4d74212932856a7d269ce155679715979df9a423 | diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractMessageChannelBinder.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractMessageChannelBinder.java
index 3aac7c84d..db24919d0 100644
--- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractMessageChannelBinder.java
+++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractMessageChannelBinder.java
@@ -278,7 +278,8 @@ public abstract class AbstractMessageChannelBinder<C extends ConsumerProperties,
@Override
@SuppressWarnings("unchecked")
protected Object handleRequestMessage(Message<?> requestMessage) {
- if (!(requestMessage.getPayload() instanceof byte[])) {
+ if (!(requestMessage.getPayload() instanceof byte[])
+ && !requestMessage.getHeaders().containsKey(BinderHeaders.BINDER_ORIGINAL_CONTENT_TYPE)) {
return requestMessage;
}
MessageValues messageValues; | ['spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractMessageChannelBinder.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 433,361 | 90,451 | 13,002 | 136 | 213 | 47 | 3 | 1 | 573 | 83 | 117 | 1 | 0 | 0 | 1970-01-01T00:24:42 | 918 | Java | {'Java': 2946369, 'Shell': 3768, 'Kotlin': 1141} | Apache License 2.0 |
641 | spring-cloud/spring-cloud-stream/402/403 | spring-cloud | spring-cloud-stream | https://github.com/spring-cloud/spring-cloud-stream/issues/403 | https://github.com/spring-cloud/spring-cloud-stream/pull/402 | https://github.com/spring-cloud/spring-cloud-stream/pull/402 | 1 | resolves | Support text/* content type for non-SCSt applications | When deserializing the payload at the consumer endpoint, the non-byte stream payload type requires to use `String` object when the underlying message content-type is of any `text` type contentType (text/plain, text/xml and text/html)
| 6acb825ad58107c42d5cc3ea7bc84035ef750315 | 4d8fa19a3ac68c5ac043302b21f79c3aeb885e65 | https://github.com/spring-cloud/spring-cloud-stream/compare/6acb825ad58107c42d5cc3ea7bc84035ef750315...4d8fa19a3ac68c5ac043302b21f79c3aeb885e65 | diff --git a/spring-cloud-stream-binders/spring-cloud-stream-binder-test/src/test/java/org/springframework/cloud/stream/binder/MessageChannelBinderSupportTests.java b/spring-cloud-stream-binders/spring-cloud-stream-binder-test/src/test/java/org/springframework/cloud/stream/binder/MessageChannelBinderSupportTests.java
index c8389214e..3a2481f68 100644
--- a/spring-cloud-stream-binders/spring-cloud-stream-binder-test/src/test/java/org/springframework/cloud/stream/binder/MessageChannelBinderSupportTests.java
+++ b/spring-cloud-stream-binders/spring-cloud-stream-binder-test/src/test/java/org/springframework/cloud/stream/binder/MessageChannelBinderSupportTests.java
@@ -111,6 +111,19 @@ public class MessageChannelBinderSupportTests {
assertNull(reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
+ @Test
+ public void testStringXML() throws IOException {
+ Message<?> message = MessageBuilder
+ .withPayload("<?xml version=\\"1.0\\" encoding=\\"UTF-8\\" standalone=\\"no\\"?><test></test>")
+ .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_XML)
+ .build();
+ Message<?> converted = binder.serializePayloadIfNecessary(message).toMessage();
+ assertEquals(MimeTypeUtils.TEXT_PLAIN, contentTypeResolver.resolve(converted.getHeaders()));
+ MessageValues reconstructed = binder.deserializePayloadIfNecessary(converted);
+ assertEquals("<?xml version=\\"1.0\\" encoding=\\"UTF-8\\" standalone=\\"no\\"?><test></test>", reconstructed.getPayload());
+ assertEquals(MimeTypeUtils.TEXT_XML.toString(), reconstructed.get(MessageHeaders.CONTENT_TYPE));
+ }
+
@Test
public void testContentTypePreserved() throws IOException {
Message<String> inbound = MessageBuilder.withPayload("{\\"foo\\":\\"foo\\"}")
diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractBinder.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractBinder.java
index a5a2bae91..540aa5f28 100644
--- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractBinder.java
+++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractBinder.java
@@ -18,7 +18,6 @@ package org.springframework.cloud.stream.binder;
import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON;
import static org.springframework.util.MimeTypeUtils.APPLICATION_OCTET_STREAM;
-import static org.springframework.util.MimeTypeUtils.TEXT_PLAIN;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -426,7 +425,7 @@ public abstract class AbstractBinder<T> implements ApplicationContextAware, Init
}
private Object deserializePayload(byte[] bytes, MimeType contentType) {
- if (TEXT_PLAIN.equals(contentType) || APPLICATION_JSON.equals(contentType)) {
+ if ("text".equalsIgnoreCase(contentType.getType()) || APPLICATION_JSON.equals(contentType)) {
try {
return new String(bytes, "UTF-8");
} | ['spring-cloud-stream-binders/spring-cloud-stream-binder-test/src/test/java/org/springframework/cloud/stream/binder/MessageChannelBinderSupportTests.java', 'spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractBinder.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 420,230 | 86,916 | 12,431 | 106 | 243 | 48 | 3 | 1 | 234 | 33 | 48 | 2 | 0 | 0 | 1970-01-01T00:24:17 | 918 | Java | {'Java': 2946369, 'Shell': 3768, 'Kotlin': 1141} | Apache License 2.0 |
639 | spring-cloud/spring-cloud-stream/757/756 | spring-cloud | spring-cloud-stream | https://github.com/spring-cloud/spring-cloud-stream/issues/756 | https://github.com/spring-cloud/spring-cloud-stream/pull/757 | https://github.com/spring-cloud/spring-cloud-stream/pull/757 | 1 | resolves | Compilation issue on reactor 3.0.4 upgrade | master has this compilation issue:
```
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project spring-cloud-stream-reactive: Compilation failure
[ERROR] /home/travis/build/spring-cloud/spring-cloud-stream/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ObservableToMessageChannelResultAdapter.java:[50,66] method from in class reactor.core.publisher.Flux<T> cannot be applied to given types;
[ERROR] required: org.reactivestreams.Publisher<? extends T>
[ERROR] found: org.reactivestreams.Publisher<capture#1 of ?>
[ERROR] reason: cannot infer type-variable(s) T,T
[ERROR] (argument mismatch; org.reactivestreams.Publisher<capture#2 of ?> cannot be converted to org.reactivestreams.Publisher<? extends capture#2 of ?>)
[ERROR] -> [Help 1]
[ERROR]
``` | 2abac42ebafa04f4d55e31c9911c4706ead3f170 | 503e749c19d0207a92a36648c2511d8bac2e7e48 | https://github.com/spring-cloud/spring-cloud-stream/compare/2abac42ebafa04f4d55e31c9911c4706ead3f170...503e749c19d0207a92a36648c2511d8bac2e7e48 | diff --git a/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ObservableToMessageChannelResultAdapter.java b/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ObservableToMessageChannelResultAdapter.java
index 42c459a06..1157bb71d 100644
--- a/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ObservableToMessageChannelResultAdapter.java
+++ b/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ObservableToMessageChannelResultAdapter.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016 the original author or authors.
+ * Copyright 2016-2017 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.
@@ -16,6 +16,7 @@
package org.springframework.cloud.stream.reactive;
+import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import rx.Observable;
import rx.RxReactiveStreams;
@@ -27,6 +28,7 @@ import org.springframework.util.Assert;
/**
* A {@link StreamListenerResultAdapter} from an {@link Observable}
* return type to a bound {@link MessageChannel}.
+ *
* @author Marius Bogoevici
*/
public class ObservableToMessageChannelResultAdapter
@@ -47,7 +49,7 @@ public class ObservableToMessageChannelResultAdapter
}
public void adapt(Observable<?> streamListenerResult, MessageChannel bindingTarget) {
- this.fluxToMessageChannelResultAdapter.adapt(Flux.from(RxReactiveStreams.toPublisher(streamListenerResult)),
- bindingTarget);
+ Publisher<?> adaptedPublisher = RxReactiveStreams.toPublisher(streamListenerResult);
+ this.fluxToMessageChannelResultAdapter.adapt(Flux.from(adaptedPublisher), bindingTarget);
}
} | ['spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ObservableToMessageChannelResultAdapter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 401,430 | 82,397 | 11,564 | 131 | 463 | 106 | 8 | 1 | 862 | 68 | 213 | 12 | 0 | 1 | 1970-01-01T00:24:43 | 918 | Java | {'Java': 2946369, 'Shell': 3768, 'Kotlin': 1141} | Apache License 2.0 |
638 | spring-cloud/spring-cloud-stream/1041/1040 | spring-cloud | spring-cloud-stream | https://github.com/spring-cloud/spring-cloud-stream/issues/1040 | https://github.com/spring-cloud/spring-cloud-stream/pull/1041 | https://github.com/spring-cloud/spring-cloud-stream/pull/1041 | 2 | resolves | Set default SpEL to configure partition key expression for outbound messages | _From @ashvinkanani-dream on August 17, 2017 9:9_
Hi,
I'd like to configure the partition key expression for all outbound messages being sent by any producer.
To achieve this I have configured following property
```
spring.cloud.stream.default.producer.partitionKeyExpression=payload.id
```
But, it didn't worked for me.
Also, when I configured the property for each output channel, it worked fine.
```
spring.cloud.stream.bindings.output-channel-1.producer.partitionKeyExpression=payload.id
spring.cloud.stream.bindings.output-channel-2.producer.partitionKeyExpression=payload.id
```
Reference
- [Producer Properties](http://docs.spring.io/spring-cloud-stream/docs/current/reference/htmlsingle/#_producer_properties)
_Copied from original issue: spring-cloud/spring-cloud-stream-binder-kafka#182_ | 7cbd005e79ce35f1192d9b8f556af972c688994a | 5ff4886434091241b1163dffe3d0155843939959 | https://github.com/spring-cloud/spring-cloud-stream/compare/7cbd005e79ce35f1192d9b8f556af972c688994a...5ff4886434091241b1163dffe3d0155843939959 | diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceProperties.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceProperties.java
index 226227c90..ae06a2730 100644
--- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceProperties.java
+++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceProperties.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2015-2016 the original author or authors.
+ * Copyright 2015-2017 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.
@@ -33,10 +33,8 @@ import org.springframework.cloud.stream.binder.ProducerProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.context.EnvironmentAware;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.env.ConfigurableEnvironment;
-import org.springframework.core.env.Environment;
import org.springframework.integration.support.utils.IntegrationUtils;
import org.springframework.util.Assert;
@@ -48,7 +46,7 @@ import org.springframework.util.Assert;
*/
@ConfigurationProperties("spring.cloud.stream")
@JsonInclude(Include.NON_DEFAULT)
-public class BindingServiceProperties implements ApplicationContextAware, EnvironmentAware, InitializingBean {
+public class BindingServiceProperties implements ApplicationContextAware, InitializingBean {
private ConversionService conversionService;
@@ -120,18 +118,15 @@ public class BindingServiceProperties implements ApplicationContextAware, Enviro
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = (ConfigurableApplicationContext) applicationContext;
- }
-
- @Override
- public void setEnvironment(Environment environment) {
- if (environment instanceof ConfigurableEnvironment) {
+ if (this.applicationContext.getEnvironment() instanceof ConfigurableEnvironment) {
// override the bindings store with the environment-initializing version if in
// a Spring context
Map<String, BindingProperties> delegate = new TreeMap<String, BindingProperties>(
String.CASE_INSENSITIVE_ORDER);
delegate.putAll(this.bindings);
- this.bindings = new EnvironmentEntryInitializingTreeMap<>((ConfigurableEnvironment) environment,
- BindingProperties.class, "spring.cloud.stream.default", delegate);
+ this.bindings = new EnvironmentEntryInitializingTreeMap<>(this.applicationContext.getEnvironment(),
+ BindingProperties.class, "spring.cloud.stream.default", delegate,
+ IntegrationUtils.getConversionService(this.applicationContext.getBeanFactory()));
}
}
diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/EnvironmentEntryInitializingTreeMap.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/EnvironmentEntryInitializingTreeMap.java
index 991f403a0..0b9ed276f 100644
--- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/EnvironmentEntryInitializingTreeMap.java
+++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/EnvironmentEntryInitializingTreeMap.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2016 the original author or authors.
+ * Copyright 2016-2017 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.
@@ -23,6 +23,7 @@ import java.util.Set;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.bind.PropertySourcesPropertyValues;
import org.springframework.boot.bind.RelaxedDataBinder;
+import org.springframework.core.convert.ConversionService;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.Assert;
@@ -38,6 +39,7 @@ import org.springframework.util.Assert;
* This implementation is not thread safe.
*
* @author Marius Bogoevici
+ * @author Ilayaperumal Gopinathan
*/
public class EnvironmentEntryInitializingTreeMap<T> extends AbstractMap<String, T> {
@@ -49,6 +51,8 @@ public class EnvironmentEntryInitializingTreeMap<T> extends AbstractMap<String,
private final Map<String, T> delegate;
+ private final ConversionService conversionService;
+
/**
* Constructs the map.
*
@@ -56,9 +60,11 @@ public class EnvironmentEntryInitializingTreeMap<T> extends AbstractMap<String,
* @param entryClass the entry class
* @param defaultsPrefix the prefix for initializing the properties
* @param delegate the actual map that stores the values
+ * @param conversionService the conversion service to use when binding the default
+ * property values.
*/
public EnvironmentEntryInitializingTreeMap(ConfigurableEnvironment environment, Class<T> entryClass,
- String defaultsPrefix, Map<String, T> delegate) {
+ String defaultsPrefix, Map<String, T> delegate, ConversionService conversionService) {
Assert.notNull(environment, "The environment cannot be null");
Assert.notNull(entryClass, "The entry class cannot be null");
Assert.notNull(defaultsPrefix, "The prefix for the property defaults cannot be null");
@@ -67,6 +73,7 @@ public class EnvironmentEntryInitializingTreeMap<T> extends AbstractMap<String,
this.entryClass = entryClass;
this.defaultsPrefix = defaultsPrefix;
this.delegate = delegate;
+ this.conversionService = conversionService;
}
@Override
@@ -74,6 +81,7 @@ public class EnvironmentEntryInitializingTreeMap<T> extends AbstractMap<String,
if (!this.delegate.containsKey(key) && key instanceof String) {
T entry = BeanUtils.instantiate(entryClass);
RelaxedDataBinder defaultsDataBinder = new RelaxedDataBinder(entry, defaultsPrefix);
+ defaultsDataBinder.setConversionService(this.conversionService);
defaultsDataBinder.bind(new PropertySourcesPropertyValues(environment.getPropertySources()));
this.delegate.put((String) key, entry);
}
diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesOnlyTest.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesOnlyTest.java
index 3236107c5..a1b158c74 100644
--- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesOnlyTest.java
+++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesOnlyTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2015 the original author or authors.
+ * Copyright 2015-2017 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.
@@ -37,7 +37,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SourceBindingWithGlobalPropertiesOnlyTest.TestSource.class, properties = {
- "spring.cloud.stream.default.contentType=application/json" })
+ "spring.cloud.stream.default.contentType=application/json",
+ "spring.cloud.stream.default.producer.partitionKeyExpression=key" })
public class SourceBindingWithGlobalPropertiesOnlyTest {
@Autowired
@@ -48,6 +49,8 @@ public class SourceBindingWithGlobalPropertiesOnlyTest {
public void testGlobalPropertiesSet() {
BindingProperties bindingProperties = bindingServiceProperties.getBindingProperties(Source.OUTPUT);
Assertions.assertThat(bindingProperties.getContentType()).isEqualTo("application/json");
+ Assertions.assertThat(bindingProperties.getProducer()).isNotNull();
+ Assertions.assertThat(bindingProperties.getProducer().getPartitionKeyExpression().getExpressionString()).isEqualTo("key");
}
@EnableBinding(Source.class) | ['spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/EnvironmentEntryInitializingTreeMap.java', 'spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesOnlyTest.java', 'spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceProperties.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 518,607 | 106,707 | 14,928 | 163 | 1,701 | 313 | 29 | 2 | 824 | 68 | 182 | 24 | 1 | 2 | 1970-01-01T00:25:02 | 918 | Java | {'Java': 2946369, 'Shell': 3768, 'Kotlin': 1141} | Apache License 2.0 |
637 | spring-cloud/spring-cloud-stream/1049/1048 | spring-cloud | spring-cloud-stream | https://github.com/spring-cloud/spring-cloud-stream/issues/1048 | https://github.com/spring-cloud/spring-cloud-stream/pull/1049 | https://github.com/spring-cloud/spring-cloud-stream/pull/1049 | 1 | fixes | AbstractAvroMessageConverter is failing due originalContentType | Currently the `AbstractAvroMessageConverter` checks for the contentType header, but it turns out that the header is set at `originalContentType`.
We need to make sure we check both values in order to make `canConvertFrom` work properly | 51e71610561e09a4006017df613851617a667b71 | 007594cafd12c74f4812d8b9b8c92a38366b9e93 | https://github.com/spring-cloud/spring-cloud-stream/compare/51e71610561e09a4006017df613851617a667b71...007594cafd12c74f4812d8b9b8c92a38366b9e93 | diff --git a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AbstractAvroMessageConverter.java b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AbstractAvroMessageConverter.java
index a1480b3c8..af544935e 100644
--- a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AbstractAvroMessageConverter.java
+++ b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AbstractAvroMessageConverter.java
@@ -37,6 +37,7 @@ import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.avro.specific.SpecificRecord;
+import org.springframework.cloud.stream.binder.BinderHeaders;
import org.springframework.core.io.Resource;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
@@ -48,6 +49,7 @@ import org.springframework.util.MimeType;
* Base class for Apache Avro
* {@link org.springframework.messaging.converter.MessageConverter} implementations.
* @author Marius Bogoevici
+ * @author Vinicius Carvalho
*/
public abstract class AbstractAvroMessageConverter extends AbstractMessageConverter {
@@ -68,6 +70,29 @@ public abstract class AbstractAvroMessageConverter extends AbstractMessageConver
return super.canConvertFrom(message, targetClass) && (message.getPayload() instanceof byte[]);
}
+ @Override
+ protected boolean supportsMimeType(MessageHeaders headers) {
+
+ for (MimeType current : getSupportedMimeTypes()) {
+ if(mimeTypeMatches(current,headers.get(MessageHeaders.CONTENT_TYPE)) || mimeTypeMatches(current,headers.get(BinderHeaders.BINDER_ORIGINAL_CONTENT_TYPE)) ){
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private boolean mimeTypeMatches(MimeType reference, Object target){
+ if(target == null){
+ return !isStrictContentTypeMatch();
+ }else if(target instanceof MimeType){
+ return reference.equals((MimeType)target);
+ }else if(target instanceof String){
+ return reference.equals(MimeType.valueOf((String)target));
+ }
+ return false;
+ }
+
@Override
protected Object convertFromInternal(Message<?> message, Class<?> targetClass, Object conversionHint) {
Object result = null; | ['spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AbstractAvroMessageConverter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 522,743 | 107,545 | 15,016 | 163 | 789 | 167 | 25 | 1 | 239 | 35 | 50 | 3 | 0 | 0 | 1970-01-01T00:25:03 | 918 | Java | {'Java': 2946369, 'Shell': 3768, 'Kotlin': 1141} | Apache License 2.0 |
672 | zalando/nakadi/677/391 | zalando | nakadi | https://github.com/zalando/nakadi/issues/391 | https://github.com/zalando/nakadi/pull/677 | https://github.com/zalando/nakadi/pull/677 | 1 | fixes | Nakadi silently overrides metadata.flow_id | When publishing an event, if the header `X-Flow-Id` is not provided, then Nakadi will silently override this field with a randomly generated value.
I would expect Nakadi not to override it, if it was provided, since it's mentioned in the API that "No preexisting value might be changed".
> 1. Once the validation succeeded, the content of the Event is updated according to the
> enrichment rules in the order the rules are defined in the `EventType`. No preexisting
> value might be changed (even if added by an enrichment rule). Violations on this will force
> the immediate **rejection** of the Event. The invalid overwrite attempt will be included in
> the item's `BatchItemResponse` object.
It should either reject such event (which doesn't make much sense) or keep it, if present.
| ddbfc693362b49214d4d13507be36f9008173a2b | 011015d32a29b8dad051fe9e6981cc47de50652e | https://github.com/zalando/nakadi/compare/ddbfc693362b49214d4d13507be36f9008173a2b...011015d32a29b8dad051fe9e6981cc47de50652e | diff --git a/src/main/java/org/zalando/nakadi/enrichment/MetadataEnrichmentStrategy.java b/src/main/java/org/zalando/nakadi/enrichment/MetadataEnrichmentStrategy.java
index 145545f9c..ec4e154fe 100644
--- a/src/main/java/org/zalando/nakadi/enrichment/MetadataEnrichmentStrategy.java
+++ b/src/main/java/org/zalando/nakadi/enrichment/MetadataEnrichmentStrategy.java
@@ -30,7 +30,9 @@ public class MetadataEnrichmentStrategy implements EnrichmentStrategy {
}
private void setFlowId(final JSONObject metadata) {
- metadata.put("flow_id", FlowIdUtils.peek());
+ if ("".equals(metadata.optString("flow_id"))) {
+ metadata.put("flow_id", FlowIdUtils.peek());
+ }
}
private void setEventTypeName(final JSONObject metadata, final EventType eventType) {
diff --git a/src/test/java/org/zalando/nakadi/enrichment/MetadataEnrichmentStrategyTest.java b/src/test/java/org/zalando/nakadi/enrichment/MetadataEnrichmentStrategyTest.java
index 768b9547c..642ec2568 100644
--- a/src/test/java/org/zalando/nakadi/enrichment/MetadataEnrichmentStrategyTest.java
+++ b/src/test/java/org/zalando/nakadi/enrichment/MetadataEnrichmentStrategyTest.java
@@ -90,6 +90,47 @@ public class MetadataEnrichmentStrategyTest {
assertThat(batch.getEvent().getJSONObject("metadata").getString("flow_id"), equalTo(flowId));
}
+ @Test
+ public void whenFlowIdIsPresentDoNotOverride() throws Exception {
+ final EventType eventType = buildDefaultEventType();
+ final JSONObject event = buildBusinessEvent();
+ event.getJSONObject("metadata").put("flow_id", "something");
+ final BatchItem batch = createBatchItem(event);
+
+ FlowIdUtils.push("something-else");
+ strategy.enrich(batch, eventType);
+
+ assertThat(batch.getEvent().getJSONObject("metadata").getString("flow_id"), equalTo("something"));
+ }
+
+ @Test
+ public void whenFlowIsEmptyStringOverrideIt() throws Exception {
+ final EventType eventType = buildDefaultEventType();
+ final JSONObject event = buildBusinessEvent();
+ event.getJSONObject("metadata").put("flow_id", "");
+ final BatchItem batch = createBatchItem(event);
+
+ final String flowId = randomString();
+ FlowIdUtils.push(flowId);
+ strategy.enrich(batch, eventType);
+
+ assertThat(batch.getEvent().getJSONObject("metadata").getString("flow_id"), equalTo(flowId));
+ }
+
+ @Test
+ public void whenFlowIsNullOverrideIt() throws Exception {
+ final EventType eventType = buildDefaultEventType();
+ final JSONObject event = buildBusinessEvent();
+ event.getJSONObject("metadata").put("flow_id", (Object)null);
+ final BatchItem batch = createBatchItem(event);
+
+ final String flowId = randomString();
+ FlowIdUtils.push(flowId);
+ strategy.enrich(batch, eventType);
+
+ assertThat(batch.getEvent().getJSONObject("metadata").getString("flow_id"), equalTo(flowId));
+ }
+
@Test
public void setPartition() throws Exception {
final EventType eventType = buildDefaultEventType(); | ['src/main/java/org/zalando/nakadi/enrichment/MetadataEnrichmentStrategy.java', 'src/test/java/org/zalando/nakadi/enrichment/MetadataEnrichmentStrategyTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 832,929 | 156,211 | 21,130 | 299 | 179 | 38 | 4 | 1 | 818 | 132 | 182 | 12 | 0 | 0 | 1970-01-01T00:24:56 | 904 | Java | {'Java': 2529825, 'Shell': 1956, 'PLpgSQL': 1208, 'Dockerfile': 872} | MIT License |
493 | broadinstitute/picard/743/728 | broadinstitute | picard | https://github.com/broadinstitute/picard/issues/728 | https://github.com/broadinstitute/picard/pull/743 | https://github.com/broadinstitute/picard/pull/743 | 1 | fixes | CollectRnaSeqMetrics Null Pointer Exception when RIBOSOMAL_INTERVALS are not given | If the`RIBOSOMAL_INTERVALS` option is not given and `RRNA_FRAGMENT_PERCENTAGE=0`, then [this if statement is always true](https://github.com/broadinstitute/picard/blob/master/src/main/java/picard/analysis/directed/RnaSeqMetricsCollector.java#L168). This leads to the following NPE:
```
Exception in thread "main" java.lang.NullPointerException
at picard.analysis.directed.RnaSeqMetricsCollector$PerUnitRnaSeqMetricsCollector.acceptRecord(RnaSeqMetricsCollector.java:171)
at picard.analysis.directed.RnaSeqMetricsCollector$PerUnitRnaSeqMetricsCollector.acceptRecord(RnaSeqMetricsCollector.java:98)
at picard.metrics.MultiLevelCollector$AllReadsDistributor.acceptRecord(MultiLevelCollector.java:192)
at picard.metrics.MultiLevelCollector.acceptRecord(MultiLevelCollector.java:315)
at picard.analysis.CollectRnaSeqMetrics.acceptRead(CollectRnaSeqMetrics.java:164)
at picard.analysis.SinglePassSamProgram.makeItSo(SinglePassSamProgram.java:138)
at picard.analysis.SinglePassSamProgram.doWork(SinglePassSamProgram.java:77)
at picard.cmdline.CommandLineProgram.instanceMain(CommandLineProgram.java:205)
at picard.cmdline.PicardCommandLine.instanceMain(PicardCommandLine.java:94)
at picard.cmdline.PicardCommandLine.main(PicardCommandLine.java:104)
```
A simple fix would be to not allow `RRNA_FRAGMENT_PERCENTAGE=0` if `RIBOSOMAL_INTERVALS=null`. | f5b9f505531d1b65b3eabd47a45ad14ff1681e3d | 2ed4968ed07cf30fad3af622867ee50a62b15d73 | https://github.com/broadinstitute/picard/compare/f5b9f505531d1b65b3eabd47a45ad14ff1681e3d...2ed4968ed07cf30fad3af622867ee50a62b15d73 | diff --git a/src/main/java/picard/analysis/CollectRnaSeqMetrics.java b/src/main/java/picard/analysis/CollectRnaSeqMetrics.java
index dfeb67111..aed80f0bf 100644
--- a/src/main/java/picard/analysis/CollectRnaSeqMetrics.java
+++ b/src/main/java/picard/analysis/CollectRnaSeqMetrics.java
@@ -134,6 +134,15 @@ static final String USAGE_DETAILS = "<p>This tool takes a SAM/BAM file containin
new CollectRnaSeqMetrics().instanceMainWithExit(argv);
}
+ @Override
+ protected String[] customCommandLineValidation() {
+ // No ribosomal intervals file and rRNA fragment percentage = 0
+ if ( RIBOSOMAL_INTERVALS == null && RRNA_FRAGMENT_PERCENTAGE == 0 ) {
+ throw new PicardException("Must use a RIBOSOMAL_INTERVALS file if RRNA_FRAGMENT_PERCENTAGE = 0.0");
+ }
+ return super.customCommandLineValidation();
+ }
+
@Override
protected void setup(final SAMFileHeader header, final File samFile) {
@@ -143,7 +152,7 @@ static final String USAGE_DETAILS = "<p>This tool takes a SAM/BAM file containin
LOG.info("Loaded " + geneOverlapDetector.getAll().size() + " genes.");
final Long ribosomalBasesInitialValue = RIBOSOMAL_INTERVALS != null ? 0L : null;
- final OverlapDetector<Interval> ribosomalSequenceOverlapDetector = RnaSeqMetricsCollector.makeOverlapDetector(samFile, header, RIBOSOMAL_INTERVALS);
+ final OverlapDetector<Interval> ribosomalSequenceOverlapDetector = RnaSeqMetricsCollector.makeOverlapDetector(samFile, header, RIBOSOMAL_INTERVALS, LOG);
final HashSet<Integer> ignoredSequenceIndices = RnaSeqMetricsCollector.makeIgnoredSequenceIndicesSet(header, IGNORE_SEQUENCE);
diff --git a/src/main/java/picard/analysis/directed/RnaSeqMetricsCollector.java b/src/main/java/picard/analysis/directed/RnaSeqMetricsCollector.java
index 8bfb3300a..36083c5c5 100644
--- a/src/main/java/picard/analysis/directed/RnaSeqMetricsCollector.java
+++ b/src/main/java/picard/analysis/directed/RnaSeqMetricsCollector.java
@@ -6,6 +6,7 @@ import htsjdk.samtools.util.CoordMath;
import htsjdk.samtools.util.Histogram;
import htsjdk.samtools.util.Interval;
import htsjdk.samtools.util.IntervalList;
+import htsjdk.samtools.util.Log;
import htsjdk.samtools.util.OverlapDetector;
import htsjdk.samtools.util.SequenceUtil;
import picard.PicardException;
@@ -60,12 +61,15 @@ public class RnaSeqMetricsCollector extends SAMRecordMultiLevelCollector<RnaSeqM
return new PerUnitRnaSeqMetricsCollector(sample, library, readGroup, ribosomalInitialValue);
}
- public static OverlapDetector<Interval> makeOverlapDetector(final File samFile, final SAMFileHeader header, final File ribosomalIntervalsFile) {
+ public static OverlapDetector<Interval> makeOverlapDetector(final File samFile, final SAMFileHeader header, final File ribosomalIntervalsFile, final Log log) {
- OverlapDetector<Interval> ribosomalSequenceOverlapDetector = new OverlapDetector<Interval>(0, 0);
+ final OverlapDetector<Interval> ribosomalSequenceOverlapDetector = new OverlapDetector<Interval>(0, 0);
if (ribosomalIntervalsFile != null) {
final IntervalList ribosomalIntervals = IntervalList.fromFile(ribosomalIntervalsFile);
+ if (ribosomalIntervals.size() == 0) {
+ log.warn("The RIBOSOMAL_INTERVALS file, " + ribosomalIntervalsFile.getAbsolutePath() + " does not contain intervals");
+ }
try {
SequenceUtil.assertSequenceDictionariesEqual(header.getSequenceDictionary(), ribosomalIntervals.getHeader().getSequenceDictionary());
} catch (SequenceUtil.SequenceListsDifferException e) {
diff --git a/src/test/java/picard/analysis/CollectRnaSeqMetricsTest.java b/src/test/java/picard/analysis/CollectRnaSeqMetricsTest.java
index fd25a8503..84da166c8 100644
--- a/src/test/java/picard/analysis/CollectRnaSeqMetricsTest.java
+++ b/src/test/java/picard/analysis/CollectRnaSeqMetricsTest.java
@@ -29,12 +29,15 @@ import htsjdk.samtools.util.Interval;
import htsjdk.samtools.util.IntervalList;
import htsjdk.samtools.util.StringUtil;
import org.testng.Assert;
+import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
+import picard.PicardException;
import picard.cmdline.CommandLineProgramTest;
import picard.annotation.RefFlatReader.RefFlatColumns;
import java.io.File;
import java.io.FileReader;
+import java.io.IOException;
import java.io.PrintStream;
public class CollectRnaSeqMetricsTest extends CommandLineProgramTest {
@@ -112,6 +115,65 @@ public class CollectRnaSeqMetricsTest extends CommandLineProgramTest {
Assert.assertEquals(metrics.PCT_R2_TRANSCRIPT_STRAND_READS, 0.666667);
}
+ @DataProvider(name = "rRnaIntervalsFiles")
+ public static Object[][] rRnaIntervalsFiles() throws IOException {
+ return new Object[][] {
+ {null},
+ {File.createTempFile("tmp.rRna.", ".interval_list")}
+ };
+ }
+
+ @Test(dataProvider = "rRnaIntervalsFiles")
+ public void testNoIntevalsNoFragPercentage(final File rRnaIntervalsFile) throws Exception {
+ final SAMRecordSetBuilder builder = new SAMRecordSetBuilder(true, SAMFileHeader.SortOrder.coordinate);
+
+ // Add a header but no intervals
+ if ( rRnaIntervalsFile != null ) {
+ final IntervalList rRnaIntervalList = new IntervalList(builder.getHeader());
+ rRnaIntervalList.write(rRnaIntervalsFile);
+ rRnaIntervalsFile.deleteOnExit();
+ }
+
+ // Create some alignments
+ final String sequence = "chr1";
+ final String ignoredSequence = "chrM";
+
+ // Set seed so that strandedness is consistent among runs.
+ builder.setRandomSeed(0);
+ final int sequenceIndex = builder.getHeader().getSequenceIndex(sequence);
+ builder.addPair("pair1", sequenceIndex, 45, 475);
+ builder.addFrag("ignoredFrag", builder.getHeader().getSequenceIndex(ignoredSequence), 1, false);
+
+ final File samFile = File.createTempFile("tmp.collectRnaSeqMetrics.", ".sam");
+ samFile.deleteOnExit();
+
+ final SAMFileWriter samWriter = new SAMFileWriterFactory().makeSAMWriter(builder.getHeader(), false, samFile);
+ for (final SAMRecord rec : builder.getRecords()) samWriter.addAlignment(rec);
+ samWriter.close();
+
+ // Generate the metrics.
+ final File metricsFile = File.createTempFile("tmp.", ".rna_metrics");
+ metricsFile.deleteOnExit();
+
+ final String rRnaIntervalsPath = rRnaIntervalsFile != null ? rRnaIntervalsFile.getAbsolutePath() : null;
+ final String[] args = new String[]{
+ "INPUT=" + samFile.getAbsolutePath(),
+ "OUTPUT=" + metricsFile.getAbsolutePath(),
+ "REF_FLAT=" + getRefFlatFile(sequence).getAbsolutePath(),
+ "RIBOSOMAL_INTERVALS=" + rRnaIntervalsPath,
+ "RRNA_FRAGMENT_PERCENTAGE=" + 0.0,
+ "STRAND_SPECIFICITY=SECOND_READ_TRANSCRIPTION_STRAND",
+ "IGNORE_SEQUENCE=" + ignoredSequence
+ };
+ try {
+ Assert.assertEquals(runPicardCommandLine(args), 0);
+ } catch(final Exception e) {
+ if (rRnaIntervalsFile != null) {
+ Assert.assertEquals(e.getCause().getClass(), PicardException.class);
+ }
+ }
+ }
+
@Test
public void testMultiLevel() throws Exception {
final String sequence = "chr1"; | ['src/main/java/picard/analysis/directed/RnaSeqMetricsCollector.java', 'src/test/java/picard/analysis/CollectRnaSeqMetricsTest.java', 'src/main/java/picard/analysis/CollectRnaSeqMetrics.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 2,790,093 | 595,163 | 61,621 | 358 | 1,499 | 341 | 19 | 2 | 1,369 | 59 | 334 | 17 | 1 | 1 | 1970-01-01T00:24:45 | 884 | Java | {'Java': 6182595, 'R': 26294, 'XSLT': 22469, 'Python': 17559, 'HTML': 11372, 'Shell': 10630, 'CSS': 3608, 'Dockerfile': 801, 'Rebol': 7} | MIT License |
492 | broadinstitute/picard/867/863 | broadinstitute | picard | https://github.com/broadinstitute/picard/issues/863 | https://github.com/broadinstitute/picard/pull/867 | https://github.com/broadinstitute/picard/pull/867 | 1 | fixes | UpdateVcfSequenceDictionary cannot write index | @ronlevine looks like you introduced a bug, can you fix? Try writing it to a file with `CREATE_INDEX=true`. Since you wrapped it with an output stream :/. I am curious as to why the change was made at all, since shouldn't `VariantContextWriterBuilder.determineOutputTypeFromFile` handle this? What was the original problem?
https://github.com/broadinstitute/picard/blob/master/src/main/java/picard/vcf/UpdateVcfSequenceDictionary.java#L92-L99 | 91339c54b3020dbbf18e0e8aaca2f50159f3ed3c | 24593ac50877cc8e31d708c04ecb3e4b70cee1f4 | https://github.com/broadinstitute/picard/compare/91339c54b3020dbbf18e0e8aaca2f50159f3ed3c...24593ac50877cc8e31d708c04ecb3e4b70cee1f4 | diff --git a/src/main/java/picard/vcf/UpdateVcfSequenceDictionary.java b/src/main/java/picard/vcf/UpdateVcfSequenceDictionary.java
index d688bebad..eacba3d73 100644
--- a/src/main/java/picard/vcf/UpdateVcfSequenceDictionary.java
+++ b/src/main/java/picard/vcf/UpdateVcfSequenceDictionary.java
@@ -38,15 +38,12 @@ import htsjdk.variant.vcf.VCFFileReader;
import htsjdk.variant.vcf.VCFHeader;
import org.broadinstitute.barclay.argparser.Argument;
import org.broadinstitute.barclay.help.DocumentedFeature;
-import picard.PicardException;
import picard.cmdline.CommandLineProgram;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import picard.cmdline.StandardOptionDefinitions;
import picard.cmdline.programgroups.VariantManipulationProgramGroup;
import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
/**
* Takes a VCF file and a Sequence Dictionary (from a variety of file types) and updates the Sequence Dictionary in VCF.
@@ -89,13 +86,7 @@ public class UpdateVcfSequenceDictionary extends CommandLineProgram {
if (CREATE_INDEX)
builder.setOption(Options.INDEX_ON_THE_FLY);
- try {
- builder.setOutputStream(new FileOutputStream(OUTPUT));
- } catch (final FileNotFoundException ex ) {
- throw new PicardException("Could not open " + OUTPUT.getAbsolutePath() + ": " + ex.getMessage(), ex);
- }
-
- final VariantContextWriter vcfWriter = builder.build();
+ final VariantContextWriter vcfWriter = builder.setOutputFile(OUTPUT).build();
fileHeader.setSequenceDictionary(samSequenceDictionary);
vcfWriter.writeHeader(fileHeader);
diff --git a/src/test/java/picard/vcf/UpdateVcfSequenceDictionaryTest.java b/src/test/java/picard/vcf/UpdateVcfSequenceDictionaryTest.java
index ee66cad94..c441b9767 100644
--- a/src/test/java/picard/vcf/UpdateVcfSequenceDictionaryTest.java
+++ b/src/test/java/picard/vcf/UpdateVcfSequenceDictionaryTest.java
@@ -30,17 +30,17 @@ import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.FileOutputStream;
-import java.io.IOException;
+import java.io.*;
import java.lang.reflect.Field;
-/**
- * @author George Grant
- */
+
public class UpdateVcfSequenceDictionaryTest {
private static final File TEST_DATA_PATH = new File("testdata/picard/vcf/");
+ private static final File INPUT_FILE = new File(TEST_DATA_PATH, "vcfFormatTest.vcf");
+
+ // vcfFormatTest.bad_dict.vcf is a vcf with two (2) ##contig lines deleted
+ private final File SAM_SEQUENCE_DICTIONARY_VCF = new File(TEST_DATA_PATH, "vcfFormatTest.bad_dict.vcf");
+
private static final File OUTPUT_DATA_PATH = IOUtil.createTempDir("UpdateVcfSequenceDictionaryTest", null);
private static final File STD_OUT_FILE = new File(OUTPUT_DATA_PATH, "stdout.vcf");
private static final String STD_OUT_NAME = "/dev/stdout";
@@ -54,23 +54,41 @@ public class UpdateVcfSequenceDictionaryTest {
public static Object[][] outputFies() {
return new Object[][] {
- {OUTPUT_DATA_PATH + "updateVcfSequenceDictionaryTest-delete-me.vcf"},
+ {OUTPUT_DATA_PATH + "updateVcfSequenceDictionaryTest-delete-me" + IOUtil.COMPRESSED_VCF_FILE_EXTENSION},
+ {OUTPUT_DATA_PATH + "updateVcfSequenceDictionaryTest-delete-me" + IOUtil.VCF_FILE_EXTENSION},
{STD_OUT_NAME}
};
}
+ /**
+ * Utility for unzipping a zipped file's contents into a human readable, unzipped file
+ *
+ * @param zippedFile input zipped file
+ * @param unzippedFile unzipped file
+ * @throws IOException
+ */
+ private void unzipFile(final File zippedFile, final File unzippedFile) throws IOException {
+ final InputStream gzInputStream = IOUtil.openFileForReading(zippedFile);
+ final FileOutputStream fileOutputStream = new FileOutputStream(unzippedFile.getAbsolutePath());
+ final byte[] buffer = new byte[1024];
+ int len;
+ while ((len = gzInputStream.read(buffer)) > 0) {
+ fileOutputStream.write(buffer, 0, len);
+ }
+ gzInputStream.close();
+ fileOutputStream.close();
+ }
+
@Test(dataProvider = "OutputFiles")
public void testUpdateVcfSequenceDictionary(final String outputFileName) throws IOException, NoSuchFieldException, IllegalAccessException {
- File input = new File(TEST_DATA_PATH, "vcfFormatTest.vcf");
- // vcfFormatTest.bad_dict.vcf is a vcf with two (2) ##contig lines deleted
- final File samSequenceDictionaryVcf = new File(TEST_DATA_PATH, "vcfFormatTest.bad_dict.vcf");
File outputFile = new File(outputFileName);
outputFile.deleteOnExit();
final UpdateVcfSequenceDictionary updateVcfSequenceDictionary = new UpdateVcfSequenceDictionary();
+ updateVcfSequenceDictionary.INPUT = INPUT_FILE;
+ updateVcfSequenceDictionary.SEQUENCE_DICTIONARY = SAM_SEQUENCE_DICTIONARY_VCF;
if (outputFileName.equals(STD_OUT_NAME)) {
-
final FileOutputStream stream = new FileOutputStream(STD_OUT_FILE);
// Ugliness required to write to a stream given as a string on the commandline.
@@ -80,25 +98,67 @@ public class UpdateVcfSequenceDictionaryTest {
final Field fdField = FileDescriptor.class.getDeclaredField("fd");
fdField.setAccessible(true);
updateVcfSequenceDictionary.OUTPUT = new File("/dev/fd/" + fdField.getInt(stream.getFD()));
-
} else {
- final FileOutputStream stream = null;
updateVcfSequenceDictionary.OUTPUT = outputFile;
}
- updateVcfSequenceDictionary.INPUT = input;
- updateVcfSequenceDictionary.SEQUENCE_DICTIONARY = samSequenceDictionaryVcf;
Assert.assertEquals(updateVcfSequenceDictionary.instanceMain(new String[0]), 0);
if (outputFileName.equals(STD_OUT_NAME)) {
outputFile = STD_OUT_FILE;
}
+ else if (outputFileName.endsWith(IOUtil.COMPRESSED_VCF_FILE_EXTENSION)) {
+ // Output is a gzipped vcf, unzip it
+ File unzippedOutputFile = new File(OUTPUT_DATA_PATH + ".out.vcf");
+ unzippedOutputFile.deleteOnExit();
+ unzipFile(outputFile, unzippedOutputFile);
+ outputFile = unzippedOutputFile;
+ }
- IOUtil.assertFilesEqual(samSequenceDictionaryVcf, outputFile);
+ IOUtil.assertFilesEqual(SAM_SEQUENCE_DICTIONARY_VCF, outputFile);
// A little extra checking.
- Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(input.toPath()).size(), 84);
- Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(samSequenceDictionaryVcf.toPath()).size(), 82);
+ Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(INPUT_FILE.toPath()).size(), 84);
+ Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(SAM_SEQUENCE_DICTIONARY_VCF.toPath()).size(), 82);
Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(outputFile.toPath()).size(), 82);
}
-}
+
+
+ private String classPath = "\\"" + System.getProperty("java.class.path") + "\\" ";
+
+ @Test
+ public void testCaptureStdout() throws IOException {
+ final File outputFile = File.createTempFile("UpdateVcfSequenceDictionaryTest.output.", ".vcf");
+ outputFile.deleteOnExit();
+
+ String[] command = {
+ "/bin/bash",
+ "-c",
+ "java -Dpicard.useLegacyParser=false -classpath " +
+ classPath +
+ "picard.cmdline.PicardCommandLine " +
+ "UpdateVcfSequenceDictionary " +
+ "-I " + INPUT_FILE.getAbsolutePath() + " " +
+ "-O /dev/stdout " +
+ "-SD " + SAM_SEQUENCE_DICTIONARY_VCF.getAbsolutePath()
+ };
+
+ try {
+ ProcessBuilder processBuilder = new ProcessBuilder(command);
+ processBuilder.inheritIO();
+ processBuilder.redirectOutput(outputFile);
+
+ Process process = processBuilder.start();
+ Assert.assertEquals(process.waitFor(), 0);
+
+ IOUtil.assertFilesEqual(SAM_SEQUENCE_DICTIONARY_VCF, outputFile);
+
+ // A little extra checking.
+ Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(INPUT_FILE.toPath()).size(), 84);
+ Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(SAM_SEQUENCE_DICTIONARY_VCF.toPath()).size(), 82);
+ Assert.assertEquals(SAMSequenceDictionaryExtractor.extractDictionary(outputFile.toPath()).size(), 82);
+ } catch (Exception e) {
+ Assert.fail("Failure executing UpdateVcfSequenceDictionary", e);
+ }
+ }
+}
\\ No newline at end of file | ['src/test/java/picard/vcf/UpdateVcfSequenceDictionaryTest.java', 'src/main/java/picard/vcf/UpdateVcfSequenceDictionary.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 3,627,078 | 776,709 | 79,753 | 451 | 520 | 94 | 11 | 1 | 448 | 50 | 110 | 3 | 1 | 0 | 1970-01-01T00:24:59 | 884 | Java | {'Java': 6182595, 'R': 26294, 'XSLT': 22469, 'Python': 17559, 'HTML': 11372, 'Shell': 10630, 'CSS': 3608, 'Dockerfile': 801, 'Rebol': 7} | MIT License |
1,004 | apicurio/apicurio-studio/1604/1533 | apicurio | apicurio-studio | https://github.com/Apicurio/apicurio-studio/issues/1533 | https://github.com/Apicurio/apicurio-studio/pull/1604 | https://github.com/Apicurio/apicurio-studio/pull/1604 | 1 | fixes | Imports must be resolved before mocking in Microcks | When trying to mock an API (that contains imported types) with microcks, the following errors occurs in the browser:
> io.apicurio.hub.core.exceptions.ServerError: Unexpected server error
> at io.apicurio.hub.api.rest.impl.DesignsResource.mockApi(DesignsResource.java:933)
> […]
> Caused by: io.apicurio.hub.api.microcks.MicrocksConnectorException: InternalServerError returned by Microcks server
> at io.apicurio.hub.api.microcks.MicrocksConnector.uploadResourceContent(MicrocksConnector.java:171)
> […]
Microcks logs the following:
> 12:21:55.071 ERROR 1 --- [080-exec-3] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: Invalid input: JSON Pointer expression must start with '/': "picurio:9#/components/responses/ForbiddenResponse"] with root cause
>
>java.lang.IllegalArgumentException: Invalid input: JSON Pointer expression must start with '/': "picurio:9#/components/responses/ForbiddenResponse"
where `ForbiddenResponse` is the imported type.
This leads me to believe that imports are currently not resolved before sending the API definition to microcks and microcks itself is unable to do so (which makes sense). | cc51237c008d280a12e2ec730b5642f849a9af29 | d6c7df3b236affee5b79bcac144f4f17f3d7f224 | https://github.com/apicurio/apicurio-studio/compare/cc51237c008d280a12e2ec730b5642f849a9af29...d6c7df3b236affee5b79bcac144f4f17f3d7f224 | diff --git a/back-end/hub-api/src/main/java/io/apicurio/hub/api/microcks/MicrocksConnector.java b/back-end/hub-api/src/main/java/io/apicurio/hub/api/microcks/MicrocksConnector.java
index f9c30ba6..4aad04d7 100644
--- a/back-end/hub-api/src/main/java/io/apicurio/hub/api/microcks/MicrocksConnector.java
+++ b/back-end/hub-api/src/main/java/io/apicurio/hub/api/microcks/MicrocksConnector.java
@@ -17,6 +17,7 @@
package io.apicurio.hub.api.microcks;
import java.io.ByteArrayInputStream;
+import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collection;
@@ -25,6 +26,7 @@ import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Default;
import javax.inject.Inject;
+import io.apicurio.hub.api.content.ContentDereferencer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,7 +41,7 @@ import io.apicurio.hub.core.config.HubConfiguration;
/**
* Default implementation of a Microcks connector.
- *
+ *
* @author [email protected]
*/
@ApplicationScoped
@@ -50,6 +52,8 @@ public class MicrocksConnector implements IMicrocksConnector {
@Inject
private HubConfiguration config;
+ @Inject
+ private ContentDereferencer dereferencer;
/** Microcks API URL (should ends with /api). */
private String apiURL;
@@ -73,7 +77,7 @@ public class MicrocksConnector implements IMicrocksConnector {
/**
* Returns the OAuth token to use when accessing Microcks.
- *
+ *
* @throws MicrocksConnectorException
*/
private String getKeycloakOAuthToken() throws MicrocksConnectorException {
@@ -135,12 +139,18 @@ public class MicrocksConnector implements IMicrocksConnector {
/**
* Upload an OAS v3 specification content to Microcks. This will trigger service discovery and mock
* endpoint publication on the Microcks side.
- *
+ *
* @param content OAS v3 specification content
* @throws MicrocksConnectorException if upload fails for many reasons
*/
public String uploadResourceContent(String content) throws MicrocksConnectorException {
String oauthToken = this.getKeycloakOAuthToken();
+ try {
+ content = dereferencer.dereference(content);
+ } catch (IOException e) {
+ logger.error("Could not dereference imports in specification content", e);
+ throw new MicrocksConnectorException("Could not dereference imports before sending to Microcks");
+ }
MultipartBody uploadRequest = Unirest.post(this.apiURL + "/artifact/upload")
.header("Authorization", "Bearer " + oauthToken)
.field("file", new ByteArrayInputStream(content.getBytes(Charset.forName("UTF-8"))), "open-api-contract.yml");
@@ -178,7 +188,7 @@ public class MicrocksConnector implements IMicrocksConnector {
/**
* Reserved for future usage.
- *
+ *
* @return List of repository secrets managed by Microcks server
* @throws MicrocksConnectorException if connection fails for any reasons
*/
@@ -188,7 +198,7 @@ public class MicrocksConnector implements IMicrocksConnector {
/**
* Reserved for future usage.
- *
+ *
* @return List of import jobs managed by Microcks server
* @throws MicrocksConnectorException if connection fails for any reasons
*/
@@ -198,7 +208,7 @@ public class MicrocksConnector implements IMicrocksConnector {
/**
* Reserved for future usage.
- *
+ *
* @param job Import job to create in Microcks server.
* @throws MicrocksConnectorException if connection fails for any reasons
*/
@@ -208,7 +218,7 @@ public class MicrocksConnector implements IMicrocksConnector {
/**
* Reserved for future usage.
- *
+ *
* @param job Import job to force import in Microcks server.
* @throws MicrocksConnectorException if connection fails for any reasons
*/ | ['back-end/hub-api/src/main/java/io/apicurio/hub/api/microcks/MicrocksConnector.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,094,436 | 231,785 | 33,392 | 306 | 574 | 127 | 24 | 1 | 1,310 | 133 | 301 | 17 | 0 | 0 | 1970-01-01T00:27:06 | 867 | TypeScript | {'TypeScript': 1453260, 'Java': 1410458, 'HTML': 647763, 'CSS': 241046, 'Shell': 5417, 'Scala': 4126, 'Dockerfile': 3804, 'Makefile': 2309, 'JavaScript': 382, 'Smarty': 176} | Apache License 2.0 |
1,276 | eclipse-vertx/vertx-sql-client/975/963 | eclipse-vertx | vertx-sql-client | https://github.com/eclipse-vertx/vertx-sql-client/issues/963 | https://github.com/eclipse-vertx/vertx-sql-client/pull/975 | https://github.com/eclipse-vertx/vertx-sql-client/pull/975 | 1 | fixes | Table created with non-nullable column even without `NOT NULL` in column definition | When using the MS SQL Client for `CREATE TABLE` statements, the resulting columns are non-`nullable` even when `NOT NULL` is not specified on the column definition.
This does not happen when using the JDBC client on the same database.
```java
PreparedStatement create = conn.prepareStatement("create table Basic (id int, dessimal numeric(19,2), primary key (id))");
create.executeUpdate();
PreparedStatement insert = conn.prepareStatement("INSERT INTO Basic (id, dessimal) values (3, ?)");
insert.setBigDecimal(1, new BigDecimal("3.2"));
insert.executeUpdate();
```
The snippet above works fine but this one fails:
```java
connnection.preparedQuery("create table Basic2 (id int, dessimal numeric(19,2), primary key (id))")
.execute(ctx.asyncAssertSuccess(create -> {
connnection.preparedQuery("INSERT INTO Basic2 (id, dessimal) values (3, @p1)")
.execute(Tuple.of(NullValue.BigDecimal), ctx.asyncAssertSuccess());
}));
```
The error message is:
```
io.vertx.mssqlclient.MSSQLException: {number=515, state=2, severity=16, message='Cannot insert the value NULL into column 'dessimal', table 'master.dbo.Basic2'; column does not allow nulls. INSERT fails.', serverName='0ac9600ef0bb', lineNumber=1}
```
As a workaround, the column definition must explicitly allow `NULL` values:
```sql
create table Basic2 (id int, dessimal numeric(19,2) null, primary key (id))
``` | 59a2187dfb498f99748d2f2f88034f704f82d11a | 70ac98aace8a145445d78c874d9327ac721ec538 | https://github.com/eclipse-vertx/vertx-sql-client/compare/59a2187dfb498f99748d2f2f88034f704f82d11a...70ac98aace8a145445d78c874d9327ac721ec538 | diff --git a/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/InitCommandCodec.java b/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/InitCommandCodec.java
index b862195d..1f24603b 100644
--- a/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/InitCommandCodec.java
+++ b/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/InitCommandCodec.java
@@ -86,9 +86,17 @@ class InitCommandCodec extends MSSQLCommandCodec<Connection, InitCommand> {
packet.writeIntLE(0x00); // ClientProgVer
packet.writeIntLE(0x00); // ClientPID
packet.writeIntLE(0x00); // ConnectionID
- packet.writeByte(LoginPacket.DEFAULT_OPTION_FLAGS1
- | LoginPacket.OPTION_FLAGS1_DUMPLOAD_OFF); // OptionFlags1
- packet.writeByte(LoginPacket.DEFAULT_OPTION_FLAGS2); // OptionFlags2
+ packet.writeByte(LoginPacket.DEFAULT_OPTION_FLAGS1 |
+ LoginPacket.OPTION_FLAGS1_ORDER_X86 |
+ LoginPacket.OPTION_FLAGS1_CHARSET_ASCII |
+ LoginPacket.OPTION_FLAGS1_FLOAT_IEEE_754 |
+ LoginPacket.OPTION_FLAGS1_USE_DB_OFF |
+ LoginPacket.OPTION_FLAGS1_INIT_DB_FATAL |
+ LoginPacket.OPTION_FLAGS1_SET_LANG_ON
+ ); // OptionFlags1
+ packet.writeByte(LoginPacket.DEFAULT_OPTION_FLAGS2 |
+ LoginPacket.OPTION_FLAGS2_ODBC_ON
+ ); // OptionFlags2
packet.writeByte(LoginPacket.DEFAULT_TYPE_FLAGS); // TypeFlags
packet.writeByte(LoginPacket.DEFAULT_OPTION_FLAGS3); // OptionFlags3
packet.writeIntLE(0x00); // ClientTimeZone
diff --git a/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/protocol/client/login/LoginPacket.java b/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/protocol/client/login/LoginPacket.java
index b0eef9b3..3f7b5d6c 100644
--- a/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/protocol/client/login/LoginPacket.java
+++ b/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/protocol/client/login/LoginPacket.java
@@ -37,7 +37,7 @@ public final class LoginPacket {
public static final byte OPTION_FLAGS1_ORDER_X68000 = 0x01;
public static final byte OPTION_FLAGS1_CHARSET_ASCII = 0x00;
public static final byte OPTION_FLAGS1_CHARSET_EBCDIC = 0x02;
- public static final byte OPTION_FALGS1_FLOAT_IEEE_754 = 0x00;
+ public static final byte OPTION_FLAGS1_FLOAT_IEEE_754 = 0x00;
public static final byte OPTION_FALGS1_FLOAT_VAX = 0x04;
public static final byte OPTION_FALGS1_ND5000 = 0x08;
public static final byte OPTION_FLAGS1_DUMPLOAD_ON = 0x00;
diff --git a/vertx-mssql-client/src/test/java/io/vertx/mssqlclient/MSSQLQueriesTest.java b/vertx-mssql-client/src/test/java/io/vertx/mssqlclient/MSSQLQueriesTest.java
index 54ed353e..823bb348 100644
--- a/vertx-mssql-client/src/test/java/io/vertx/mssqlclient/MSSQLQueriesTest.java
+++ b/vertx-mssql-client/src/test/java/io/vertx/mssqlclient/MSSQLQueriesTest.java
@@ -17,6 +17,7 @@ import io.vertx.ext.unit.junit.Repeat;
import io.vertx.ext.unit.junit.RepeatRule;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.sqlclient.Tuple;
+import io.vertx.sqlclient.data.NullValue;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
@@ -74,4 +75,16 @@ public class MSSQLQueriesTest extends MSSQLTestBase {
ctx.assertTrue(Math.abs(localDateTime.until(start, ChronoUnit.SECONDS)) < 1);
}));
}
+
+ @Test
+ public void testCreateTable(TestContext ctx) {
+ connnection.query("drop table if exists Basic")
+ .execute(ctx.asyncAssertSuccess(drop -> {
+ connnection.preparedQuery("create table Basic (id int, dessimal numeric(19,2), primary key (id))")
+ .execute(ctx.asyncAssertSuccess(create -> {
+ connnection.preparedQuery("INSERT INTO Basic (id, dessimal) values (3, @p1)")
+ .execute(Tuple.of(NullValue.BigDecimal), ctx.asyncAssertSuccess());
+ }));
+ }));
+ }
} | ['vertx-mssql-client/src/test/java/io/vertx/mssqlclient/MSSQLQueriesTest.java', 'vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/protocol/client/login/LoginPacket.java', 'vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/InitCommandCodec.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 2,148,524 | 503,522 | 61,249 | 369 | 813 | 198 | 16 | 2 | 1,416 | 158 | 340 | 33 | 0 | 4 | 1970-01-01T00:27:03 | 836 | Java | {'Java': 3751793, 'PLpgSQL': 22210, 'TSQL': 13875, 'PLSQL': 6105, 'Shell': 1839, 'Dockerfile': 200} | Apache License 2.0 |
1,275 | eclipse-vertx/vertx-sql-client/1252/1251 | eclipse-vertx | vertx-sql-client | https://github.com/eclipse-vertx/vertx-sql-client/issues/1251 | https://github.com/eclipse-vertx/vertx-sql-client/pull/1252 | https://github.com/eclipse-vertx/vertx-sql-client/pull/1252 | 1 | fixes | Type pollution agent report | ### Version
Using version `4.3.4`.
### Context
I've been running the Techempower benchmark with Quarkus + Hibernate Reactive + Vert.x `vertx-pg-client` and attaching the [agent to detect the type pollution cases](https://github.com/RedHatPerf/type-pollution-agent).
This agent is able to report cases of [JDK-8180450](https://bugs.openjdk.org/browse/JDK-8180450) in our libraries, which are very hard to spot otherwise but result in extreme performance penalties, so I'd recommend treating alerts from it at high priority - especially as fixes might be trivial, while returning very high performance impact.
This is the report output using today's Quarkus snapshot:
```
4: io.vertx.sqlclient.impl.ListTuple
Count: 14491599
Types:
io.vertx.sqlclient.impl.TupleInternal
io.vertx.sqlclient.Tuple
Traces:
io.vertx.sqlclient.impl.command.ExtendedQueryCommand.prepare(ExtendedQueryCommand.java:122)
class: io.vertx.sqlclient.impl.TupleInternal
count: 7070022
io.vertx.sqlclient.impl.command.ExtendedQueryCommand.params(ExtendedQueryCommand.java:160)
class: io.vertx.sqlclient.Tuple
count: 7029308
io.vertx.sqlclient.impl.command.ExtendedQueryCommand.prepare(ExtendedQueryCommand.java:115)
class: io.vertx.sqlclient.impl.TupleInternal
count: 193981
io.vertx.sqlclient.impl.command.ExtendedQueryCommand.prepare(ExtendedQueryCommand.java:114)
class: io.vertx.sqlclient.Tuple
count: 179589
io.vertx.pgclient.impl.codec.ExtendedQueryCommandCodec.encode(ExtendedQueryCommandCodec.java:51)
class: io.vertx.sqlclient.Tuple
count: 18699
```
Interpreting this, the problem is trivial: the same concrete type `io.vertx.sqlclient.impl.ListTuple` is occasionally being tested for being of type `io.vertx.sqlclient.impl.TupleInternal`, and occasionally for type `io.vertx.sqlclient.Tuple`.
Such alternating checks cause a problem with the internal type cache in hotspot, the simplest way to fix it is to always check for the same type.
Perusing the object hierarchy it seems any implementation of `Tuple` is always also a valid cast to `TupleInternal`, so my suggestion would be for all internal code to consistently cast to `TupleInternal`, and let the type get widened as needed (which doesn't need a check).
cc/ @tsegismont @vietj @franz1981 | 356d134b0e436647cb9ef6e105cf153a64b62431 | fec314bb3cdb65556873b4d8cc704bc3d4d40cc0 | https://github.com/eclipse-vertx/vertx-sql-client/compare/356d134b0e436647cb9ef6e105cf153a64b62431...fec314bb3cdb65556873b4d8cc704bc3d4d40cc0 | diff --git a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/ExtendedBatchQueryCommandCodec.java b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/ExtendedBatchQueryCommandCodec.java
index 1190c575..cd405d47 100644
--- a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/ExtendedBatchQueryCommandCodec.java
+++ b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/ExtendedBatchQueryCommandCodec.java
@@ -27,6 +27,7 @@ import io.vertx.db2client.impl.codec.DB2PreparedStatement.QueryInstance;
import io.vertx.db2client.impl.drda.DRDAQueryRequest;
import io.vertx.db2client.impl.drda.DRDAQueryResponse;
import io.vertx.sqlclient.Tuple;
+import io.vertx.sqlclient.impl.TupleInternal;
import io.vertx.sqlclient.impl.command.CommandResponse;
import io.vertx.sqlclient.impl.command.ExtendedQueryCommand;
@@ -34,7 +35,7 @@ class ExtendedBatchQueryCommandCodec<R> extends ExtendedQueryCommandBaseCodec<R,
private static final Logger LOG = LoggerFactory.getLogger(ExtendedBatchQueryCommandCodec.class);
- private final List<Tuple> params;
+ private final List<TupleInternal> params;
private final List<QueryInstance> queryInstances;
private final String baseCursorId;
diff --git a/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedBatchQueryCommandCodec.java b/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedBatchQueryCommandCodec.java
index 99dcd6d9..1a5759a4 100644
--- a/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedBatchQueryCommandCodec.java
+++ b/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedBatchQueryCommandCodec.java
@@ -12,7 +12,6 @@
package io.vertx.mssqlclient.impl.codec;
import io.netty.buffer.ByteBuf;
-import io.vertx.sqlclient.Tuple;
import io.vertx.sqlclient.impl.TupleInternal;
import io.vertx.sqlclient.impl.command.CommandResponse;
import io.vertx.sqlclient.impl.command.ExtendedQueryCommand;
@@ -21,7 +20,7 @@ import java.util.List;
class ExtendedBatchQueryCommandCodec<T> extends ExtendedQueryCommandBaseCodec<T> {
- private final List<Tuple> paramsList;
+ private final List<TupleInternal> paramsList;
private int paramsIdx;
private int messageDecoded;
@@ -52,7 +51,7 @@ class ExtendedBatchQueryCommandCodec<T> extends ExtendedQueryCommandBaseCodec<T>
@Override
protected TupleInternal prepexecRequestParams() {
paramsIdx = 1;
- return (TupleInternal) paramsList.get(0);
+ return paramsList.get(0);
}
@Override
@@ -67,6 +66,6 @@ class ExtendedBatchQueryCommandCodec<T> extends ExtendedQueryCommandBaseCodec<T>
@Override
protected TupleInternal execRequestParams() {
- return (TupleInternal) paramsList.get(paramsIdx);
+ return paramsList.get(paramsIdx);
}
}
diff --git a/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedCursorQueryCommandCodec.java b/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedCursorQueryCommandCodec.java
index a58ed0cb..4efb5961 100644
--- a/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedCursorQueryCommandCodec.java
+++ b/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedCursorQueryCommandCodec.java
@@ -175,7 +175,7 @@ class ExtendedCursorQueryCommandCodec<T> extends ExtendedQueryCommandBaseCodec<T
@Override
protected TupleInternal prepexecRequestParams() {
- return (TupleInternal) cmd.params();
+ return cmd.params();
}
@Override
diff --git a/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedQueryCommandCodec.java b/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedQueryCommandCodec.java
index 3106756b..8d4b8a59 100644
--- a/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedQueryCommandCodec.java
+++ b/vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedQueryCommandCodec.java
@@ -22,11 +22,11 @@ class ExtendedQueryCommandCodec<T> extends ExtendedQueryCommandBaseCodec<T> {
@Override
protected TupleInternal prepexecRequestParams() {
- return (TupleInternal) cmd.params();
+ return cmd.params();
}
@Override
protected TupleInternal execRequestParams() {
- return (TupleInternal) cmd.params();
+ return cmd.params();
}
}
diff --git a/vertx-mysql-client/src/main/java/io/vertx/mysqlclient/impl/codec/ExtendedBatchQueryCommandCodec.java b/vertx-mysql-client/src/main/java/io/vertx/mysqlclient/impl/codec/ExtendedBatchQueryCommandCodec.java
index 02b247ed..bf021292 100644
--- a/vertx-mysql-client/src/main/java/io/vertx/mysqlclient/impl/codec/ExtendedBatchQueryCommandCodec.java
+++ b/vertx-mysql-client/src/main/java/io/vertx/mysqlclient/impl/codec/ExtendedBatchQueryCommandCodec.java
@@ -16,6 +16,7 @@ import io.vertx.core.impl.NoStackTraceThrowable;
import io.vertx.mysqlclient.MySQLBatchException;
import io.vertx.mysqlclient.MySQLException;
import io.vertx.sqlclient.Tuple;
+import io.vertx.sqlclient.impl.TupleInternal;
import io.vertx.sqlclient.impl.command.CommandResponse;
import io.vertx.sqlclient.impl.command.ExtendedQueryCommand;
@@ -25,7 +26,7 @@ import static io.vertx.mysqlclient.impl.protocol.Packets.EnumCursorType.CURSOR_T
class ExtendedBatchQueryCommandCodec<R> extends ExtendedQueryCommandBaseCodec<R, ExtendedQueryCommand<R>> {
- private final List<Tuple> params;
+ private final List<TupleInternal> params;
private int batchIdx = 0;
ExtendedBatchQueryCommandCodec(ExtendedQueryCommand<R> cmd) {
diff --git a/vertx-oracle-client/src/main/java/io/vertx/oracleclient/impl/commands/OraclePreparedBatch.java b/vertx-oracle-client/src/main/java/io/vertx/oracleclient/impl/commands/OraclePreparedBatch.java
index c7958b54..32384edb 100644
--- a/vertx-oracle-client/src/main/java/io/vertx/oracleclient/impl/commands/OraclePreparedBatch.java
+++ b/vertx-oracle-client/src/main/java/io/vertx/oracleclient/impl/commands/OraclePreparedBatch.java
@@ -16,6 +16,7 @@ import io.vertx.oracleclient.OraclePrepareOptions;
import io.vertx.oracleclient.impl.Helper;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.Tuple;
+import io.vertx.sqlclient.impl.TupleInternal;
import io.vertx.sqlclient.impl.command.ExtendedQueryCommand;
import oracle.jdbc.OraclePreparedStatement;
@@ -30,9 +31,9 @@ import java.util.stream.Collector;
public class OraclePreparedBatch<C, R> extends QueryCommand<C, R> {
private final ExtendedQueryCommand<R> query;
- private final List<Tuple> listParams;
+ private final List<TupleInternal> listParams;
- public OraclePreparedBatch(ExtendedQueryCommand<R> query, Collector<Row, C, R> collector, List<Tuple> listParams) {
+ public OraclePreparedBatch(ExtendedQueryCommand<R> query, Collector<Row, C, R> collector, List<TupleInternal> listParams) {
super(collector);
this.query = query;
this.listParams = listParams;
diff --git a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/ExtendedQueryCommandCodec.java b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/ExtendedQueryCommandCodec.java
index c1db0d35..d3821b1d 100644
--- a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/ExtendedQueryCommandCodec.java
+++ b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/ExtendedQueryCommandCodec.java
@@ -16,7 +16,7 @@
*/
package io.vertx.pgclient.impl.codec;
-import io.vertx.sqlclient.Tuple;
+import io.vertx.sqlclient.impl.TupleInternal;
import io.vertx.sqlclient.impl.codec.InvalidCachedStatementEvent;
import io.vertx.sqlclient.impl.RowDesc;
import io.vertx.sqlclient.impl.command.CommandResponse;
@@ -48,7 +48,7 @@ class ExtendedQueryCommandCodec<R, C extends ExtendedQueryCommand<R>> extends Qu
completionHandler.handle(CommandResponse.failure("Can not execute batch query with 0 sets of batch parameters."));
return;
} else {
- for (Tuple param : cmd.paramsList()) {
+ for (TupleInternal param : cmd.paramsList()) {
encoder.writeBind(ps.bind, cmd.cursorId(), param);
encoder.writeExecute(cmd.cursorId(), cmd.fetch());
}
diff --git a/vertx-sql-client-templates/src/main/java/io/vertx/sqlclient/templates/impl/JsonTuple.java b/vertx-sql-client-templates/src/main/java/io/vertx/sqlclient/templates/impl/JsonTuple.java
index a90f83ef..9a204318 100644
--- a/vertx-sql-client-templates/src/main/java/io/vertx/sqlclient/templates/impl/JsonTuple.java
+++ b/vertx-sql-client-templates/src/main/java/io/vertx/sqlclient/templates/impl/JsonTuple.java
@@ -16,7 +16,7 @@ import io.vertx.sqlclient.impl.TupleInternal;
import java.util.function.Function;
-public class JsonTuple implements TupleInternal {
+public class JsonTuple extends TupleInternal {
private final int size;
private final Function<Integer, String> columnMapping;
diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/ArrayTuple.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/ArrayTuple.java
index 9cd1e2a9..46e2fcf9 100644
--- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/ArrayTuple.java
+++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/ArrayTuple.java
@@ -22,7 +22,7 @@ import io.vertx.sqlclient.Tuple;
import java.util.Arrays;
import java.util.Collection;
-public class ArrayTuple implements TupleInternal {
+public class ArrayTuple extends TupleInternal {
private static final Object[] EMPTY_ARRAY = new Object[0];
public static Tuple EMPTY = new ArrayTuple(0);
diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/ListTuple.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/ListTuple.java
index f813465b..1591fe6f 100644
--- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/ListTuple.java
+++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/ListTuple.java
@@ -21,7 +21,7 @@ import io.vertx.sqlclient.Tuple;
import java.util.List;
-public class ListTuple implements TupleInternal {
+public class ListTuple extends TupleInternal {
private final List<Object> list;
diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/TupleInternal.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/TupleInternal.java
index e4eb9805..c45a6111 100644
--- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/TupleInternal.java
+++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/TupleInternal.java
@@ -17,20 +17,20 @@ import io.vertx.sqlclient.data.NullValue;
import java.util.ArrayList;
import java.util.List;
-public interface TupleInternal extends Tuple {
+public abstract class TupleInternal implements Tuple {
- void setValue(int pos, Object value);
+ public abstract void setValue(int pos, Object value);
@Override
- default Object getValue(int pos) {
+ public Object getValue(int pos) {
Object val = getValueInternal(pos);
return val instanceof NullValue ? null : val;
}
- Object getValueInternal(int pos);
+ public abstract Object getValueInternal(int pos);
@Override
- default List<Class<?>> types() {
+ public List<Class<?>> types() {
int len = size();
List<Class<?>> types = new ArrayList<>(len);
for (int i = 0; i < len; i++) {
diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/command/ExtendedQueryCommand.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/command/ExtendedQueryCommand.java
index 18d5f40a..3d70a8fe 100644
--- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/command/ExtendedQueryCommand.java
+++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/command/ExtendedQueryCommand.java
@@ -111,8 +111,8 @@ public class ExtendedQueryCommand<R> extends QueryCommandBase<R> {
public String prepare() {
if (ps != null) {
if (batch) {
- for (Tuple tuple : (List<Tuple>) tuples) {
- String msg = ps.prepare((TupleInternal) tuple);
+ for (TupleInternal tuple : (List<TupleInternal>) tuples) {
+ String msg = ps.prepare(tuple);
if (msg != null) {
return msg;
}
@@ -132,8 +132,8 @@ public class ExtendedQueryCommand<R> extends QueryCommandBase<R> {
/**
* @return the list of parameters for batch execution
*/
- public List<Tuple> paramsList() {
- return batch ? (List<Tuple>) tuples : null;
+ public List<TupleInternal> paramsList() {
+ return batch ? (List<TupleInternal>) tuples : null;
}
/**
@@ -148,7 +148,7 @@ public class ExtendedQueryCommand<R> extends QueryCommandBase<R> {
}
tuple = list.get(0);
} else {
- tuple = (Tuple) tuples;
+ tuple = (TupleInternal) tuples;
}
return tuple.types();
}
@@ -156,8 +156,8 @@ public class ExtendedQueryCommand<R> extends QueryCommandBase<R> {
/**
* @return the parameters for query execution
*/
- public Tuple params() {
- return batch ? null : (Tuple) tuples;
+ public TupleInternal params() {
+ return batch ? null : (TupleInternal) tuples;
}
public PreparedStatement preparedStatement() { | ['vertx-oracle-client/src/main/java/io/vertx/oracleclient/impl/commands/OraclePreparedBatch.java', 'vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedBatchQueryCommandCodec.java', 'vertx-mysql-client/src/main/java/io/vertx/mysqlclient/impl/codec/ExtendedBatchQueryCommandCodec.java', 'vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/ExtendedQueryCommandCodec.java', 'vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/TupleInternal.java', 'vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedCursorQueryCommandCodec.java', 'vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/ArrayTuple.java', 'vertx-mssql-client/src/main/java/io/vertx/mssqlclient/impl/codec/ExtendedQueryCommandCodec.java', 'vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/ExtendedBatchQueryCommandCodec.java', 'vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/command/ExtendedQueryCommand.java', 'vertx-sql-client-templates/src/main/java/io/vertx/sqlclient/templates/impl/JsonTuple.java', 'vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/ListTuple.java'] | {'.java': 12} | 12 | 12 | 0 | 0 | 12 | 2,417,177 | 567,261 | 69,946 | 419 | 2,691 | 572 | 58 | 12 | 2,302 | 224 | 545 | 42 | 2 | 1 | 1970-01-01T00:27:47 | 836 | Java | {'Java': 3751793, 'PLpgSQL': 22210, 'TSQL': 13875, 'PLSQL': 6105, 'Shell': 1839, 'Dockerfile': 200} | Apache License 2.0 |
1,274 | eclipse-vertx/vertx-sql-client/662/666 | eclipse-vertx | vertx-sql-client | https://github.com/eclipse-vertx/vertx-sql-client/issues/666 | https://github.com/eclipse-vertx/vertx-sql-client/pull/662 | https://github.com/eclipse-vertx/vertx-sql-client/pull/662#issuecomment-635472139 | 1 | fixes | Recycling pooled connection events are not emitted on the eventloop context associated with connection pool | ### Version
it should be only in 4.0
Currently recycling pooled connection events are not emitted on the eventloop context associated with connection pool and are emitted on the caller thread which might cause a racy access to the states of connection pool | a4e49c55966a87043b078e70f1594029d5dadea6 | 4ce65f3e87ec4dc8cc48de03ecc8cd3c17f48f3c | https://github.com/eclipse-vertx/vertx-sql-client/compare/a4e49c55966a87043b078e70f1594029d5dadea6...4ce65f3e87ec4dc8cc48de03ecc8cd3c17f48f3c | diff --git a/vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTestBase.java b/vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTestBase.java
index 529e505e..0ec4f5cd 100644
--- a/vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTestBase.java
+++ b/vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTestBase.java
@@ -55,15 +55,15 @@ public abstract class PgPoolTestBase extends PgTestBase {
@Test
public void testPool(TestContext ctx) {
- int num = 1000;
+ int num = 5000;
Async async = ctx.async(num);
PgPool pool = createPool(options, 4);
for (int i = 0;i < num;i++) {
pool.getConnection(ctx.asyncAssertSuccess(conn -> {
- conn.query("SELECT id, randomnumber from WORLD WHERE id = 1").execute(ar -> {
+ conn.query("SELECT id, randomnumber from WORLD").execute(ar -> {
if (ar.succeeded()) {
SqlResult result = ar.result();
- ctx.assertEquals(1, result.size());
+ ctx.assertEquals(10000, result.size());
} else {
ctx.assertEquals("closed", ar.cause().getMessage());
}
@@ -80,10 +80,10 @@ public abstract class PgPoolTestBase extends PgTestBase {
Async async = ctx.async(num);
PgPool pool = createPool(options, 4);
for (int i = 0;i < num;i++) {
- pool.query("SELECT id, randomnumber from WORLD WHERE id = 1").execute(ar -> {
+ pool.query("SELECT id, randomnumber from WORLD").execute(ar -> {
if (ar.succeeded()) {
SqlResult result = ar.result();
- ctx.assertEquals(1, result.size());
+ ctx.assertEquals(10000, result.size());
} else {
ctx.assertEquals("closed", ar.cause().getMessage());
}
diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/ConnectionPool.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/ConnectionPool.java
index 7c92c0e2..b9c115d9 100644
--- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/ConnectionPool.java
+++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/ConnectionPool.java
@@ -169,6 +169,14 @@ public class ConnectionPool {
@Override
public void close(Holder holder, Promise<Void> promise) {
+ if (context != null) {
+ context.dispatch(v -> doClose(holder, promise));
+ } else {
+ doClose(holder, promise);
+ }
+ }
+
+ private void doClose(Holder holder, Promise<Void> promise) {
if (holder != this.holder) {
String msg;
if (this.holder == null) { | ['vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTestBase.java', 'vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/pool/ConnectionPool.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,017,846 | 473,340 | 57,700 | 353 | 222 | 49 | 8 | 1 | 262 | 43 | 50 | 5 | 0 | 0 | 1970-01-01T00:26:30 | 836 | Java | {'Java': 3751793, 'PLpgSQL': 22210, 'TSQL': 13875, 'PLSQL': 6105, 'Shell': 1839, 'Dockerfile': 200} | Apache License 2.0 |
1,280 | eclipse-vertx/vertx-sql-client/836/833 | eclipse-vertx | vertx-sql-client | https://github.com/eclipse-vertx/vertx-sql-client/issues/833 | https://github.com/eclipse-vertx/vertx-sql-client/pull/836 | https://github.com/eclipse-vertx/vertx-sql-client/pull/836 | 1 | fixes | Improve transaction rollback of an already completed transaction | The implementation of the `Transaction` does not handle correctly reentrant termination of the transaction, i.e calling `rollback` or `commit` while the transaction state becomes completed. This can lead to releasing twice the connection to the connection pool preventing the state of the application to progress.
Here is a reproducer:
```java
@Test
public void testReproducer(TestContext ctx) {
Async async = ctx.async();
connector.accept(ctx.asyncAssertSuccess(tx -> {
tx.query("SELECT whatever from DOES_NOT_EXIST").execute(ctx.asyncAssertFailure());
tx.query("SELECT 1").execute(ctx.asyncAssertFailure(err -> {
tx.rollback(ctx.asyncAssertFailure(v -> {
// Already rolled back
async.complete();
}));
}));
}));
}
```
This test adds 2 queries to the same transaction and add the second before the result of the first query (thing that is not possible with synchronous API, unless 2 threads are used).
When the first query is executed, the transaction is rolled backed and with the current implementation it will fail all the pending queries (See TransactionImpl#wrap method) before the transaction is rolled back (same method after).
This test will rollback the transaction in the completion handler of the 2nd query and then the transaction will try to roll back the transaction. This will result in 2 callbacks that will both try to return the connection to the pool and the 2nd one will fail with an IllegalStateException.
| bb56e651a9c851fd475631e1e9acace69bd006bc | e687fb7a088b65036021d34cafd09f71f6bb37ba | https://github.com/eclipse-vertx/vertx-sql-client/compare/bb56e651a9c851fd475631e1e9acace69bd006bc...e687fb7a088b65036021d34cafd09f71f6bb37ba | diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/TransactionImpl.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/TransactionImpl.java
index 9493be0f..63bac5a8 100644
--- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/TransactionImpl.java
+++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/TransactionImpl.java
@@ -33,9 +33,6 @@ import io.vertx.sqlclient.impl.command.TxCommand;
class TransactionImpl implements Transaction {
- private static final TxCommand<Void> ROLLBACK = new TxCommand<>(TxCommand.Kind.ROLLBACK, null);
- private static final TxCommand<Void> COMMIT = new TxCommand<>(TxCommand.Kind.COMMIT, null);
-
private static final int ST_BEGIN = 0;
private static final int ST_PENDING = 1;
private static final int ST_PROCESSING = 2;
@@ -43,7 +40,7 @@ class TransactionImpl implements Transaction {
private final ContextInternal context;
private final Connection connection;
- private Deque<ScheduledCommand<?>> pending = new ArrayDeque<>();
+ private final Deque<CommandBase<?>> pending = new ArrayDeque<>();
private int status = ST_BEGIN;
private final Promise<Void> completion;
@@ -53,66 +50,34 @@ class TransactionImpl implements Transaction {
this.completion = context.promise();
}
- static class ScheduledCommand<R> {
- final CommandBase<R> cmd;
- final Handler<AsyncResult<R>> handler;
- ScheduledCommand(CommandBase<R> cmd, Handler<AsyncResult<R>> handler) {
- this.cmd = cmd;
- this.handler = handler;
- }
- }
-
Future<Transaction> begin() {
PromiseInternal<Transaction> promise = context.promise(this::afterBegin);
- ScheduledCommand<Transaction> b = doQuery(new TxCommand<>(TxCommand.Kind.BEGIN, this), promise);
- doSchedule(b.cmd, b.handler);
+ TxCommand<Transaction> begin = new TxCommand<>(TxCommand.Kind.BEGIN, this);
+ begin.handler = wrap(promise);
+ execute(begin);
return promise.future();
}
- private <R> void doSchedule(CommandBase<R> cmd, Handler<AsyncResult<R>> handler) {
- connection.schedule(cmd, context.promise(handler));
+ private <R> void execute(CommandBase<R> cmd) {
+ connection.schedule(cmd, context.promise(cmd.handler));
}
- private <R> void wrapAndSchedule(ScheduledCommand<R> scheduled) {
- CommandBase<R> cmd = scheduled.cmd;
- if (isComplete(cmd)) {
- status = ST_COMPLETED;
- doSchedule(cmd, ar -> {
- if (ar.succeeded()) {
- if (cmd == COMMIT) {
- completion.tryComplete();
- } else {
- completion.tryFail(TransactionRollbackException.INSTANCE);
- }
- } else {
- completion.tryFail(ar.cause());
- }
- scheduled.handler.handle(ar);
- });
- } else {
- status = ST_PROCESSING;
- doSchedule(cmd, wrap(scheduled.handler));
- }
- }
-
- private <T> Handler<AsyncResult<T>> wrap(Handler<AsyncResult<T>> handler) {
+ private <T> Handler<AsyncResult<T>> wrap(Promise<T> handler) {
return ar -> {
synchronized (TransactionImpl.this) {
- status = ST_PENDING;
- if (ar.failed()) {
- // We won't recover from this so rollback
- ScheduledCommand<?> c;
- while ((c = pending.poll()) != null) {
- c.handler.handle(Future.failedFuture("Rollback exception"));
- }
- schedule__(doQuery(ROLLBACK, context.promise(ar2 -> {
- handler.handle(ar);
- })));
- } else {
- handler.handle(ar);
- checkPending();
+ if (status == ST_PROCESSING) {
+ status = ST_PENDING;
}
}
+ if (ar.failed()) {
+ // We won't recover from this so rollback
+ rollback(a -> {
+ handler.handle(ar);
+ });
+ } else {
+ handler.handle(ar);
+ checkPending();
+ }
};
}
@@ -125,70 +90,51 @@ class TransactionImpl implements Transaction {
checkPending();
}
- private static boolean isComplete(CommandBase<?> cmd) {
- if (cmd instanceof TxCommand) {
- TxCommand txCmd = (TxCommand) cmd;
- return txCmd.kind == TxCommand.Kind.COMMIT || txCmd.kind == TxCommand.Kind.ROLLBACK;
- }
- return false;
- }
-
-
- private synchronized void checkPending() {
- switch (status) {
- case ST_BEGIN:
- break;
- case ST_PENDING: {
- ScheduledCommand<?> cmd = pending.poll();
- if (cmd != null) {
- wrapAndSchedule(cmd);
- }
- break;
- }
- case ST_PROCESSING:
- break;
- case ST_COMPLETED: {
- if (pending.size() > 0) {
- VertxException err = new VertxException("Transaction already completed");
- ScheduledCommand<?> cmd;
- while ((cmd = pending.poll()) != null) {
- cmd.cmd.fail(err);
- }
+ private void checkPending() {
+ while (true) {
+ CommandBase<?> cmd;
+ synchronized (this) {
+ switch (status) {
+ case ST_PENDING:
+ cmd = pending.poll();
+ if (cmd != null) {
+ status = ST_PROCESSING;
+ execute(cmd);
+ }
+ return;
+ case ST_COMPLETED:
+ cmd = pending.poll();
+ if (cmd == null) {
+ return;
+ }
+ break;
+ default:
+ return;
}
- break;
}
+ VertxException err = new VertxException("Transaction already completed", false);
+ cmd.fail(err);
}
}
public <R> void schedule(CommandBase<R> cmd, Promise<R> handler) {
- schedule__(cmd, handler);
+ cmd.handler = wrap(handler);
+ schedule(cmd);
}
- public <R> void schedule__(ScheduledCommand<R> b) {
+ public <R> void schedule(CommandBase<R> b) {
synchronized (this) {
pending.add(b);
}
checkPending();
}
- public <R> void schedule__(CommandBase<R> cmd, Handler<AsyncResult<R>> handler) {
- schedule__(new ScheduledCommand<>(cmd, handler));
- }
-
@Override
public Future<Void> commit() {
- switch (status) {
- case ST_BEGIN:
- case ST_PENDING:
- case ST_PROCESSING:
- Promise<Void> promise = context.promise();
- schedule__(doQuery(COMMIT, promise));
- return promise.future();
- case ST_COMPLETED:
- return context.failedFuture("Transaction already completed");
- default:
- throw new IllegalStateException();
- }
+ Promise<Void> promise = context.promise();
+ CommandBase<Void> commit = txCommand(TxCommand.Kind.COMMIT, promise);
+ schedule(commit);
+ return promise.future();
}
public void commit(Handler<AsyncResult<Void>> handler) {
@@ -200,13 +146,13 @@ class TransactionImpl implements Transaction {
@Override
public Future<Void> rollback() {
- if (status == ST_COMPLETED) {
- return context.failedFuture("Transaction already completed");
- } else {
- Promise<Void> promise = context.promise();
- schedule__(doQuery(ROLLBACK, promise));
- return promise.future();
+ Promise<Void> promise = context.promise();
+ TxCommand<Void> rollback = txCommand(TxCommand.Kind.ROLLBACK, promise);
+ synchronized (this) {
+ pending.addFirst(rollback);
}
+ checkPending();
+ return promise.future();
}
public void rollback(Handler<AsyncResult<Void>> handler) {
@@ -216,8 +162,31 @@ class TransactionImpl implements Transaction {
}
}
- private <R> ScheduledCommand<R> doQuery(TxCommand<R> cmd, Promise<R> handler) {
- return new ScheduledCommand<>(cmd, handler);
+ private TxCommand<Void> txCommand(TxCommand.Kind kind, Promise<Void> promise) {
+ TxCommand<Void> cmd = new TxCommand<>(kind, null);
+ cmd.handler = ar -> {
+ tryComplete(kind);
+ promise.handle(ar);
+ };
+ return cmd;
+ }
+
+ private void tryComplete(TxCommand.Kind kind) {
+ synchronized (this) {
+ if (status == ST_COMPLETED) {
+ return;
+ }
+ status = ST_COMPLETED;
+ }
+ switch (kind) {
+ case COMMIT:
+ completion.complete();
+ break;
+ case ROLLBACK:
+ completion.fail(TransactionRollbackException.INSTANCE);
+ break;
+ }
+ checkPending();
}
@Override
diff --git a/vertx-sql-client/src/test/java/io/vertx/sqlclient/tck/TransactionTestBase.java b/vertx-sql-client/src/test/java/io/vertx/sqlclient/tck/TransactionTestBase.java
index 1547b6a7..5b75a494 100644
--- a/vertx-sql-client/src/test/java/io/vertx/sqlclient/tck/TransactionTestBase.java
+++ b/vertx-sql-client/src/test/java/io/vertx/sqlclient/tck/TransactionTestBase.java
@@ -252,6 +252,21 @@ public abstract class TransactionTestBase {
}));
}
+ @Test
+ public void testRollbackPendingQueries(TestContext ctx) {
+ Async async = ctx.async();
+ connector.accept(ctx.asyncAssertSuccess(res -> {
+ res.client.query("SELECT whatever from DOES_NOT_EXIST").execute(ctx.asyncAssertFailure(v -> {
+ }));
+ res.client.query("SELECT 1").execute(ctx.asyncAssertFailure(err -> {
+ res.tx.rollback(ctx.asyncAssertFailure(v -> {
+ // Already rolled back
+ async.complete();
+ }));
+ }));
+ }));
+ }
+
@Test
public void testWithTransactionCommit(TestContext ctx) {
Async async = ctx.async(); | ['vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/TransactionImpl.java', 'vertx-sql-client/src/test/java/io/vertx/sqlclient/tck/TransactionTestBase.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,089,045 | 489,298 | 59,630 | 359 | 6,368 | 1,352 | 187 | 1 | 1,527 | 203 | 302 | 26 | 0 | 1 | 1970-01-01T00:26:47 | 836 | Java | {'Java': 3751793, 'PLpgSQL': 22210, 'TSQL': 13875, 'PLSQL': 6105, 'Shell': 1839, 'Dockerfile': 200} | Apache License 2.0 |
1,278 | eclipse-vertx/vertx-sql-client/855/851 | eclipse-vertx | vertx-sql-client | https://github.com/eclipse-vertx/vertx-sql-client/issues/851 | https://github.com/eclipse-vertx/vertx-sql-client/pull/855 | https://github.com/eclipse-vertx/vertx-sql-client/pull/855 | 1 | fixes | PreparedQuery does not take parameter types into account | This bug reports follows-up on https://github.com/quarkusio/quarkus/issues/11501
The user initially reported they were not able to insert into jsonb column with Pg Client whereas the same query with Postgres JDBC works.
I proposed a better query to the user that works with both Postgres JDBC and the Pg Client as a workaround.
As for the issue, I did a little research and it seems the Pg client does not always send parameter types when preparing a query.
Consider the following table:
```sql
CREATE TABLE object_data (data JSONB)
```
And the following query:
```
INSERT INTO object_data (data) VALUES (to_json($1)) RETURNING (data)
```
If you execute:
```java
PreparedQuery<RowSet<Row>> insertQuery = pgConnection.preparedQuery("INSERT INTO object_data (data) VALUES (to_json($1)) RETURNING (data)");
insertQuery.execute(Tuple.of("toto"), ctx.asyncAssertSuccess(rs -> {
Row row = rs.iterator().next();
Object value = row.getJson(0);
System.out.println("value = " + value);
}));
```
You will see:
```
io.vertx.pgclient.PgException: { "message": "could not determine polymorphic type because input has type unknown", "severity": "ERROR", "code": "42804", "file": "parse_coerce.c", "line": "1866", "routine": "enforce_generic_type_consistency" }
```
But if you change this:
https://github.com/eclipse-vertx/vertx-sql-client/blob/a08a7d7d97bdfa9b209afd76d866f4915d448712/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/SocketConnectionBase.java#L194
to
```java
PrepareStatementCommand prepareCmd = prepareCommand(queryCmd, cache, true);
```
Then you get the expected result:
```
value = toto
```
My understanding is that we do not want to send the parameters because we wouldn't be able to cache the prepared statement, correct?
I believe Posgres JDBC checks if the types are the same before reusing a cached statement and, if they are not the same, prepares the statement again with new types. | cc3b6c99c7110ad98fd350c3d7f51b997c907305 | 93b12a0ed0205093e1cf933f637eab9ea9e1dbed | https://github.com/eclipse-vertx/vertx-sql-client/compare/cc3b6c99c7110ad98fd350c3d7f51b997c907305...93b12a0ed0205093e1cf933f637eab9ea9e1dbed | diff --git a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgSocketConnection.java b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgSocketConnection.java
index 0820a4c3..6b2bfb84 100644
--- a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgSocketConnection.java
+++ b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgSocketConnection.java
@@ -19,23 +19,17 @@ package io.vertx.pgclient.impl;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.DecoderException;
-import io.vertx.core.impl.ContextInternal;
+import io.vertx.core.AsyncResult;
+import io.vertx.core.Future;
+import io.vertx.core.Handler;
+import io.vertx.core.Promise;
+import io.vertx.core.buffer.Buffer;
import io.vertx.core.impl.EventLoopContext;
+import io.vertx.core.net.impl.NetSocketInternal;
import io.vertx.pgclient.PgException;
import io.vertx.pgclient.impl.codec.PgCodec;
-import io.vertx.sqlclient.impl.Connection;
-import io.vertx.sqlclient.impl.Notice;
-import io.vertx.sqlclient.impl.Notification;
-import io.vertx.sqlclient.impl.QueryResultHandler;
-import io.vertx.sqlclient.impl.SocketConnectionBase;
-import io.vertx.sqlclient.impl.command.CommandBase;
-import io.vertx.sqlclient.impl.command.InitCommand;
-import io.vertx.core.*;
-import io.vertx.core.buffer.Buffer;
-import io.vertx.core.net.impl.NetSocketInternal;
-import io.vertx.sqlclient.impl.command.QueryCommandBase;
-import io.vertx.sqlclient.impl.command.SimpleQueryCommand;
-import io.vertx.sqlclient.impl.command.TxCommand;
+import io.vertx.sqlclient.impl.*;
+import io.vertx.sqlclient.impl.command.*;
import io.vertx.sqlclient.spi.DatabaseMetadata;
import java.util.Map;
@@ -161,8 +155,8 @@ public class PgSocketConnection extends SocketConnectionBase {
@Override
public boolean isIndeterminatePreparedStatementError(Throwable error) {
if (error instanceof PgException) {
- PgException e = (PgException) error;
- return "42P18".equals(e.getCode());
+ String code = ((PgException) error).getCode();
+ return "42P18".equals(code) || "42804".equals(code);
}
return false;
}
diff --git a/vertx-pg-client/src/test/java/io/vertx/pgclient/PreparedStatementTestBase.java b/vertx-pg-client/src/test/java/io/vertx/pgclient/PreparedStatementTestBase.java
index a84ef22d..8b7cd99a 100644
--- a/vertx-pg-client/src/test/java/io/vertx/pgclient/PreparedStatementTestBase.java
+++ b/vertx-pg-client/src/test/java/io/vertx/pgclient/PreparedStatementTestBase.java
@@ -24,31 +24,14 @@ import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
-import io.vertx.pgclient.data.Box;
-import io.vertx.pgclient.data.Circle;
-import io.vertx.pgclient.data.Interval;
-import io.vertx.pgclient.data.Line;
-import io.vertx.pgclient.data.LineSegment;
-import io.vertx.pgclient.data.Path;
-import io.vertx.pgclient.data.Point;
-import io.vertx.pgclient.data.Polygon;
-import io.vertx.sqlclient.Cursor;
-import io.vertx.sqlclient.Row;
-import io.vertx.sqlclient.RowIterator;
-import io.vertx.sqlclient.RowSet;
-import io.vertx.sqlclient.RowStream;
-import io.vertx.sqlclient.Tuple;
+import io.vertx.pgclient.data.*;
+import io.vertx.sqlclient.*;
import org.junit.After;
import org.junit.Before;
-import org.junit.Rule;
import org.junit.Test;
import java.lang.reflect.Array;
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.time.OffsetDateTime;
-import java.time.ZoneOffset;
+import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
@@ -552,4 +535,16 @@ public abstract class PreparedStatementTestBase extends PgTestBase {
}));
}));
}
+
+ @Test
+ public void testInferDataTypeLazyPolymorphic(TestContext ctx) {
+ PgConnection.connect(vertx, options(), ctx.asyncAssertSuccess(conn -> {
+ conn.prepare("SELECT to_jsonb($1)", ctx.asyncAssertSuccess(ps -> {
+ ps.query().execute(Tuple.of("foo"), ctx.asyncAssertSuccess(result -> {
+ ctx.assertEquals("foo", result.iterator().next().getString(0));
+ conn.close();
+ }));
+ }));
+ }));
+ }
} | ['vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgSocketConnection.java', 'vertx-pg-client/src/test/java/io/vertx/pgclient/PreparedStatementTestBase.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,094,598 | 490,795 | 59,751 | 361 | 1,159 | 236 | 26 | 1 | 1,982 | 243 | 488 | 56 | 2 | 6 | 1970-01-01T00:26:48 | 836 | Java | {'Java': 3751793, 'PLpgSQL': 22210, 'TSQL': 13875, 'PLSQL': 6105, 'Shell': 1839, 'Dockerfile': 200} | Apache License 2.0 |
1,279 | eclipse-vertx/vertx-sql-client/848/847 | eclipse-vertx | vertx-sql-client | https://github.com/eclipse-vertx/vertx-sql-client/issues/847 | https://github.com/eclipse-vertx/vertx-sql-client/pull/848 | https://github.com/eclipse-vertx/vertx-sql-client/pull/848 | 1 | fix | [vertx 4.0.0] Connection.close callback may not be called | ### Version
Vertx 4.0.0
### Context
Some code working in vertx 3.9.x begin to hang.
After investigation it was comming from `connection.close().await()` (using kotlin-coroutine)
Replacing the kotlin extension `await()` by `onSuccess { ... }.onFailure{ ... }.onComplete{ ... }` showed that none is called.
### Do you have a reproducer?
No, but I think I have an explaination.
The method `close()` is called on a `ConnectionConnectionImpl`. This method create a new `Promise` then call `close(Promise ...)`
If the context is not vertx current context, it dispatch a new `close()` call in the context. But this call has no link to the promise created by the initial `close()` call.
```
@Override
public Future<Void> close() {
Promise<Void> promise = promise(); // new promise here
close(promise);
return promise.future();
}
private void close(Promise<Void> promise) {
if (context == Vertx.currentContext()) {
if (tx != null) {
tx.rollback(ar -> conn.close(this, promise));
tx = null;
} else {
conn.close(this, promise);
}
} else {
context.runOnContext(v -> close()); // so `promise` argument of method is never used, a close() will generate a new one
}
}
```
| 33407c3ddfc8cd7affe2e77c585b97a5afd62f19 | ce73aae89f5b511e222bceb2c6d7650fa164d448 | https://github.com/eclipse-vertx/vertx-sql-client/compare/33407c3ddfc8cd7affe2e77c585b97a5afd62f19...ce73aae89f5b511e222bceb2c6d7650fa164d448 | diff --git a/vertx-pg-client/src/test/java/io/vertx/pgclient/PgConnectionTestBase.java b/vertx-pg-client/src/test/java/io/vertx/pgclient/PgConnectionTestBase.java
index 30b3f931..ab4cd49e 100644
--- a/vertx-pg-client/src/test/java/io/vertx/pgclient/PgConnectionTestBase.java
+++ b/vertx-pg-client/src/test/java/io/vertx/pgclient/PgConnectionTestBase.java
@@ -462,4 +462,20 @@ public abstract class PgConnectionTestBase extends PgClientTestBase<SqlConnectio
});
}));
}
+
+ @Test
+ public void testCloseConnectionFromDifferentContext(TestContext ctx) {
+ Async done = ctx.async(1);
+ connector.accept(ctx.asyncAssertSuccess(conn -> {
+ conn.query("SELECT 1").execute(ctx.asyncAssertSuccess(res -> {
+ ctx.assertEquals(1, res.size());
+ // schedule from another context
+ new Thread(() -> {
+ conn.close(v2 -> {
+ done.complete();
+ });
+ }).start();
+ }));
+ }));
+ }
}
diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/SqlConnectionImpl.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/SqlConnectionImpl.java
index a2d516a8..ff2348da 100644
--- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/SqlConnectionImpl.java
+++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/SqlConnectionImpl.java
@@ -149,7 +149,7 @@ public class SqlConnectionImpl<C extends SqlConnection> extends SqlConnectionBas
conn.close(this, promise);
}
} else {
- context.runOnContext(v -> close());
+ context.runOnContext(v -> close(promise));
}
}
} | ['vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/SqlConnectionImpl.java', 'vertx-pg-client/src/test/java/io/vertx/pgclient/PgConnectionTestBase.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,098,341 | 491,299 | 59,913 | 361 | 92 | 20 | 2 | 1 | 1,280 | 178 | 306 | 39 | 0 | 1 | 1970-01-01T00:26:47 | 836 | Java | {'Java': 3751793, 'PLpgSQL': 22210, 'TSQL': 13875, 'PLSQL': 6105, 'Shell': 1839, 'Dockerfile': 200} | Apache License 2.0 |
1,282 | eclipse-vertx/vertx-sql-client/706/671 | eclipse-vertx | vertx-sql-client | https://github.com/eclipse-vertx/vertx-sql-client/issues/671 | https://github.com/eclipse-vertx/vertx-sql-client/pull/706 | https://github.com/eclipse-vertx/vertx-sql-client/pull/706 | 1 | fixes | error using prepared statement cache with DB2 | When I enable the prepared statement cache with DB2 in the HR test suite, I get an error.
I *think* the root cause is this:
```
[2020-06-02 20:24:03] SEVERE io.vertx.db2client.impl.codec.DB2Encoder FATAL: Unable to encode command: io.vertx.sqlclient.impl.command.CloseStatementCommand@501e333e
java.util.ConcurrentModificationException
at java.util.HashMap$ValueSpliterator.forEachRemaining(HashMap.java:1625)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at io.vertx.db2client.impl.codec.DB2PreparedStatement.close(DB2PreparedStatement.java:101)
at io.vertx.db2client.impl.codec.CloseStatementCommandCodec.encode(CloseStatementCommandCodec.java:31)
at io.vertx.db2client.impl.codec.DB2Encoder.write(DB2Encoder.java:79)
at io.vertx.db2client.impl.codec.DB2Encoder.write(DB2Encoder.java:63)
at io.netty.channel.CombinedChannelDuplexHandler.write(CombinedChannelDuplexHandler.java:346)
at io.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:717)
at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:709)
at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:792)
at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:702)
at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:697)
at io.vertx.sqlclient.impl.SocketConnectionBase.checkPending(SocketConnectionBase.java:177)
at io.vertx.sqlclient.impl.SocketConnectionBase.schedule(SocketConnectionBase.java:165)
at io.vertx.db2client.impl.DB2SocketConnection.schedule(DB2SocketConnection.java:70)
at io.vertx.sqlclient.impl.Connection.schedule(Connection.java:34)
at io.vertx.sqlclient.impl.cache.PreparedStatementCache.lambda$new$0(PreparedStatementCache.java:38)
at io.vertx.sqlclient.impl.cache.LruCache.removeEldestEntry(LruCache.java:38)
at java.util.LinkedHashMap.afterNodeInsertion(LinkedHashMap.java:299)
at java.util.HashMap.putVal(HashMap.java:663)
at java.util.HashMap.put(HashMap.java:611)
at io.vertx.sqlclient.impl.cache.InflightCachingStmtEntry.handle(InflightCachingStmtEntry.java:40)
at io.vertx.sqlclient.impl.cache.InflightCachingStmtEntry.handle(InflightCachingStmtEntry.java:21)
at io.vertx.sqlclient.impl.SocketConnectionBase.handleMessage(SocketConnectionBase.java:188)
at io.vertx.sqlclient.impl.SocketConnectionBase.lambda$init$0(SocketConnectionBase.java:78)
at io.vertx.core.net.impl.NetSocketImpl.lambda$new$2(NetSocketImpl.java:101)
at io.vertx.core.streams.impl.InboundBuffer.handleEvent(InboundBuffer.java:237)
at io.vertx.core.streams.impl.InboundBuffer.write(InboundBuffer.java:127)
at io.vertx.core.net.impl.NetSocketImpl.handleMessage(NetSocketImpl.java:357)
at io.vertx.core.impl.ContextImpl.executeTask(ContextImpl.java:366)
at io.vertx.core.impl.EventLoopContext.execute(EventLoopContext.java:43)
at io.vertx.core.impl.ContextImpl.executeFromIO(ContextImpl.java:229)
at io.vertx.core.net.impl.VertxHandler.channelRead(VertxHandler.java:173)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:436)
at io.vertx.db2client.impl.codec.DB2Encoder.lambda$write$0(DB2Encoder.java:75)
at io.vertx.db2client.impl.codec.PrepareStatementCodec.handleReadyForQuery(PrepareStatementCodec.java:89)
at io.vertx.db2client.impl.codec.PrepareStatementCodec.handleColumnDefinitionsDecodingCompleted(PrepareStatementCodec.java:101)
at io.vertx.db2client.impl.codec.PrepareStatementCodec.decodePayload(PrepareStatementCodec.java:80)
at io.vertx.db2client.impl.codec.DB2Decoder.decodePayload(DB2Decoder.java:80)
at io.vertx.db2client.impl.codec.DB2Decoder.decode(DB2Decoder.java:53)
at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:501)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:440)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:251)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:714)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:650)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:576)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
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:745)
``` | 1456727c0d1f2fcd29eafd0ae1601e5853357ebc | b854f6ce91b9bc856b3c9fe50adb1601824341bc | https://github.com/eclipse-vertx/vertx-sql-client/compare/1456727c0d1f2fcd29eafd0ae1601e5853357ebc...b854f6ce91b9bc856b3c9fe50adb1601824341bc | diff --git a/vertx-db2-client/src/main/java/io/vertx/db2client/DB2Exception.java b/vertx-db2-client/src/main/java/io/vertx/db2client/DB2Exception.java
index ec5ac85c..633bd1cd 100644
--- a/vertx-db2-client/src/main/java/io/vertx/db2client/DB2Exception.java
+++ b/vertx-db2-client/src/main/java/io/vertx/db2client/DB2Exception.java
@@ -23,6 +23,12 @@ public class DB2Exception extends RuntimeException {
private final int errorCode;
private final String sqlState;
+
+ public DB2Exception(int errorCode, String sqlState) {
+ super("An error occurred with a DB2 operation. SQLCODE=" + errorCode + " SQLSTATE=" + sqlState);
+ this.errorCode = errorCode;
+ this.sqlState = sqlState;
+ }
public DB2Exception(String message, int errorCode, String sqlState) {
super(message);
diff --git a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/DB2Decoder.java b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/DB2Decoder.java
index 3dcae962..51850d7f 100644
--- a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/DB2Decoder.java
+++ b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/DB2Decoder.java
@@ -77,17 +77,22 @@ class DB2Decoder extends ByteToMessageDecoder {
if (LOG.isDebugEnabled())
LOG.debug("<<< DECODE " + ctx + " (" + payloadLength + " bytes)");
ctx.decodePayload(payload, payloadLength);
- } catch (DB2Exception connex) {
- // A common connection error occurred, so don't bother with a hex dump and
- // generic error message
- ctx.completionHandler.handle(CommandResponse.failure(connex));
} catch (Throwable t) {
- int i = payload.readerIndex();
- payload.readerIndex(startIndex);
- StringBuilder sb = new StringBuilder(
- "FATAL: Error parsing buffer at index " + i + " / 0x" + Integer.toHexString(i) + "\\n");
- ByteBufUtil.appendPrettyHexDump(sb, payload);
- LOG.error(sb.toString(), t);
+ if (LOG.isDebugEnabled()) {
+ if (!(t instanceof DB2Exception) ||
+ (t.getMessage() != null &&
+ t.getMessage().startsWith("An error occurred with a DB2 operation."))) {
+ int i = payload.readerIndex();
+ payload.readerIndex(startIndex);
+ StringBuilder sb = new StringBuilder(
+ "FATAL: Error parsing buffer at index " + i + " / 0x" + Integer.toHexString(i) + "\\n" +
+ "For command " + ctx + "\\n");
+ ByteBufUtil.appendPrettyHexDump(sb, payload);
+ LOG.error(sb.toString(), t);
+ } else {
+ LOG.error("Command failed with: " + t.getMessage() + "\\nCommand=" + ctx, t);
+ }
+ }
ctx.completionHandler.handle(CommandResponse.failure(t));
} finally {
payload.clear();
diff --git a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/DB2PreparedStatement.java b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/DB2PreparedStatement.java
index be55fd86..b9a85f1f 100644
--- a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/DB2PreparedStatement.java
+++ b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/DB2PreparedStatement.java
@@ -15,9 +15,9 @@
*/
package io.vertx.db2client.impl.codec;
-import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
@@ -37,7 +37,7 @@ class DB2PreparedStatement implements PreparedStatement {
final DB2RowDesc rowDesc;
final Section section;
- private final Map<String, QueryInstance> activeQueries = new HashMap<>(4);
+ private final Map<String, QueryInstance> activeQueries = new ConcurrentHashMap<>(4);
public static class QueryInstance {
final String cursorId;
diff --git a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/ExtendedQueryCommandBaseCodec.java b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/ExtendedQueryCommandBaseCodec.java
index 156d7342..20e9faf8 100644
--- a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/ExtendedQueryCommandBaseCodec.java
+++ b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/ExtendedQueryCommandBaseCodec.java
@@ -114,9 +114,9 @@ abstract class ExtendedQueryCommandBaseCodec<R, C extends ExtendedQueryCommand<R
@Override
public String toString() {
if (isQuery)
- return super.toString() + ", fetch=" + cmd.fetch();
+ return super.toString() + ", ps=" + statement + ", fetch=" + cmd.fetch();
else
- return super.toString();
+ return super.toString() + ", ps=" + statement;
}
}
diff --git a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/NetSqlca.java b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/NetSqlca.java
index e21dc948..877f3298 100644
--- a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/NetSqlca.java
+++ b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/NetSqlca.java
@@ -156,6 +156,9 @@ public class NetSqlca {
throw new DB2Exception("The column '" + errMsg + "' provided does not exist", sqlca.sqlCode_, sqlca.sqlState_);
else
throw new DB2Exception("A column provided does not exist", sqlca.sqlCode_, sqlca.sqlState_);
+ case SqlCode.INCORRECT_NUM_HOST_VARIABLES:
+ throw new DB2Exception("The number of variables that were passed into an OPEN or EXECUTE statement do not match " +
+ "the number of parameter markers that were defined in the statement.", sqlca.sqlCode_, sqlca.sqlState_);
case SqlCode.NULL_CONSTRAINT_VIOLATION:
throw new DB2Exception("An attempt was made to INSERT or UPDATE a column that was declared as not nullable with the NULL value: " + errMsg,
sqlca.sqlCode_, sqlca.sqlState_);
@@ -200,7 +203,7 @@ public class NetSqlca {
else
throw new DB2Exception("Duplicate keys were detected on the updated table", sqlca.sqlCode_, sqlca.sqlState_);
default:
- throw new IllegalStateException("ERROR: " + sqlca.toString());
+ throw new DB2Exception(sqlca.sqlCode_, sqlca.sqlState_);
}
}
diff --git a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/SectionManager.java b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/SectionManager.java
index ff05fe2d..369a7b03 100644
--- a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/SectionManager.java
+++ b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/SectionManager.java
@@ -49,15 +49,9 @@ public class SectionManager {
public int sectionsInUse() {
return pkgs.stream().mapToInt(DB2Package::sectionsInUse).sum();
}
-
+
public Section getSection(String sql) {
- if (DRDAQueryRequest.isQuery(sql) ||
- "COMMIT".equalsIgnoreCase(sql) ||
- "ROLLBACK".equalsIgnoreCase(sql)) {
- return getDynamicSection();
- } else {
- return staticSection;
- }
+ return getDynamicSection();
}
private Section getDynamicSection() {
diff --git a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/SqlCode.java b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/SqlCode.java
index 268b205f..f0f99619 100644
--- a/vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/SqlCode.java
+++ b/vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/SqlCode.java
@@ -50,6 +50,8 @@ public class SqlCode {
public static final int OBJECT_NOT_DEFINED = -204;
public static final int COLUMN_DOES_NOT_EXIST = -206;
+
+ public static final int INCORRECT_NUM_HOST_VARIABLES = -313;
public static final int NULL_CONSTRAINT_VIOLATION = -407;
| ['vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/SqlCode.java', 'vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/SectionManager.java', 'vertx-db2-client/src/main/java/io/vertx/db2client/DB2Exception.java', 'vertx-db2-client/src/main/java/io/vertx/db2client/impl/drda/NetSqlca.java', 'vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/DB2Decoder.java', 'vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/DB2PreparedStatement.java', 'vertx-db2-client/src/main/java/io/vertx/db2client/impl/codec/ExtendedQueryCommandBaseCodec.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 2,045,069 | 478,700 | 58,434 | 351 | 2,763 | 594 | 56 | 7 | 6,063 | 164 | 1,276 | 71 | 0 | 1 | 1970-01-01T00:26:33 | 836 | Java | {'Java': 3751793, 'PLpgSQL': 22210, 'TSQL': 13875, 'PLSQL': 6105, 'Shell': 1839, 'Dockerfile': 200} | Apache License 2.0 |
1,281 | eclipse-vertx/vertx-sql-client/743/742 | eclipse-vertx | vertx-sql-client | https://github.com/eclipse-vertx/vertx-sql-client/issues/742 | https://github.com/eclipse-vertx/vertx-sql-client/pull/743 | https://github.com/eclipse-vertx/vertx-sql-client/pull/743 | 1 | fixes | Pool implementation for one-shot queries does not use all available resources | When executing one-shot queries, the pool implementation will often schedule the SQL commands on the few available connections instead of creating more if maximum size has not been reached.
Consider the following test:
```java
@Test
public void testUseAvailableResources(TestContext ctx) {
int poolSize = 10;
Async async = ctx.async();
PgPool pool = PgPool.pool(options, new PoolOptions().setMaxSize(poolSize));
AtomicReference<PgConnection> ctrlConnRef = new AtomicReference<>();
PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(ctrlConn -> {
ctrlConnRef.set(ctrlConn);
for (int i = 0; i < poolSize; i++) {
vertx.setTimer(10 * (i + 1), l -> {
pool.query("select pg_sleep(5)").execute(ar -> {});
});
}
vertx.setTimer(10 * (poolSize + 1), event -> {
ctrlConn.query("select count(*) as cnt from pg_stat_activity where application_name like '%vertx%'").execute(ctx.asyncAssertSuccess(rows -> {
Integer count = rows.iterator().next().getInteger("cnt");
ctx.assertEquals(poolSize + 1, count);
async.complete();
}));
});
}));
try {
async.await();
} finally {
PgConnection ctrlConn = ctrlConnRef.get();
if (ctrlConn != null) {
ctrlConn.close();
}
pool.close();
}
}
```
It fails like this:
```
java.lang.AssertionError: Not equals : 11 != 2
```
This test targets Postgres but the problem is in `PoolBase` implementation so I believe it affects all SQL clients.
| 6bbdcf51be62c8fab42c2f8de49f54724565ab94 | 1bfb2aeeb4c32c37985b4de55c31a4f17b161342 | https://github.com/eclipse-vertx/vertx-sql-client/compare/6bbdcf51be62c8fab42c2f8de49f54724565ab94...1bfb2aeeb4c32c37985b4de55c31a4f17b161342 | diff --git a/vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTest.java b/vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTest.java
index 67bc6faf..e9ad6a19 100644
--- a/vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTest.java
+++ b/vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTest.java
@@ -17,9 +17,9 @@
package io.vertx.pgclient;
-import io.vertx.sqlclient.PoolOptions;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
+import io.vertx.sqlclient.PoolOptions;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicReference;
@@ -130,4 +130,36 @@ public class PgPoolTest extends PgPoolTestBase {
pool.close();
}
}
+
+ @Test
+ public void testUseAvailableResources(TestContext ctx) {
+ int poolSize = 10;
+ Async async = ctx.async(poolSize + 1);
+ PgPool pool = PgPool.pool(options, new PoolOptions().setMaxSize(poolSize));
+ AtomicReference<PgConnection> ctrlConnRef = new AtomicReference<>();
+ PgConnection.connect(vertx, options, ctx.asyncAssertSuccess(ctrlConn -> {
+ ctrlConnRef.set(ctrlConn);
+ for (int i = 0; i < poolSize; i++) {
+ vertx.setTimer(10 * (i + 1), l -> {
+ pool.query("select pg_sleep(5)").execute(ctx.asyncAssertSuccess(res -> async.countDown()));
+ });
+ }
+ vertx.setTimer(10 * (poolSize + 1), event -> {
+ ctrlConn.query("select count(*) as cnt from pg_stat_activity where application_name like '%vertx%'").execute(ctx.asyncAssertSuccess(rows -> {
+ Integer count = rows.iterator().next().getInteger("cnt");
+ ctx.assertEquals(poolSize + 1, count);
+ async.countDown();
+ }));
+ });
+ }));
+ try {
+ async.await();
+ } finally {
+ PgConnection ctrlConn = ctrlConnRef.get();
+ if (ctrlConn != null) {
+ ctrlConn.close();
+ }
+ pool.close();
+ }
+ }
}
diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/PoolBase.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/PoolBase.java
index 35874ccb..2fe4ec9f 100644
--- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/PoolBase.java
+++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/PoolBase.java
@@ -17,19 +17,13 @@
package io.vertx.sqlclient.impl;
-import io.vertx.sqlclient.PoolOptions;
+import io.vertx.core.*;
import io.vertx.sqlclient.Pool;
+import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.SqlConnection;
import io.vertx.sqlclient.Transaction;
import io.vertx.sqlclient.impl.command.CommandBase;
import io.vertx.sqlclient.impl.command.CommandResponse;
-import io.vertx.sqlclient.impl.command.CommandScheduler;
-import io.vertx.core.AsyncResult;
-import io.vertx.core.Context;
-import io.vertx.core.Future;
-import io.vertx.core.Handler;
-import io.vertx.core.Vertx;
-import io.vertx.core.VertxException;
/**
* Todo :
@@ -88,9 +82,11 @@ public abstract class PoolBase<P extends PoolBase<P>> extends SqlClientBase<P> i
pool.acquire(new CommandWaiter() { // SHOULD BE IT !!!!!
@Override
protected void onSuccess(Connection conn) {
- cmd.handler = handler;
+ cmd.handler = commandResponse -> {
+ conn.close(this);
+ handler.handle(commandResponse);
+ };
conn.schedule(cmd);
- conn.close(this);
}
@Override
protected void onFailure(Throwable cause) { | ['vertx-pg-client/src/test/java/io/vertx/pgclient/PgPoolTest.java', 'vertx-sql-client/src/main/java/io/vertx/sqlclient/impl/PoolBase.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,775,476 | 414,900 | 50,306 | 278 | 556 | 103 | 16 | 1 | 1,598 | 174 | 366 | 47 | 0 | 2 | 1970-01-01T00:26:37 | 836 | Java | {'Java': 3751793, 'PLpgSQL': 22210, 'TSQL': 13875, 'PLSQL': 6105, 'Shell': 1839, 'Dockerfile': 200} | Apache License 2.0 |
9,438 | objectionary/eo/1354/1351 | objectionary | eo | https://github.com/objectionary/eo/issues/1351 | https://github.com/objectionary/eo/pull/1354 | https://github.com/objectionary/eo/pull/1354 | 1 | fix | Home object design. Visibility modifiers. | The `org.eolang.maven.Home` object itself and most of his methods are declared as public, but we can restrict visibility to `package-private`. | 0d9109677e9ba6581092aac2b00966426f9d417a | df5d1b884adf41b6c9ba142b125ae417fb783b36 | https://github.com/objectionary/eo/compare/0d9109677e9ba6581092aac2b00966426f9d417a...df5d1b884adf41b6c9ba142b125ae417fb783b36 | diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/Footprint.java b/eo-maven-plugin/src/main/java/org/eolang/maven/Footprint.java
index f32fe344e..3603b4536 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/Footprint.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/Footprint.java
@@ -30,7 +30,7 @@ import org.cactoos.Scalar;
* Program footprint of EO compilation process.
* @since 1.0
*/
-public interface Footprint {
+interface Footprint {
/**
* Get program content of a specific type.
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/FtCached.java b/eo-maven-plugin/src/main/java/org/eolang/maven/FtCached.java
index 9e990f00d..eeada3d80 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/FtCached.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/FtCached.java
@@ -50,7 +50,7 @@ import org.cactoos.text.TextOf;
* </code>
* @since 1.0
*/
-public final class FtCached implements Footprint {
+final class FtCached implements Footprint {
/**
* Path to target root.
*/
@@ -72,7 +72,7 @@ public final class FtCached implements Footprint {
* @param main Main root
* @param cache Cache root
*/
- public FtCached(final String hash, final Path main, final Path cache) {
+ FtCached(final String hash, final Path main, final Path cache) {
this.hash = hash;
this.main = main;
this.cache = cache;
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/FtDefault.java b/eo-maven-plugin/src/main/java/org/eolang/maven/FtDefault.java
index 25bc299f1..c334c00f2 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/FtDefault.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/FtDefault.java
@@ -34,7 +34,7 @@ import org.cactoos.text.TextOf;
* Default implementation of a Footprint.
* @since 1.0
*/
-public final class FtDefault implements Footprint {
+final class FtDefault implements Footprint {
/**
* Path to main location.
@@ -45,7 +45,7 @@ public final class FtDefault implements Footprint {
* Ctor.
* @param main Main location.
*/
- public FtDefault(final Path main) {
+ FtDefault(final Path main) {
this.main = main;
}
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/Home.java b/eo-maven-plugin/src/main/java/org/eolang/maven/Home.java
index 28c835d84..883232497 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/Home.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/Home.java
@@ -48,7 +48,7 @@ import org.cactoos.scalar.LengthOf;
* We also need to add new unit test
*/
@SuppressWarnings("PMD.TooManyMethods")
-public class Home {
+final class Home {
/**
* Current working directory.
*/
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/JavaFiles.java b/eo-maven-plugin/src/main/java/org/eolang/maven/JavaFiles.java
index 64a4c484e..7656c4dfc 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/JavaFiles.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/JavaFiles.java
@@ -38,7 +38,7 @@ import org.cactoos.text.Joined;
* Java files from XMIR.
* @since 1.0
*/
-public final class JavaFiles {
+final class JavaFiles {
/**
* Path to XMIR file.
@@ -56,7 +56,7 @@ public final class JavaFiles {
* @param src XML with java code
* @param target Base destination path
*/
- public JavaFiles(final Path src, final Path target) {
+ JavaFiles(final Path src, final Path target) {
this.source = src;
this.dest = target;
}
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/Objectionary.java b/eo-maven-plugin/src/main/java/org/eolang/maven/Objectionary.java
index 9f94b8839..869a679e4 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/Objectionary.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/Objectionary.java
@@ -31,7 +31,7 @@ import org.cactoos.Input;
*
* @since 1.0
*/
-public interface Objectionary {
+interface Objectionary {
/**
* Resolve object.
* @param name Object name.
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/OyCaching.java b/eo-maven-plugin/src/main/java/org/eolang/maven/OyCaching.java
index 89fe260af..050b54479 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/OyCaching.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/OyCaching.java
@@ -33,7 +33,7 @@ import org.cactoos.io.TeeInput;
*
* @since 1.0
*/
-public final class OyCaching implements Objectionary {
+final class OyCaching implements Objectionary {
/**
* Cache location.
@@ -56,7 +56,7 @@ public final class OyCaching implements Objectionary {
* @param cache Cache directory.
* @param primary Primary objectionary.
*/
- public OyCaching(
+ OyCaching(
final String ver,
final Path cache,
final Objectionary primary
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/OyEmpty.java b/eo-maven-plugin/src/main/java/org/eolang/maven/OyEmpty.java
index f7bbbe6bc..2bf6d361f 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/OyEmpty.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/OyEmpty.java
@@ -31,7 +31,7 @@ import org.cactoos.Input;
*
* @since 0.1
*/
-public final class OyEmpty implements Objectionary {
+final class OyEmpty implements Objectionary {
@Override
public String toString() {
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/OyFallback.java b/eo-maven-plugin/src/main/java/org/eolang/maven/OyFallback.java
index 1742f4c14..1977ad9a6 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/OyFallback.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/OyFallback.java
@@ -34,7 +34,7 @@ import org.cactoos.func.IoCheckedFunc;
*
* @since 1.0
*/
-public final class OyFallback implements Objectionary {
+final class OyFallback implements Objectionary {
/**
* Primary Objectionary.
@@ -51,7 +51,7 @@ public final class OyFallback implements Objectionary {
* @param primary Primary source.
* @param secondary Secondary source.
*/
- public OyFallback(final Objectionary primary, final Objectionary secondary) {
+ OyFallback(final Objectionary primary, final Objectionary secondary) {
this.first = primary;
this.second = secondary;
}
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/OyFallbackSwap.java b/eo-maven-plugin/src/main/java/org/eolang/maven/OyFallbackSwap.java
index 5bfedf86c..1e2325a46 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/OyFallbackSwap.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/OyFallbackSwap.java
@@ -46,7 +46,7 @@ import org.cactoos.scalar.Unchecked;
* </pre>
* @since 1.0
*/
-public final class OyFallbackSwap implements Objectionary {
+final class OyFallbackSwap implements Objectionary {
/**
* Swapped Oy.
*/
@@ -58,7 +58,7 @@ public final class OyFallbackSwap implements Objectionary {
* @param second Initial secondary
* @param swap Whether to swap
*/
- public OyFallbackSwap(
+ OyFallbackSwap(
final Objectionary first,
final Objectionary second,
final boolean swap
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/OyHome.java b/eo-maven-plugin/src/main/java/org/eolang/maven/OyHome.java
index ef6781a0c..fe03de396 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/OyHome.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/OyHome.java
@@ -33,7 +33,7 @@ import org.cactoos.io.InputOf;
*
* @since 1.0
*/
-public final class OyHome implements Objectionary {
+final class OyHome implements Objectionary {
/**
* Local storage.
*/
@@ -49,7 +49,7 @@ public final class OyHome implements Objectionary {
* @param ver Version.
* @param path Root.
*/
- public OyHome(final String ver, final Path path) {
+ OyHome(final String ver, final Path path) {
this.version = ver;
this.home = path;
}
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/OyRemote.java b/eo-maven-plugin/src/main/java/org/eolang/maven/OyRemote.java
index 62a90109e..c2d5ed9df 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/OyRemote.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/OyRemote.java
@@ -35,7 +35,7 @@ import org.cactoos.io.InputOf;
*
* @since 0.1
*/
-public final class OyRemote implements Objectionary {
+final class OyRemote implements Objectionary {
/**
* The address template.
@@ -47,7 +47,7 @@ public final class OyRemote implements Objectionary {
* @param tag Tag
* @throws IOException if fails.
*/
- public OyRemote(final String tag) throws IOException {
+ OyRemote(final String tag) throws IOException {
this.template = String.format(
"https://raw.githubusercontent.com/objectionary/home/%s/objects/%%s.eo",
tag | ['eo-maven-plugin/src/main/java/org/eolang/maven/Objectionary.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/FtCached.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/FtDefault.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/OyCaching.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/OyEmpty.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/OyFallbackSwap.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/OyHome.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/JavaFiles.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/Home.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/Footprint.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/OyFallback.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/OyRemote.java'] | {'.java': 12} | 12 | 12 | 0 | 0 | 12 | 530,900 | 116,300 | 17,074 | 158 | 1,822 | 389 | 40 | 12 | 142 | 20 | 30 | 1 | 0 | 0 | 1970-01-01T00:27:46 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,441 | objectionary/eo/1263/1256 | objectionary | eo | https://github.com/objectionary/eo/issues/1256 | https://github.com/objectionary/eo/pull/1263 | https://github.com/objectionary/eo/pull/1263 | 1 | fix | `keepBinaries` property is not respected in `UnplaceMojo` | Within `UnplaceMojo` we have config parameter `keepBinaries` which is supposed to prevent specified compiled (placed) files from removal.
However current implementation ignore it since it calls consequently two steps:
1. `keepThem` step would remove everything but specified in `keepBinaries`
2. `killThem` step would remove everything with no respect to `keepBinaries`
Need to make `killThem` respect `keepBinaries` property. | 17e240ebb323d2e12e0a79fc9e3656eef9f7895e | 74e17969d5f4bfac96c1d26b0defa680083ee327 | https://github.com/objectionary/eo/compare/17e240ebb323d2e12e0a79fc9e3656eef9f7895e...74e17969d5f4bfac96c1d26b0defa680083ee327 | diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java b/eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java
index fdbbe2150..8648526e6 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java
@@ -150,6 +150,10 @@ public final class UnplaceMojo extends SafeMojo {
related, tojo.get(PlaceMojo.ATTR_ORIGIN)
);
}
+ if (UnplaceMojo.inside(related, this.keepBinaries)
+ && !UnplaceMojo.inside(related, this.removeBinaries)) {
+ continue;
+ }
if (UnplaceMojo.delete(path)) {
unplaced += 1;
Logger.debug(
diff --git a/eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java b/eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java
index 5b68695c3..890b50a70 100644
--- a/eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java
+++ b/eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java
@@ -25,6 +25,7 @@ package org.eolang.maven;
import java.nio.file.Path;
import java.nio.file.Paths;
+import org.cactoos.set.SetOf;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
@@ -37,6 +38,10 @@ import org.junit.jupiter.api.io.TempDir;
* @checkstyle LocalFinalVariableNameCheck (100 lines)
*/
final class UnplaceMojoTest {
+ /**
+ * Value for 'class' ATTR_KIND.
+ */
+ private static final String ATTR_KIND_CLASS = "class";
@Test
void testCleaning(@TempDir final Path temp) throws Exception {
@@ -52,25 +57,25 @@ final class UnplaceMojoTest {
final Path list = temp.resolve("placed.csv");
Catalogs.INSTANCE.make(list)
.add(foo.toString())
- .set(PlaceMojo.ATTR_KIND, "class")
+ .set(PlaceMojo.ATTR_KIND, UnplaceMojoTest.ATTR_KIND_CLASS)
.set(PlaceMojo.ATTR_RELATED, "---")
.set(PlaceMojo.ATTR_ORIGIN, "some.jar")
.set(PlaceMojo.ATTR_HASH, new FileHash(foo));
Catalogs.INSTANCE.make(list)
.add(foo2.toString())
- .set(PlaceMojo.ATTR_KIND, "class")
+ .set(PlaceMojo.ATTR_KIND, UnplaceMojoTest.ATTR_KIND_CLASS)
.set(PlaceMojo.ATTR_RELATED, "---")
.set(PlaceMojo.ATTR_ORIGIN, "some.jar")
.set(PlaceMojo.ATTR_HASH, new FileHash(foo2));
Catalogs.INSTANCE.make(list)
.add(foo3.toString())
- .set(PlaceMojo.ATTR_KIND, "class")
+ .set(PlaceMojo.ATTR_KIND, UnplaceMojoTest.ATTR_KIND_CLASS)
.set(PlaceMojo.ATTR_RELATED, "---")
.set(PlaceMojo.ATTR_ORIGIN, "some.jar")
.set(PlaceMojo.ATTR_HASH, new FileHash(foo3));
Catalogs.INSTANCE.make(list)
.add(foo4.toString())
- .set(PlaceMojo.ATTR_KIND, "class")
+ .set(PlaceMojo.ATTR_KIND, UnplaceMojoTest.ATTR_KIND_CLASS)
.set(PlaceMojo.ATTR_RELATED, "---")
.set(PlaceMojo.ATTR_ORIGIN, "some.jar")
.set(PlaceMojo.ATTR_HASH, new FileHash(foo4));
@@ -99,4 +104,59 @@ final class UnplaceMojoTest {
Matchers.is(false)
);
}
+
+ @Test
+ void testKeepBinaries(@TempDir final Path temp) throws Exception {
+ final Path foo = temp.resolve("a/b/c/foo5.class");
+ new Home().save("testKeepBinaries", foo);
+ final Path pparent = foo.getParent().getParent();
+ final Path list = temp.resolve("placed.csv");
+ Catalogs.INSTANCE.make(list)
+ .add(foo.toString())
+ .set(PlaceMojo.ATTR_KIND, UnplaceMojoTest.ATTR_KIND_CLASS)
+ .set(PlaceMojo.ATTR_RELATED, "a/b/c/foo5.class")
+ .set(PlaceMojo.ATTR_ORIGIN, "some-keep.jar")
+ .set(PlaceMojo.ATTR_HASH, new FileHash(foo));
+ new Moja<>(UnplaceMojo.class)
+ .with("placed", list.toFile())
+ .with("placedFormat", "csv")
+ .with("keepBinaries", new SetOf<>("**foo5.class"))
+ .execute();
+ MatcherAssert.assertThat(
+ new Home().exists(foo),
+ Matchers.is(true)
+ );
+ MatcherAssert.assertThat(
+ new Home().exists(Paths.get(String.valueOf(pparent))),
+ Matchers.is(true)
+ );
+ }
+
+ @Test
+ void testKeepRemoveBinaries(@TempDir final Path temp) throws Exception {
+ final Path foo = temp.resolve("a/b/c/foo6.class");
+ new Home().save("testKeepRemoveBinaries", foo);
+ final Path pparent = foo.getParent().getParent();
+ final Path list = temp.resolve("placed.csv");
+ Catalogs.INSTANCE.make(list)
+ .add(foo.toString())
+ .set(PlaceMojo.ATTR_KIND, UnplaceMojoTest.ATTR_KIND_CLASS)
+ .set(PlaceMojo.ATTR_RELATED, "a/b/c/foo6.class")
+ .set(PlaceMojo.ATTR_ORIGIN, "some-keep-remove.jar")
+ .set(PlaceMojo.ATTR_HASH, new FileHash(foo));
+ new Moja<>(UnplaceMojo.class)
+ .with("placed", list.toFile())
+ .with("placedFormat", "csv")
+ .with("keepBinaries", new SetOf<>("**foo6.class"))
+ .with("removeBinaries", new SetOf<>("**foo6.class"))
+ .execute();
+ MatcherAssert.assertThat(
+ new Home().exists(foo),
+ Matchers.is(false)
+ );
+ MatcherAssert.assertThat(
+ new Home().exists(Paths.get(String.valueOf(pparent))),
+ Matchers.is(false)
+ );
+ }
} | ['eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 520,737 | 114,505 | 16,826 | 156 | 178 | 40 | 4 | 1 | 433 | 57 | 96 | 6 | 0 | 0 | 1970-01-01T00:27:43 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,439 | objectionary/eo/1339/1292 | objectionary | eo | https://github.com/objectionary/eo/issues/1292 | https://github.com/objectionary/eo/pull/1339 | https://github.com/objectionary/eo/pull/1339 | 1 | solved | SpyTrain.java:48-51: we need to implement StLambdaQuiet... | The puzzle `1248-52399106` from #1248 has to be resolved:
https://github.com/objectionary/eo/blob/4a80878e27a1e6d41b71b4d2ab4949b741a1c51f/eo-maven-plugin/src/main/java/org/eolang/maven/SpyTrain.java#L48-L51
The puzzle was created by rultor on 30-Sep-22.
Estimate: 30 minutes, role: DEV.
If you have any technical questions, don't ask me, submit new tickets instead. The task will be \\"done\\" when the problem is fixed and the text of the puzzle is _removed_ from the source code. Here is more about [PDD](http://www.yegor256.com/2009/03/04/pdd.html) and [about me](http://www.yegor256.com/2017/04/05/pdd-in-action.html).
| 2fd90f407b6a33a8679a8575314d9659932d968e | 67e5087459eda1d882a7e23f664bc7164e97a5bc | https://github.com/objectionary/eo/compare/2fd90f407b6a33a8679a8575314d9659932d968e...67e5087459eda1d882a7e23f664bc7164e97a5bc | diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/SpyTrain.java b/eo-maven-plugin/src/main/java/org/eolang/maven/SpyTrain.java
index a394a3d1a..ff6ac08d9 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/SpyTrain.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/SpyTrain.java
@@ -30,7 +30,6 @@ import com.yegor256.xsline.StLambda;
import com.yegor256.xsline.TrEnvelope;
import com.yegor256.xsline.TrLambda;
import com.yegor256.xsline.Train;
-import java.io.IOException;
import java.nio.file.Path;
/**
@@ -45,10 +44,6 @@ final class SpyTrain extends TrEnvelope {
*
* @param train Original one
* @param dir The dir to save
- * @todo #1248:30min we need to implement StLambdaQuiet in
- * yegor256/xsline. It will be similar to StLambda
- * but it will also catch checked exceptions. Then we should
- * change code below
*/
SpyTrain(final Train<Shift> train, final Path dir) {
super(
@@ -60,16 +55,12 @@ final class SpyTrain extends TrEnvelope {
shift::uid,
(pos, xml) -> {
final String log = shift.uid().replaceAll("[^a-z0-9]", "-");
- try {
- new Home().save(
- xml.toString(),
- dir.resolve(
- String.format("%02d-%s.xml", pos, log)
- )
- );
- } catch (final IOException exc) {
- throw new IllegalStateException(exc);
- }
+ new Home().save(
+ xml.toString(),
+ dir.resolve(
+ String.format("%02d-%s.xml", pos, log)
+ )
+ );
if (Logger.isDebugEnabled(SpyTrain.class)) {
Logger.debug(
SpyTrain.class, "Step #%d by %s:\\n%s", | ['eo-maven-plugin/src/main/java/org/eolang/maven/SpyTrain.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 525,058 | 115,277 | 16,919 | 157 | 1,035 | 149 | 21 | 1 | 631 | 66 | 210 | 10 | 3 | 0 | 1970-01-01T00:27:45 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,426 | objectionary/eo/2224/2208 | objectionary | eo | https://github.com/objectionary/eo/issues/2208 | https://github.com/objectionary/eo/pull/2224 | https://github.com/objectionary/eo/pull/2224 | 1 | closes | BinarizeMojo.java:49-51: Make cargo compilation in... | The puzzle `2195-24c0d5f1` from #2195 has to be resolved:
https://github.com/objectionary/eo/blob/0918ffe1f84cac89def9be8e89f8dc635184f266/eo-maven-plugin/src/main/java/org/eolang/maven/BinarizeMojo.java#L49-L51
The puzzle was created by rultor on 04-Jul-23.
Estimate: 90 minutes, role: DEV.
If you have any technical questions, don't ask me, submit new tickets instead. The task will be \\"done\\" when the problem is fixed and the text of the puzzle is _removed_ from the source code. Here is more about [PDD](http://www.yegor256.com/2009/03/04/pdd.html) and [about me](http://www.yegor256.com/2017/04/05/pdd-in-action.html).
| e9ef31a90b26e033d921daa4510af06a4264ca8e | 9eed2b4286ffc4228c093ff5e403acce5e6f61cf | https://github.com/objectionary/eo/compare/e9ef31a90b26e033d921daa4510af06a4264ca8e...9eed2b4286ffc4228c093ff5e403acce5e6f61cf | diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/BinarizeMojo.java b/eo-maven-plugin/src/main/java/org/eolang/maven/BinarizeMojo.java
index 69945b806..99d3d5214 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/BinarizeMojo.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/BinarizeMojo.java
@@ -34,6 +34,10 @@ import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
+import org.cactoos.experimental.Threads;
+import org.cactoos.iterable.Filtered;
+import org.cactoos.iterable.Mapped;
+import org.cactoos.number.SumOf;
import org.eolang.maven.rust.BuildFailureException;
/**
@@ -45,9 +49,6 @@ import org.eolang.maven.rust.BuildFailureException;
* Now it copies cargo project to cache directory in the end of every
* compilation. It is better to copy the project only if it was changed
* with the last compilation.
- * @todo #2195:90min Make cargo compilation in parallel. Now cargo
- * projects are being built consistently which is too long.
- * It is much better to build them in parallel to reduce time.
*/
@Mojo(
name = "binarize",
@@ -77,11 +78,35 @@ public final class BinarizeMojo extends SafeMojo {
@Override
public void exec() throws IOException {
new Moja<>(BinarizeParseMojo.class).copy(this).execute();
- for (final File project: targetDir.toPath().resolve("Lib").toFile().listFiles()) {
- if (project.isDirectory() && project.toPath().resolve("Cargo.toml").toFile().exists()) {
- this.build(project);
- }
- }
+ final int total = new SumOf(
+ new Threads<>(
+ Runtime.getRuntime().availableProcessors(),
+ new Mapped<>(
+ project -> () -> {
+ this.build(project);
+ return 1;
+ },
+ new Filtered<>(
+ project -> BinarizeMojo.valid(project),
+ targetDir.toPath().resolve("Lib").toFile().listFiles()
+ )
+ )
+ )
+ ).intValue();
+ Logger.info(
+ this,
+ String.format("Built in total %d cargo projects", total)
+ );
+ }
+
+ /**
+ * Is the project valid?
+ * @param project File to check.
+ * @return True if valid. Otherwise false.
+ */
+ private static boolean valid(final File project) {
+ return project.isDirectory()
+ && project.toPath().resolve("Cargo.toml").toFile().exists();
}
/**
@@ -91,7 +116,7 @@ public final class BinarizeMojo extends SafeMojo {
*/
private void build(final File project) throws IOException {
final File target = project.toPath().resolve("target").toFile();
- final File cached = cache
+ final File cached = this.cache
.resolve("Lib")
.resolve(project.getName())
.resolve("target").toFile();
@@ -117,16 +142,6 @@ public final class BinarizeMojo extends SafeMojo {
)
) {
proc.stdout();
- proc.waitFor();
- } catch (final InterruptedException exception) {
- Thread.currentThread().interrupt();
- throw new BuildFailureException(
- String.format(
- "Interrupted while building %s",
- project
- ),
- exception
- );
} catch (final IllegalArgumentException exc) {
throw new BuildFailureException(
String.format( | ['eo-maven-plugin/src/main/java/org/eolang/maven/BinarizeMojo.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 745,537 | 162,407 | 23,784 | 210 | 2,038 | 384 | 53 | 1 | 635 | 66 | 209 | 10 | 3 | 0 | 1970-01-01T00:28:08 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,427 | objectionary/eo/2061/1123 | objectionary | eo | https://github.com/objectionary/eo/issues/1123 | https://github.com/objectionary/eo/pull/2061 | https://github.com/objectionary/eo/pull/2061 | 1 | closes | Can't dataize integer or float | I think it's necessary to notify users of EO that we can't dataize integer or float like this:
```
[] > app
5 > @
```
Here is output after `eoc dataize app`:
```
Exception in thread "main" java.lang.ClassCastException: Cannot cast java.lang.Long to java.lang.Boolean
at java.base/java.lang.Class.cast(Class.java:3605)
at org.eolang.Dataized.take(Dataized.java:127)
at org.eolang.Main.run(Main.java:190)
at org.eolang.Main.main(Main.java:98)
```
Or maybe I do smth wrong? | b6c2e15f2b8f4416836337e9cff5513272ebf810 | 5befbfda41ab0fe2988541b58cad3efa42cb945c | https://github.com/objectionary/eo/compare/b6c2e15f2b8f4416836337e9cff5513272ebf810...5befbfda41ab0fe2988541b58cad3efa42cb945c | diff --git a/eo-runtime/src/main/java/org/eolang/Main.java b/eo-runtime/src/main/java/org/eolang/Main.java
index b6403ffff..91fc2ec17 100644
--- a/eo-runtime/src/main/java/org/eolang/Main.java
+++ b/eo-runtime/src/main/java/org/eolang/Main.java
@@ -193,11 +193,12 @@ public final class Main {
phi.attr("Δ").put(new Data.Value<>(arg));
app.attr(0).put(phi);
}
- if (!new Dataized(app).take(Boolean.class)) {
- throw new IllegalStateException(
- "Runtime dataization failure"
- );
- }
+ Main.LOGGER.info(
+ String.format(
+ "%n---%n%s",
+ new Dataized(app).take().toString()
+ )
+ );
}
/**
diff --git a/eo-runtime/src/test/java/org/eolang/MainTest.java b/eo-runtime/src/test/java/org/eolang/MainTest.java
index dc74e0698..f555039cd 100644
--- a/eo-runtime/src/test/java/org/eolang/MainTest.java
+++ b/eo-runtime/src/test/java/org/eolang/MainTest.java
@@ -66,8 +66,8 @@ final class MainTest {
@Test
void deliversCleanOutput() throws Exception {
MatcherAssert.assertThat(
- MainTest.exec("org.eolang.io.stdout", "Hi!"),
- Matchers.equalTo(String.format("Hi!%s", System.lineSeparator()))
+ MainTest.exec("org.eolang.io.stdout", "Hello!"),
+ Matchers.equalTo(String.format("Hello!%n---%ntrue%n"))
);
}
| ['eo-runtime/src/main/java/org/eolang/Main.java', 'eo-runtime/src/test/java/org/eolang/MainTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 715,620 | 156,358 | 22,861 | 205 | 339 | 61 | 11 | 1 | 489 | 59 | 129 | 14 | 0 | 2 | 1970-01-01T00:28:03 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,428 | objectionary/eo/1973/1961 | objectionary | eo | https://github.com/objectionary/eo/issues/1961 | https://github.com/objectionary/eo/pull/1973 | https://github.com/objectionary/eo/pull/1973 | 1 | closes | DcsDepgraph.java:195-197: Close `JsonReader` object in... | The puzzle `1897-5e29a33b` from #1897 has to be resolved:
https://github.com/objectionary/eo/blob/8e82e617d5de10dc7816327d416acff19269cda0/eo-maven-plugin/src/main/java/org/eolang/maven/dependencies/DcsDepgraph.java#L195-L197
The puzzle was created by Max Petrov on 31-Mar-23.
Estimate: 30 minutes, role: DEV.
If you have any technical questions, don't ask me, submit new tickets instead. The task will be \\"done\\" when the problem is fixed and the text of the puzzle is _removed_ from the source code. Here is more about [PDD](http://www.yegor256.com/2009/03/04/pdd.html) and [about me](http://www.yegor256.com/2017/04/05/pdd-in-action.html).
| 02a511e6d5d9d872035770da4ead57318ec2813a | 1caef19e9f38f7a1b02fa10a4418a5e72915ed0a | https://github.com/objectionary/eo/compare/02a511e6d5d9d872035770da4ead57318ec2813a...1caef19e9f38f7a1b02fa10a4418a5e72915ed0a | diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/dependencies/DcsDepgraph.java b/eo-maven-plugin/src/main/java/org/eolang/maven/dependencies/DcsDepgraph.java
index fa6fbf1c9..cb7ecaf1d 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/dependencies/DcsDepgraph.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/dependencies/DcsDepgraph.java
@@ -202,9 +202,12 @@ public final class DcsDepgraph implements Iterable<Dependency> {
final Collection<Dependency> all = new ArrayList<>(0);
if (Files.exists(this.file)) {
Logger.debug(this, String.format("Dependencies file: %s", this.file));
- final JsonReader reader = Json.createReader(Files.newBufferedReader(this.file));
- final JsonArray artifacts = reader.readObject()
- .getJsonArray("artifacts");
+ final JsonArray artifacts;
+ try (JsonReader reader =
+ Json.createReader(Files.newBufferedReader(this.file))
+ ) {
+ artifacts = reader.readObject().getJsonArray("artifacts");
+ }
for (final JsonValue artifact : artifacts) {
final JsonObject obj = artifact.asJsonObject();
final String group = obj.getString("groupId"); | ['eo-maven-plugin/src/main/java/org/eolang/maven/dependencies/DcsDepgraph.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 696,003 | 152,268 | 22,160 | 201 | 528 | 80 | 9 | 1 | 653 | 67 | 210 | 10 | 3 | 0 | 1970-01-01T00:28:00 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,429 | objectionary/eo/1968/1959 | objectionary | eo | https://github.com/objectionary/eo/issues/1959 | https://github.com/objectionary/eo/pull/1968 | https://github.com/objectionary/eo/pull/1968 | 1 | closes | RedundantParentheses.java:105-113: Refactor regexp in... | The puzzle `1897-b918ace1` from #1897 has to be resolved:
https://github.com/objectionary/eo/blob/8e82e617d5de10dc7816327d416acff19269cda0/eo-parser/src/main/java/org/eolang/parser/RedundantParentheses.java#L105-L113
The puzzle was created by Max Petrov on 31-Mar-23.
Estimate: 30 minutes, role: DEV.
If you have any technical questions, don't ask me, submit new tickets instead. The task will be \\"done\\" when the problem is fixed and the text of the puzzle is _removed_ from the source code. Here is more about [PDD](http://www.yegor256.com/2009/03/04/pdd.html) and [about me](http://www.yegor256.com/2017/04/05/pdd-in-action.html).
| c4289d759510b1551a0ac69c2adcbc44853ccf65 | e940f2cb8b3a2c5d16f7fc27abdb9b77c0901e1e | https://github.com/objectionary/eo/compare/c4289d759510b1551a0ac69c2adcbc44853ccf65...e940f2cb8b3a2c5d16f7fc27abdb9b77c0901e1e | diff --git a/eo-parser/src/main/java/org/eolang/parser/RedundantParentheses.java b/eo-parser/src/main/java/org/eolang/parser/RedundantParentheses.java
index a4d9bb39b..4c83b7029 100644
--- a/eo-parser/src/main/java/org/eolang/parser/RedundantParentheses.java
+++ b/eo-parser/src/main/java/org/eolang/parser/RedundantParentheses.java
@@ -28,6 +28,7 @@ import java.util.ArrayDeque;
import java.util.Deque;
import java.util.function.Consumer;
import java.util.function.Predicate;
+import java.util.regex.Pattern;
/**
* The class that checks redundant parentheses for object expression.
@@ -36,6 +37,11 @@ import java.util.function.Predicate;
*/
final class RedundantParentheses implements Predicate<String> {
+ /**
+ * Pattern for string literals.
+ */
+ private static final Pattern PATTERN = Pattern.compile("(?ms)\\"\\"\\".*?\\"\\"\\"|\\".*?\\"");
+
/**
* The callback that will be called in case if redundant parentheses is found.
*/
@@ -113,9 +119,7 @@ final class RedundantParentheses implements Predicate<String> {
* Refactor this repetition that can lead to a stack overflow for large inputs. (line 113)
*/
private static char[] expressionChars(final String expression) {
- return expression.replaceAll(
- "\\"(.|\\\\s)*?\\"|\\"\\"\\"(.|\\\\s)*?\\"\\"\\"",
- "literal"
- ).toCharArray();
+ return RedundantParentheses
+ .PATTERN.matcher(expression).replaceAll("literal").toCharArray();
}
} | ['eo-parser/src/main/java/org/eolang/parser/RedundantParentheses.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 695,909 | 152,256 | 22,152 | 201 | 438 | 106 | 12 | 1 | 644 | 67 | 204 | 10 | 3 | 0 | 1970-01-01T00:28:00 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,430 | objectionary/eo/1930/1897 | objectionary | eo | https://github.com/objectionary/eo/issues/1897 | https://github.com/objectionary/eo/pull/1930 | https://github.com/objectionary/eo/pull/1930 | 1 | fixes | sonarcube is complaining about our quality of code | We have pretty bad results in SonarCube: https://sonarcloud.io/summary/new_code?id=com.objectionary%3Aeo Let's try to fix at least the major problems. | 3919daf96f6d10a4254d7cd178c323580f6c994b | 8e82e617d5de10dc7816327d416acff19269cda0 | https://github.com/objectionary/eo/compare/3919daf96f6d10a4254d7cd178c323580f6c994b...8e82e617d5de10dc7816327d416acff19269cda0 | diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/Coordinates.java b/eo-maven-plugin/src/main/java/org/eolang/maven/Coordinates.java
index 92649073c..90f76c3f1 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/Coordinates.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/Coordinates.java
@@ -23,6 +23,7 @@
*/
package org.eolang.maven;
+import javax.annotation.Nonnull;
import org.apache.maven.model.Dependency;
/**
@@ -69,12 +70,12 @@ public final class Coordinates implements Comparable<Coordinates> {
}
@Override
- public int compareTo(final Coordinates other) {
+ public int compareTo(@Nonnull final Coordinates other) {
return this.toString().compareTo(other.toString());
}
@Override
- public boolean equals(final Object other) {
+ public boolean equals(@Nonnull final Object other) {
return this.toString().equals(other.toString());
}
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/DepDirs.java b/eo-maven-plugin/src/main/java/org/eolang/maven/DepDirs.java
index a069c0b2b..a46f285d9 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/DepDirs.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/DepDirs.java
@@ -31,6 +31,7 @@ import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import java.util.stream.Stream;
import org.cactoos.list.ListEnvelope;
/**
@@ -62,15 +63,17 @@ final class DepDirs extends ListEnvelope<String> {
final List<String> names = new LinkedList<>();
if (Files.exists(dir)) {
final String home = dir.toAbsolutePath().toString();
- names.addAll(
- Files.find(dir, 4, (t, u) -> true)
- .filter(file -> file.toFile().isDirectory())
- .map(file -> file.toAbsolutePath().toString())
- .filter(name -> !name.equals(home))
- .map(name -> name.substring(home.length() + 1))
- .filter(name -> name.split(Pattern.quote(File.separator)).length == 4)
- .collect(Collectors.toList())
- );
+ try (Stream<Path> paths = Files.find(dir, 4, (t, u) -> true)) {
+ names.addAll(
+ paths
+ .filter(file -> file.toFile().isDirectory())
+ .map(file -> file.toAbsolutePath().toString())
+ .filter(name -> !name.equals(home))
+ .map(name -> name.substring(home.length() + 1))
+ .filter(name -> name.split(Pattern.quote(File.separator)).length == 4)
+ .collect(Collectors.toList())
+ );
+ }
}
return names;
}
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java b/eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java
index aaaadbd79..873d97fc9 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java
@@ -25,6 +25,7 @@ package org.eolang.maven;
import com.jcabi.log.Logger;
import java.io.IOException;
+import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -264,7 +265,7 @@ public final class UnplaceMojo extends SafeMojo {
Files.delete(file);
deleted = true;
}
- while (!Files.newDirectoryStream(dir).iterator().hasNext()) {
+ while (UnplaceMojo.isEmpty(dir)) {
final Path curdir = dir;
dir = curdir.getParent();
Files.delete(curdir);
@@ -276,4 +277,20 @@ public final class UnplaceMojo extends SafeMojo {
}
return deleted;
}
+
+ /**
+ * Check if folder is empty.
+ * @param path Folder to be checked
+ * @return True if folder is empty and False otherwise
+ * @throws IOException In case of I/O issues
+ */
+ private static boolean isEmpty(final Path path) throws IOException {
+ boolean empty = false;
+ if (Files.isDirectory(path)) {
+ try (DirectoryStream<Path> directory = Files.newDirectoryStream(path)) {
+ empty = !directory.iterator().hasNext();
+ }
+ }
+ return empty;
+ }
}
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/dependencies/DcsDepgraph.java b/eo-maven-plugin/src/main/java/org/eolang/maven/dependencies/DcsDepgraph.java
index d3a233e1a..fa6fbf1c9 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/dependencies/DcsDepgraph.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/dependencies/DcsDepgraph.java
@@ -51,6 +51,7 @@ import org.twdata.maven.mojoexecutor.MojoExecutor;
*
* @see <a href="https://github.com/ferstl/depgraph-maven-plugin">here</a>
* @since 0.28.11
+ * @checkstyle NoJavadocForOverriddenMethodsCheck (200 lines)
*/
public final class DcsDepgraph implements Iterable<Dependency> {
@@ -187,6 +188,14 @@ public final class DcsDepgraph implements Iterable<Dependency> {
this.file = path;
}
+ /**
+ * Returns an iterator over elements of type {@code T}.
+ *
+ * @return Iterator.
+ * @todo #1897:30m Close `JsonReader` object in `DcsJson`.
+ * SonarCloud mandates readers to be closed.
+ * Use try-with-resources or close this "JsonReader" in a "finally" clause. (line 203)
+ */
@Override
public Iterator<Dependency> iterator() {
try {
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/footprint/FtDefault.java b/eo-maven-plugin/src/main/java/org/eolang/maven/footprint/FtDefault.java
index 99cd041b2..dbfa20cbf 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/footprint/FtDefault.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/footprint/FtDefault.java
@@ -41,6 +41,7 @@ import org.eolang.maven.util.Home;
* Program footprint of EO compilation process.
* <p>The footprint consists of file in {@link #main} folder</p>
* @since 1.0
+ * @checkstyle NoJavadocForOverriddenMethodsCheck (100 lines)
*/
public final class FtDefault implements Footprint {
@@ -75,6 +76,18 @@ public final class FtDefault implements Footprint {
);
}
+ /**
+ * Get list of saved regular files with ext.
+ *
+ * @param ext File extension
+ * @return List of files
+ * @throws IOException In case of IO issues
+ * @todo #1897:30m Close `Stream` object in `FtDefault`.
+ * Connections, streams, files, and other classes that implement the
+ * Closeable interface or its super-interface,
+ * AutoCloseable, needs to be closed after use.
+ * Use try-with-resources or close this "Stream" in a "finally" clause.. (line 90)
+ */
@Override
public List<Path> list(final String ext) throws IOException {
final List<Path> res;
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/util/Walk.java b/eo-maven-plugin/src/main/java/org/eolang/maven/util/Walk.java
index d49782847..2777c66df 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/util/Walk.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/util/Walk.java
@@ -116,6 +116,12 @@ public final class Walk extends ListEnvelope<Path> {
* List them all.
* @param dir The dir
* @return List
+ * @throws IOException If fails
+ * @todo #1897:30m Close `Stream` object in `Walk`.
+ * Connections, streams, files, and other classes that implement the
+ * Closeable interface or its super-interface,
+ * AutoCloseable, needs to be closed after use.
+ * Use try-with-resources or close this "Stream" in a "finally" clause.. (line 131)
*/
private static List<Path> list(final Path dir) {
try {
diff --git a/eo-parser/src/main/java/org/eolang/parser/RedundantParentheses.java b/eo-parser/src/main/java/org/eolang/parser/RedundantParentheses.java
index fb508e602..a4d9bb39b 100644
--- a/eo-parser/src/main/java/org/eolang/parser/RedundantParentheses.java
+++ b/eo-parser/src/main/java/org/eolang/parser/RedundantParentheses.java
@@ -100,8 +100,17 @@ final class RedundantParentheses implements Predicate<String> {
/**
* Clears raw expression from text literals and returns it as an array of chars.
- * @param expression Raw experession
+ * @param expression Raw expression
* @return Expression as an array of chars.
+ * @todo #1897:30m Refactor regexp in `RedundantParenthesis`.
+ * The Java regex engine uses recursive method calls to implement backtracking.
+ * Therefore when a repetition inside a regular expression contains multiple paths
+ * (i.e. the body of the repetition contains an alternation (|), an optional
+ * element or another repetition), trying to match the regular expression can cause a
+ * stack overflow on large inputs. This does not happen when using a possessive quantifier
+ * (such as *+ instead of *) or when using a character class inside a repetition
+ * (e.g. [ab]* instead of (a|b)*).
+ * Refactor this repetition that can lead to a stack overflow for large inputs. (line 113)
*/
private static char[] expressionChars(final String expression) {
return expression.replaceAll(
diff --git a/eo-runtime/src/main/java/org/eolang/BytesOf.java b/eo-runtime/src/main/java/org/eolang/BytesOf.java
index 6b59551b3..69aeef7aa 100644
--- a/eo-runtime/src/main/java/org/eolang/BytesOf.java
+++ b/eo-runtime/src/main/java/org/eolang/BytesOf.java
@@ -142,7 +142,7 @@ public final class BytesOf implements Bytes {
} else {
byte dst = (byte) (bytes[source] << mod);
if (source + 1 < bytes.length) {
- dst |= bytes[source + 1] >>> (Byte.SIZE - mod) & carry;
+ dst |= bytes[source + 1] >>> (Byte.SIZE - mod) & carry & 0xFF;
}
bytes[index] = dst;
}
@@ -156,7 +156,7 @@ public final class BytesOf implements Bytes {
} else {
byte dst = (byte) ((0xff & bytes[source]) >>> mod);
if (source - 1 >= 0) {
- dst |= bytes[source - 1] << (Byte.SIZE - mod) & carry;
+ dst |= bytes[source - 1] << (Byte.SIZE - mod) & carry & 0xFF;
}
bytes[index] = dst;
}
@@ -176,7 +176,7 @@ public final class BytesOf implements Bytes {
final int zeros = BytesOf.numberOfLeadingZeros(
bytes[index]
);
- bytes[index] = (byte) (bytes[index] ^ (-1 << (Byte.SIZE - zeros)));
+ bytes[index] = (byte) (bytes[index] & 0xFF ^ (-1 << (Byte.SIZE - zeros)));
if (zeros != Byte.SIZE) {
break;
}
diff --git a/eo-runtime/src/main/java/org/eolang/Dataized.java b/eo-runtime/src/main/java/org/eolang/Dataized.java
index 87d8f89ce..f4e46a559 100644
--- a/eo-runtime/src/main/java/org/eolang/Dataized.java
+++ b/eo-runtime/src/main/java/org/eolang/Dataized.java
@@ -126,4 +126,15 @@ public final class Dataized {
public <T> T take(final Class<T> type) {
return type.cast(this.take());
}
+
+ /**
+ * Clean up resources.
+ * This includes call of {@link ThreadLocal#remove()} method to prevent
+ * memory leaks.
+ */
+ public static void cleanUp() {
+ Dataized.LEVEL.remove();
+ Dataized.MAX_LEVEL.remove();
+ }
+
}
diff --git a/eo-runtime/src/main/java/org/eolang/ExprReduce.java b/eo-runtime/src/main/java/org/eolang/ExprReduce.java
index a31eed108..be7fd20a3 100644
--- a/eo-runtime/src/main/java/org/eolang/ExprReduce.java
+++ b/eo-runtime/src/main/java/org/eolang/ExprReduce.java
@@ -84,6 +84,14 @@ public final class ExprReduce<T> implements Expr {
@Override
public Phi get(final Phi rho) {
final Optional<T> acc = this.arguments.get(rho, this.param).stream().reduce(this.reduction);
+ if (!acc.isPresent()) {
+ throw new IllegalStateException(
+ String.format(
+ "Unable to reduce expression for %s",
+ rho
+ )
+ );
+ }
return new Data.ToPhi(acc.get());
}
diff --git a/eo-runtime/src/main/java/org/eolang/Main.java b/eo-runtime/src/main/java/org/eolang/Main.java
index 609d771ff..b6403ffff 100644
--- a/eo-runtime/src/main/java/org/eolang/Main.java
+++ b/eo-runtime/src/main/java/org/eolang/Main.java
@@ -214,7 +214,7 @@ public final class Main {
)
)
) {
- return input.lines().findFirst().get();
+ return input.lines().findFirst().orElse("N/A");
}
}
diff --git a/eo-runtime/src/main/java/org/eolang/PhDefault.java b/eo-runtime/src/main/java/org/eolang/PhDefault.java
index 28f2df6ad..461b9e27f 100644
--- a/eo-runtime/src/main/java/org/eolang/PhDefault.java
+++ b/eo-runtime/src/main/java/org/eolang/PhDefault.java
@@ -284,6 +284,16 @@ public abstract class PhDefault implements Phi, Cloneable {
return "?";
}
+ /**
+ * Clean up resources.
+ * This includes call of {@link ThreadLocal#remove()} method to prevent
+ * memory leaks.
+ */
+ public static void cleanUp() {
+ PhDefault.TERMS.remove();
+ PhDefault.NESTING.remove();
+ }
+
/**
* Add new attribute.
* | ['eo-runtime/src/main/java/org/eolang/Main.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/DepDirs.java', 'eo-runtime/src/main/java/org/eolang/ExprReduce.java', 'eo-parser/src/main/java/org/eolang/parser/RedundantParentheses.java', 'eo-runtime/src/main/java/org/eolang/PhDefault.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/footprint/FtDefault.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/Coordinates.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/dependencies/DcsDepgraph.java', 'eo-runtime/src/main/java/org/eolang/Dataized.java', 'eo-runtime/src/main/java/org/eolang/BytesOf.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/util/Walk.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java'] | {'.java': 12} | 12 | 12 | 0 | 0 | 12 | 681,411 | 149,046 | 21,726 | 197 | 5,660 | 1,235 | 121 | 12 | 150 | 17 | 40 | 1 | 1 | 0 | 1970-01-01T00:27:59 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,432 | objectionary/eo/1913/1376 | objectionary | eo | https://github.com/objectionary/eo/issues/1376 | https://github.com/objectionary/eo/pull/1913 | https://github.com/objectionary/eo/pull/1913 | 1 | closes | Home.java:47-48: Prohibit absolute paths in methods... | The puzzle `1352-39528ceb` from #1352 has to be resolved:
https://github.com/objectionary/eo/blob/09faccc4fba201855269a0b61108053e460c21f3/eo-maven-plugin/src/main/java/org/eolang/maven/Home.java#L47-L48
The puzzle was created by rultor on 31-Oct-22.
Estimate: 30 minutes, role: DEV.
If you have any technical questions, don't ask me, submit new tickets instead. The task will be \\"done\\" when the problem is fixed and the text of the puzzle is _removed_ from the source code. Here is more about [PDD](http://www.yegor256.com/2009/03/04/pdd.html) and [about me](http://www.yegor256.com/2017/04/05/pdd-in-action.html).
| 49ec17f8d60d59cb41fdf9f9c25521b7f52549e3 | 7757f3cd7d1ce57f90aedce05678d171e03e781f | https://github.com/objectionary/eo/compare/49ec17f8d60d59cb41fdf9f9c25521b7f52549e3...7757f3cd7d1ce57f90aedce05678d171e03e781f | diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/OptimizeMojo.java b/eo-maven-plugin/src/main/java/org/eolang/maven/OptimizeMojo.java
index 42739f725..ad19809eb 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/OptimizeMojo.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/OptimizeMojo.java
@@ -264,7 +264,7 @@ public final class OptimizeMojo extends SafeMojo implements CompilationStep {
);
new Home(dir).save(
xml.toString(),
- target
+ dir.relativize(target)
);
Logger.debug(
this, "Optimized %s (program:%s) to %s",
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/util/Home.java b/eo-maven-plugin/src/main/java/org/eolang/maven/util/Home.java
index c2b302591..e10108887 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/util/Home.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/util/Home.java
@@ -28,7 +28,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import org.cactoos.Bytes;
import org.cactoos.Input;
import org.cactoos.Text;
@@ -43,8 +42,6 @@ import org.cactoos.scalar.LengthOf;
* Base location for files.
*
* @since 0.27
- * @todo #1352:30min Prohibit absolute paths in methods `save`, `load`, `exists`.
- * Throw an exception in case absolut path is given for these methods.
*/
@SuppressWarnings("PMD.TooManyMethods")
public final class Home {
@@ -53,13 +50,6 @@ public final class Home {
*/
private final Path cwd;
- /**
- * Ctor.
- */
- public Home() {
- this(Paths.get(""));
- }
-
/**
* Ctor.
*
@@ -119,9 +109,10 @@ public final class Home {
* @param input Input
* @param path Cwd-relative path to file
* @throws IOException If fails
+ * @throws IllegalArgumentException If give path is absolute
*/
public void save(final Input input, final Path path) throws IOException {
- final Path target = this.absolute(path);
+ final Path target = this.absolute(this.onlyRelative(path));
if (target.toFile().getParentFile().mkdirs()) {
Logger.debug(
this, "Directory created: %s",
@@ -157,9 +148,10 @@ public final class Home {
*
* @param path Cwd-relative path to file
* @return True if exists
+ * @throws IllegalArgumentException If give path is absolute
*/
public boolean exists(final Path path) {
- return Files.exists(this.absolute(path));
+ return Files.exists(this.absolute(this.onlyRelative(path)));
}
/**
@@ -169,9 +161,10 @@ public final class Home {
* @return Bytes of file
* @throws IOException if method can't find the file by path or
* if some exception happens during reading the file
+ * @throws IllegalArgumentException If give path is absolute
*/
public Bytes load(final Path path) throws IOException {
- return new BytesOf(Files.readAllBytes(this.absolute(path)));
+ return new BytesOf(Files.readAllBytes(this.absolute(this.onlyRelative(path))));
}
/**
@@ -183,4 +176,23 @@ public final class Home {
public Path absolute(final Path path) {
return this.cwd.resolve(path);
}
+
+ /**
+ * Verifies that given path is relative and throws exception if not.
+ * @param path Path to be verified
+ * @return Given path if it's relative
+ * @throws IllegalArgumentException If given path is Absolute
+ */
+ private Path onlyRelative(final Path path) {
+ if (path.isAbsolute()) {
+ throw new IllegalArgumentException(
+ String.format(
+ "Path must be relative to base %s but absolute given: %s",
+ this.cwd,
+ path
+ )
+ );
+ }
+ return path;
+ }
}
diff --git a/eo-maven-plugin/src/test/java/org/eolang/maven/ProbeMojoTest.java b/eo-maven-plugin/src/test/java/org/eolang/maven/ProbeMojoTest.java
index ce49c5fec..915269e36 100644
--- a/eo-maven-plugin/src/test/java/org/eolang/maven/ProbeMojoTest.java
+++ b/eo-maven-plugin/src/test/java/org/eolang/maven/ProbeMojoTest.java
@@ -26,6 +26,7 @@ package org.eolang.maven;
import com.yegor256.tojos.MnCsv;
import java.io.IOException;
import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.LinkedList;
import org.cactoos.io.ResourceOf;
import org.cactoos.text.TextOf;
@@ -67,9 +68,9 @@ final class ProbeMojoTest {
@Test
void findsProbesViaOfflineHashFile(@TempDir final Path temp) throws IOException {
- new Home().save(
+ new Home(temp).save(
new ResourceOf("org/eolang/maven/commits/tags.txt"),
- temp.resolve("tags.txt")
+ Paths.get("tags.txt")
);
MatcherAssert.assertThat(
ProbeMojoTest.firstEntry(
diff --git a/eo-maven-plugin/src/test/java/org/eolang/maven/PullMojoTest.java b/eo-maven-plugin/src/test/java/org/eolang/maven/PullMojoTest.java
index a56942277..b0dc852f2 100644
--- a/eo-maven-plugin/src/test/java/org/eolang/maven/PullMojoTest.java
+++ b/eo-maven-plugin/src/test/java/org/eolang/maven/PullMojoTest.java
@@ -94,7 +94,7 @@ final class PullMojoTest {
new ResourceOf("org/eolang/maven/simple-io.eo")
)
),
- program
+ temp.relativize(program)
);
Catalogs.INSTANCE.make(temp.resolve("eo-foreign.json"), "json")
.add("foo.src")
@@ -144,9 +144,9 @@ final class PullMojoTest {
@Test
void pullsUsingOfflineHashFile(@TempDir final Path temp) throws IOException {
- new Home().save(
+ new Home(temp).save(
new ResourceOf("org/eolang/maven/commits/tags.txt"),
- temp.resolve("tags.txt")
+ Paths.get("tags.txt")
);
final Path target = temp.resolve("target");
final Path foreign = temp.resolve("eo-foreign.json");
diff --git a/eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java b/eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java
index c1f2300db..eaf8fe6ee 100644
--- a/eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java
+++ b/eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java
@@ -27,6 +27,7 @@ import com.yegor256.tojos.Tojo;
import com.yegor256.tojos.Tojos;
import java.io.IOException;
import java.nio.file.Path;
+import java.nio.file.Paths;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.List;
@@ -235,11 +236,13 @@ final class UnplaceMojoTest {
* @throws IOException If fails.
*/
private static Path clazz(final Path temp) throws IOException {
- final Path path = temp.resolve(
- String.format("a/b/c/%d_foo.class", new SecureRandom().nextInt())
+ final Path path =
+ Paths.get(String.format("a/b/c/%d_foo.class", new SecureRandom().nextInt()));
+ new Home(temp).save(
+ () -> UUID.randomUUID().toString(),
+ path
);
- new Home().save(() -> UUID.randomUUID().toString(), path);
- return path;
+ return temp.resolve(path);
}
/**
diff --git a/eo-maven-plugin/src/test/java/org/eolang/maven/dependencies/DcsJsonTest.java b/eo-maven-plugin/src/test/java/org/eolang/maven/dependencies/DcsJsonTest.java
index 43ef75790..72bdc552a 100644
--- a/eo-maven-plugin/src/test/java/org/eolang/maven/dependencies/DcsJsonTest.java
+++ b/eo-maven-plugin/src/test/java/org/eolang/maven/dependencies/DcsJsonTest.java
@@ -25,6 +25,7 @@ package org.eolang.maven.dependencies;
import java.io.IOException;
import java.nio.file.Path;
+import java.nio.file.Paths;
import org.cactoos.io.ResourceOf;
import org.cactoos.scalar.LengthOf;
import org.eolang.maven.util.Home;
@@ -60,11 +61,11 @@ final class DcsJsonTest {
private Path file(final Path tmp, final String name) {
try {
final Path res = tmp.resolve(name);
- new Home().save(
+ new Home(tmp).save(
new ResourceOf(
String.format("org/eolang/maven/dependencies/%s", name)
),
- res
+ Paths.get(name)
);
return res;
} catch (final IOException ex) {
diff --git a/eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChCompoundTest.java b/eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChCompoundTest.java
index 878de6e9c..9d5843b9b 100644
--- a/eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChCompoundTest.java
+++ b/eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChCompoundTest.java
@@ -26,6 +26,7 @@ package org.eolang.maven.hash;
import java.io.IOException;
import java.nio.file.Path;
+import java.nio.file.Paths;
import org.cactoos.io.ResourceOf;
import org.eolang.maven.OnlineCondition;
import org.eolang.maven.util.Home;
@@ -70,7 +71,10 @@ final class ChCompoundTest {
@Test
void getsCommitHashValueFromFile(@TempDir final Path temp) throws IOException {
final Path file = temp.resolve("tags.txt");
- new Home().save(new ResourceOf("org/eolang/maven/commits/tags.txt"), file);
+ new Home(temp).save(
+ new ResourceOf("org/eolang/maven/commits/tags.txt"),
+ Paths.get("tags.txt")
+ );
MatcherAssert.assertThat(
new ChCompound(
file,
diff --git a/eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChTextTest.java b/eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChTextTest.java
index 1a35f3b4f..5713425f6 100644
--- a/eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChTextTest.java
+++ b/eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChTextTest.java
@@ -51,7 +51,10 @@ class ChTextTest {
@BeforeAll
static void setUp(@TempDir final Path dir) throws IOException {
ChTextTest.file = dir.resolve("tags.txt");
- new Home().save(new ResourceOf("org/eolang/maven/commits/tags.txt"), ChTextTest.file);
+ new Home(dir).save(
+ new ResourceOf("org/eolang/maven/commits/tags.txt"),
+ dir.relativize(ChTextTest.file)
+ );
}
@ParameterizedTest
diff --git a/eo-maven-plugin/src/test/java/org/eolang/maven/util/HomeTest.java b/eo-maven-plugin/src/test/java/org/eolang/maven/util/HomeTest.java
index 94e1d4045..45ce38d0b 100644
--- a/eo-maven-plugin/src/test/java/org/eolang/maven/util/HomeTest.java
+++ b/eo-maven-plugin/src/test/java/org/eolang/maven/util/HomeTest.java
@@ -50,20 +50,21 @@ final class HomeTest {
@ValueSource(ints = {0, 100, 1_000, 10_000})
@ParameterizedTest
void saves(final int size, @TempDir final Path temp) throws IOException {
- final Path resolve = temp.resolve("1.txt");
+ final Path resolve = Paths.get("1.txt");
final String content = new UncheckedText(new Randomized(size)).asString();
new Home(temp).save(content, resolve);
MatcherAssert.assertThat(
- new UncheckedText(new TextOf(resolve)).asString(),
+ new UncheckedText(new TextOf(temp.resolve(resolve))).asString(),
Matchers.is(content)
);
}
@Test
void exists(@TempDir final Path temp) throws IOException {
- Files.write(temp.resolve("file.txt"), "any content".getBytes());
+ final Path path = Paths.get("file.txt");
+ Files.write(temp.resolve(path), "any content".getBytes());
MatcherAssert.assertThat(
- new Home(temp).exists(Paths.get("file.txt")),
+ new Home(temp).exists(path),
Matchers.is(true)
);
}
@@ -109,7 +110,7 @@ final class HomeTest {
void loadsBytesFromExistingFile(@TempDir final Path temp) throws IOException {
final Home home = new Home(temp);
final String content = "bar";
- final Path subfolder = temp.resolve("subfolder").resolve("foo.txt");
+ final Path subfolder = Paths.get("subfolder", "foo.txt");
home.save(content, subfolder);
MatcherAssert.assertThat(
new TextOf(home.load(subfolder)),
@@ -121,7 +122,15 @@ final class HomeTest {
void loadsFromAbsentFile(@TempDir final Path temp) {
Assertions.assertThrows(
NoSuchFileException.class,
- () -> new Home(temp).load(temp.resolve("nonexistent"))
+ () -> new Home(temp).load(Paths.get("nonexistent"))
+ );
+ }
+
+ @Test
+ void throwsExceptionOnAbsolute(@TempDir final Path temp) {
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> new Home(temp).exists(Paths.get("/tmp/file.txt"))
);
}
} | ['eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChCompoundTest.java', 'eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java', 'eo-maven-plugin/src/test/java/org/eolang/maven/dependencies/DcsJsonTest.java', 'eo-maven-plugin/src/test/java/org/eolang/maven/util/HomeTest.java', 'eo-maven-plugin/src/test/java/org/eolang/maven/ProbeMojoTest.java', 'eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChTextTest.java', 'eo-maven-plugin/src/test/java/org/eolang/maven/PullMojoTest.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/OptimizeMojo.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/util/Home.java'] | {'.java': 9} | 9 | 9 | 0 | 0 | 9 | 661,513 | 145,088 | 21,045 | 194 | 1,550 | 301 | 40 | 2 | 627 | 66 | 201 | 10 | 3 | 0 | 1970-01-01T00:27:59 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,443 | objectionary/eo/1037/1007 | objectionary | eo | https://github.com/objectionary/eo/issues/1007 | https://github.com/objectionary/eo/pull/1037 | https://github.com/objectionary/eo/pull/1037 | 1 | closes | Ram is not thread safe | Ram is a singleton, if it's being used from two threads, CME will happen.
https://github.com/objectionary/eo/blob/master/eo-runtime/src/main/java/EOorg/EOeolang/Ram.java
https://github.com/objectionary/eo/blob/master/eo-runtime/src/main/eo/org/eolang/ram.eo | dc485edf1c92e2a6c43cf4deaa4dc5dee321d69c | 7cca6fbe3320faa1151e7a78836114cfc3cba194 | https://github.com/objectionary/eo/compare/dc485edf1c92e2a6c43cf4deaa4dc5dee321d69c...7cca6fbe3320faa1151e7a78836114cfc3cba194 | diff --git a/eo-runtime/src/main/java/EOorg/EOeolang/Ram.java b/eo-runtime/src/main/java/EOorg/EOeolang/Ram.java
index c0520bfd7..a22e10ec2 100644
--- a/eo-runtime/src/main/java/EOorg/EOeolang/Ram.java
+++ b/eo-runtime/src/main/java/EOorg/EOeolang/Ram.java
@@ -32,8 +32,8 @@ import java.io.RandomAccessFile;
import java.io.UncheckedIOException;
import java.lang.management.ManagementFactory;
import java.nio.file.Files;
-import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
import org.eolang.Dataized;
import org.eolang.Phi;
@@ -51,7 +51,7 @@ public enum Ram {
/**
* Phi to File mapping.
*/
- private final Map<Phi, RandomAccessFile> addresses = new HashMap<>();
+ private final Map<Phi, RandomAccessFile> addresses = new ConcurrentHashMap<>();
/**
* Read.
diff --git a/eo-runtime/src/test/java/EOorg/EOeolang/RamTest.java b/eo-runtime/src/test/java/EOorg/EOeolang/RamTest.java
index 6ec564bd4..5886561db 100644
--- a/eo-runtime/src/test/java/EOorg/EOeolang/RamTest.java
+++ b/eo-runtime/src/test/java/EOorg/EOeolang/RamTest.java
@@ -7,6 +7,8 @@ import org.eolang.PhWith;
import org.eolang.Phi;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
+import org.junit.jupiter.api.parallel.Execution;
+import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@@ -14,6 +16,7 @@ import org.junit.jupiter.params.provider.CsvSource;
* Test for {@link Ram}.
* @since 1.0
*/
+@Execution(ExecutionMode.CONCURRENT)
final class RamTest {
@ParameterizedTest
@CsvSource({ | ['eo-runtime/src/main/java/EOorg/EOeolang/Ram.java', 'eo-runtime/src/test/java/EOorg/EOeolang/RamTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 511,071 | 111,634 | 16,463 | 161 | 234 | 44 | 4 | 1 | 259 | 16 | 74 | 3 | 2 | 0 | 1970-01-01T00:27:40 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,440 | objectionary/eo/1329/1322 | objectionary | eo | https://github.com/objectionary/eo/issues/1322 | https://github.com/objectionary/eo/pull/1329 | https://github.com/objectionary/eo/pull/1329 | 1 | fix | Unique hashcodes in parallel | @yegor256 @mximp Now the test passes succesfully with `threads = 100` but failes when `threads = 1000`:
```
@Test
public void phiUniqueHashesInDynamic() {
final int threads = 1000;
final Set<Integer> hashes = ConcurrentHashMap.newKeySet();
new Threads<>(
threads,
Stream.generate(
() -> (Scalar<Integer>) () -> (new EOmutex$EOacquire(Phi.Φ)).hashCode()
).limit(threads).collect(Collectors.toList())
).forEach(hashes::add);
MatcherAssert.assertThat(
hashes.size(),
Matchers.equalTo(threads)
);
}
```
```
[ERROR] Failures:
[ERROR] EOmutexTest.phiUniqueHashesInDynamic:88
Expected: <1000>
but: was <988>
[ERROR] Tests run: 27, Failures: 1, Errors: 0, Skipped: 0
```
| cd3465dfb99b6daee240c32931b87e4f60501343 | ee5099c29b78a4044c825e2196e7d1af47fc1c02 | https://github.com/objectionary/eo/compare/cd3465dfb99b6daee240c32931b87e4f60501343...ee5099c29b78a4044c825e2196e7d1af47fc1c02 | diff --git a/eo-runtime/src/main/java/org/eolang/Vertices.java b/eo-runtime/src/main/java/org/eolang/Vertices.java
index f8caa087f..1fba45eac 100644
--- a/eo-runtime/src/main/java/org/eolang/Vertices.java
+++ b/eo-runtime/src/main/java/org/eolang/Vertices.java
@@ -57,7 +57,7 @@ final class Vertices {
public int next() {
return this.seen.computeIfAbsent(
String.format("next:%d", this.count.addAndGet(1)),
- key -> this.seen.size() + 1
+ key -> this.count.addAndGet(1)
);
}
@@ -97,7 +97,7 @@ final class Vertices {
);
final String hash = new String(digest.digest());
return this.seen.computeIfAbsent(
- hash, key -> this.seen.size() + 1
+ hash, key -> this.count.addAndGet(1)
);
}
diff --git a/eo-runtime/src/test/java/org/eolang/VerticesTest.java b/eo-runtime/src/test/java/org/eolang/VerticesTest.java
index 5f3d7299f..0bee3bed8 100644
--- a/eo-runtime/src/test/java/org/eolang/VerticesTest.java
+++ b/eo-runtime/src/test/java/org/eolang/VerticesTest.java
@@ -23,6 +23,8 @@
*/
package org.eolang;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -45,7 +47,7 @@ final class VerticesTest {
void makesNext() {
MatcherAssert.assertThat(
new Vertices().next(),
- Matchers.equalTo(1)
+ Matchers.greaterThan(0)
);
}
@@ -59,16 +61,30 @@ final class VerticesTest {
);
}
+ /**
+ * Test that {@link Vertices#best(Object)} and {@link Vertices#next()}
+ * works correctly in multithreaded environment, i.e. produces non-repeatable
+ * values.
+ */
@Test
- void vtxThreadTest() {
+ void vtxConcurrencyTest() {
final Set<Integer> hashes = ConcurrentHashMap.newKeySet();
final Vertices vtx = new Vertices();
- final int threads = 8;
+ final int threads = 1000;
+ final List<Scalar<Integer>> tasks = new ArrayList<>(threads);
+ tasks.addAll(
+ Stream.generate(() -> (Scalar<Integer>) vtx::next)
+ .limit(threads / 2)
+ .collect(Collectors.toList())
+ );
+ tasks.addAll(
+ Stream.generate(() -> (Scalar<Integer>) () -> vtx.best(new Random().nextLong()))
+ .limit(threads / 2)
+ .collect(Collectors.toList())
+ );
new Threads<>(
threads,
- Stream.generate(
- () -> (Scalar<Integer>) () -> vtx.best(new Random().nextLong())
- ).limit(threads).collect(Collectors.toList())
+ tasks
).forEach(hashes::add);
MatcherAssert.assertThat(
hashes.size(), | ['eo-runtime/src/main/java/org/eolang/Vertices.java', 'eo-runtime/src/test/java/org/eolang/VerticesTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 525,196 | 115,485 | 16,957 | 157 | 181 | 48 | 4 | 1 | 833 | 73 | 212 | 26 | 0 | 2 | 1970-01-01T00:27:45 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,446 | objectionary/eo/889/739 | objectionary | eo | https://github.com/objectionary/eo/issues/739 | https://github.com/objectionary/eo/pull/889 | https://github.com/objectionary/eo/pull/889 | 1 | fixes | turn on Checkstyle in eo-runtime | At the moment it's disabled. Let's turn it on and fix the code. | a2a061c337d2da27fd91cba58119e246be4844e6 | 3d5bc78d6ce941ee51b17d1123601715fe008173 | https://github.com/objectionary/eo/compare/a2a061c337d2da27fd91cba58119e246be4844e6...3d5bc78d6ce941ee51b17d1123601715fe008173 | diff --git a/eo-runtime/src/main/java/EOorg/EOeolang/EOfloat$EOdiv.java b/eo-runtime/src/main/java/EOorg/EOeolang/EOfloat$EOdiv.java
index abb876102..718e1d1d6 100644
--- a/eo-runtime/src/main/java/EOorg/EOeolang/EOfloat$EOdiv.java
+++ b/eo-runtime/src/main/java/EOorg/EOeolang/EOfloat$EOdiv.java
@@ -59,7 +59,13 @@ public class EOfloat$EOdiv extends PhDefault {
"x",
Double.class,
(acc, x) -> acc / x,
- x -> x.equals(0.0) ? "division by zero is infinity" : ""
+ x -> {
+ String msg = "";
+ if (x.equals(0.0)) {
+ msg = "division by zero is infinity";
+ }
+ return msg;
+ }
)
)
);
diff --git a/eo-runtime/src/main/java/EOorg/EOeolang/EOheap$EOpointer$EOblock.java b/eo-runtime/src/main/java/EOorg/EOeolang/EOheap$EOpointer$EOblock.java
index 7c336a19f..47a246f67 100644
--- a/eo-runtime/src/main/java/EOorg/EOeolang/EOheap$EOpointer$EOblock.java
+++ b/eo-runtime/src/main/java/EOorg/EOeolang/EOheap$EOpointer$EOblock.java
@@ -96,7 +96,8 @@ public class EOheap$EOpointer$EOblock extends PhDefault {
rho -> {
final Phi block = rho.attr("σ").get();
final Phi pointer = block.attr("σ").get();
- final int address = new Param(pointer, "address").strong(Long.class).intValue();
+ final int address =
+ new Param(pointer, "address").strong(Long.class).intValue();
final byte[] source = new Param(rho, "x").strong(byte[].class);
final byte[] data = Heaps.INSTANCE.data(pointer);
System.arraycopy(source, 0, data, address, source.length);
diff --git a/eo-runtime/src/main/java/EOorg/EOeolang/EOint$EOdiv.java b/eo-runtime/src/main/java/EOorg/EOeolang/EOint$EOdiv.java
index b8282d986..55e0fb771 100644
--- a/eo-runtime/src/main/java/EOorg/EOeolang/EOint$EOdiv.java
+++ b/eo-runtime/src/main/java/EOorg/EOeolang/EOint$EOdiv.java
@@ -64,7 +64,13 @@ public class EOint$EOdiv extends PhDefault {
"x",
Long.class,
(acc, x) -> acc / x,
- x -> x.equals(0L) ? "division by zero is infinity" : ""
+ x -> {
+ String msg = "";
+ if (x.equals(0L)) {
+ msg = "division by zero is infinity";
+ }
+ return msg;
+ }
)
)
);
diff --git a/eo-runtime/src/main/java/EOorg/EOeolang/EOram$EOread.java b/eo-runtime/src/main/java/EOorg/EOeolang/EOram$EOread.java
index 58f73c9e0..06ca0d0bb 100644
--- a/eo-runtime/src/main/java/EOorg/EOeolang/EOram$EOread.java
+++ b/eo-runtime/src/main/java/EOorg/EOeolang/EOram$EOread.java
@@ -46,7 +46,7 @@ public class EOram$EOread extends PhDefault {
* Ctor.
* @param sigma Sigma
*/
- public EOram$EOread(Phi sigma) {
+ public EOram$EOread(final Phi sigma) {
super(sigma);
this.add("p", new AtFree());
this.add("l", new AtFree());
@@ -58,13 +58,10 @@ public class EOram$EOread extends PhDefault {
final int pos = new Param(rho, "p").strong(Long.class).intValue();
final int len = new Param(rho, "l").strong(Long.class).intValue();
return new Data.ToPhi(
- Ram.INSTANCE.read(
- rho.attr("ρ").get(), pos, len)
+ Ram.INSTANCE.read(rho.attr("ρ").get(), pos, len)
);
}
)
);
}
-
-
}
diff --git a/eo-runtime/src/main/java/EOorg/EOeolang/EOstring$EOslice.java b/eo-runtime/src/main/java/EOorg/EOeolang/EOstring$EOslice.java
index 0c90928d3..890fa8934 100644
--- a/eo-runtime/src/main/java/EOorg/EOeolang/EOstring$EOslice.java
+++ b/eo-runtime/src/main/java/EOorg/EOeolang/EOstring$EOslice.java
@@ -62,7 +62,7 @@ public class EOstring$EOslice extends PhDefault {
final int start = new Param(rho, "start").strong(Long.class).intValue();
final int length = new Param(rho, "len").strong(Long.class).intValue();
final int end = length + start;
- Phi result;
+ final Phi result;
if (start < 0) {
result = error(
"Start index must be greater than 0 but was %d",
@@ -91,7 +91,7 @@ public class EOstring$EOslice extends PhDefault {
* Building error.
* @param msg Formatted string for error message
* @param args Arguments for the formatted string
- * @return φ containing error
+ * @return A φ containing error
*/
private static Phi error(final String msg, final Object... args) {
return new PhWith(
diff --git a/eo-runtime/src/main/java/EOorg/EOeolang/EOtxt/EOtext$EOtrim.java b/eo-runtime/src/main/java/EOorg/EOeolang/EOtxt/EOtext$EOtrim.java
index 8658c4998..7261c0541 100644
--- a/eo-runtime/src/main/java/EOorg/EOeolang/EOtxt/EOtext$EOtrim.java
+++ b/eo-runtime/src/main/java/EOorg/EOeolang/EOtxt/EOtext$EOtrim.java
@@ -55,8 +55,8 @@ public class EOtext$EOtrim extends PhDefault {
this,
rho -> {
final Phi text = rho.attr("ρ").get();
- final String s = new Param(text, "s").strong(String.class);
- return new Data.ToPhi(s.trim());
+ final String content = new Param(text, "s").strong(String.class);
+ return new Data.ToPhi(content.trim());
}
)
);
diff --git a/eo-runtime/src/main/java/EOorg/EOeolang/Ram.java b/eo-runtime/src/main/java/EOorg/EOeolang/Ram.java
index a3c2eb41f..70e2a2b12 100644
--- a/eo-runtime/src/main/java/EOorg/EOeolang/Ram.java
+++ b/eo-runtime/src/main/java/EOorg/EOeolang/Ram.java
@@ -66,7 +66,7 @@ public enum Ram {
final int position,
final int length
) throws IOException {
- final RandomAccessFile ram = init(object);
+ final RandomAccessFile ram = this.init(object);
ram.seek(position);
final byte[] buffer = new byte[length];
ram.readFully(buffer, 0, length);
@@ -112,8 +112,8 @@ public enum Ram {
);
file.setLength(size);
return file;
- } catch (final IOException e) {
- throw new UncheckedIOException(e);
+ } catch (final IOException ex) {
+ throw new UncheckedIOException(ex);
}
}
);
diff --git a/eo-runtime/src/main/java/org/eolang/AtNamed.java b/eo-runtime/src/main/java/org/eolang/AtNamed.java
index 0b96410da..1bea27923 100644
--- a/eo-runtime/src/main/java/org/eolang/AtNamed.java
+++ b/eo-runtime/src/main/java/org/eolang/AtNamed.java
@@ -57,6 +57,7 @@ final class AtNamed implements Attr {
* @param onme Oname
* @param src Source φ
* @param attr Attribute
+ * @checkstyle ParameterNumberCheck (10 lines)
*/
AtNamed(final String nme, final String onme,
final Phi src, final Attr attr) {
diff --git a/eo-runtime/src/main/java/org/eolang/Data.java b/eo-runtime/src/main/java/org/eolang/Data.java
index c9eb09c7c..10cd1ffe4 100644
--- a/eo-runtime/src/main/java/org/eolang/Data.java
+++ b/eo-runtime/src/main/java/org/eolang/Data.java
@@ -88,6 +88,13 @@ public interface Data<T> {
return this.take().hashCode();
}
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj) return true;
+ if (obj == null || getClass() != obj.getClass()) return false;
+ return this.take().equals(((Once<?>) obj).take());
+ }
+
@Override
public String toString() {
final T data = this.ref.get();
diff --git a/eo-runtime/src/main/java/org/eolang/PhPackage.java b/eo-runtime/src/main/java/org/eolang/PhPackage.java
index e2ecec3c3..08e82e137 100644
--- a/eo-runtime/src/main/java/org/eolang/PhPackage.java
+++ b/eo-runtime/src/main/java/org/eolang/PhPackage.java
@@ -68,11 +68,13 @@ final class PhPackage implements Phi {
return new AtSimple(
this.objects.computeIfAbsent(
target, t -> {
+ Phi phi;
try {
- return this.sub(t);
+ phi = this.sub(t);
} catch (final ClassNotFoundException ex) {
- return new PhPackage(abs.toString());
+ phi = new PhPackage(abs.toString());
}
+ return phi;
}
)
);
diff --git a/eo-runtime/src/main/java/org/eolang/Term.java b/eo-runtime/src/main/java/org/eolang/Term.java
index 4d679f59b..f2beb66e3 100644
--- a/eo-runtime/src/main/java/org/eolang/Term.java
+++ b/eo-runtime/src/main/java/org/eolang/Term.java
@@ -35,6 +35,7 @@ public interface Term {
* To φ-calculus term, as text.
*
* @return The expression in φ-calculus
+ * @checkstyle MethodNameCheck (5 lines)
*/
String φTerm();
| ['eo-runtime/src/main/java/org/eolang/Data.java', 'eo-runtime/src/main/java/EOorg/EOeolang/EOheap$EOpointer$EOblock.java', 'eo-runtime/src/main/java/EOorg/EOeolang/EOstring$EOslice.java', 'eo-runtime/src/main/java/EOorg/EOeolang/EOint$EOdiv.java', 'eo-runtime/src/main/java/EOorg/EOeolang/EOram$EOread.java', 'eo-runtime/src/main/java/EOorg/EOeolang/EOfloat$EOdiv.java', 'eo-runtime/src/main/java/org/eolang/Term.java', 'eo-runtime/src/main/java/org/eolang/AtNamed.java', 'eo-runtime/src/main/java/EOorg/EOeolang/Ram.java', 'eo-runtime/src/main/java/org/eolang/PhPackage.java', 'eo-runtime/src/main/java/EOorg/EOeolang/EOtxt/EOtext$EOtrim.java'] | {'.java': 11} | 11 | 11 | 0 | 0 | 11 | 488,625 | 107,063 | 15,707 | 153 | 2,576 | 458 | 55 | 11 | 63 | 13 | 17 | 1 | 0 | 0 | 1970-01-01T00:27:38 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,445 | objectionary/eo/891/873 | objectionary | eo | https://github.com/objectionary/eo/issues/873 | https://github.com/objectionary/eo/pull/891 | https://github.com/objectionary/eo/pull/891 | 2 | fixed | UnplaceMojo.delete() doesn't delete empty directories | `UnplaceMojo.delete()` deletes directories only sometimes. Some of them (even though they are empty) stay on the disc. Let's find out why it's happening, reproduce this in a test, and fix. | 24920402dbf3122c9a24f05e59e4f56427e0ca85 | 45df2a303010596945b7af1ddae94ddd1a896a57 | https://github.com/objectionary/eo/compare/24920402dbf3122c9a24f05e59e4f56427e0ca85...45df2a303010596945b7af1ddae94ddd1a896a57 | diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java b/eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java
index 73011adfe..5ce04bb5c 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java
@@ -241,10 +241,12 @@ public final class UnplaceMojo extends SafeMojo {
* @throws IOException If fails
*/
private static void delete(final Path file) throws IOException {
- final Path dir = file.getParent();
+ Path dir = file.getParent();
Files.delete(file);
- if (!Files.newDirectoryStream(dir).iterator().hasNext()) {
- Files.delete(dir);
+ while (!Files.newDirectoryStream(dir).iterator().hasNext()) {
+ final Path curdir = dir;
+ dir = curdir.getParent();
+ Files.delete(curdir);
Logger.debug(
UnplaceMojo.class,
"Empty directory deleted too: %s",
diff --git a/eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java b/eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java
index b63242458..9075afd7d 100644
--- a/eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java
+++ b/eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java
@@ -27,6 +27,7 @@ import com.yegor256.tojos.Csv;
import com.yegor256.tojos.MonoTojos;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.Paths;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
@@ -36,18 +37,39 @@ import org.junit.jupiter.api.io.TempDir;
* Test case for {@link UnplaceMojo}.
*
* @since 0.1
+ * @checkstyle LocalFinalVariableNameCheck (100 lines)
*/
+@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public final class UnplaceMojoTest {
@Test
public void testCleaning(@TempDir final Path temp) throws Exception {
final Path foo = temp.resolve("a/b/c/foo.class");
- new Save("abc", foo).save();
+ new Save("...", foo).save();
+ final Path pparent = foo.getParent().getParent();
+ final Path foo2 = temp.resolve("a/b/c/foo2.class");
+ new Save("...", foo2).save();
+ final Path foo3 = temp.resolve("a/b/c/d/foo3.class");
+ new Save("...", foo3).save();
+ final Path foo4 = temp.resolve("a/b/c/e/foo4.class");
+ new Save("...", foo4).save();
final Path list = temp.resolve("placed.json");
new MonoTojos(new Csv(list)).add(foo.toString())
.set("kind", "class")
.set(PlaceMojo.ATTR_RELATED, "---")
.set("hash", new FileHash(foo));
+ new MonoTojos(new Csv(list)).add(foo2.toString())
+ .set("kind", "class")
+ .set(PlaceMojo.ATTR_RELATED, "---")
+ .set("hash", new FileHash(foo2));
+ new MonoTojos(new Csv(list)).add(foo3.toString())
+ .set("kind", "class")
+ .set(PlaceMojo.ATTR_RELATED, "---")
+ .set("hash", new FileHash(foo3));
+ new MonoTojos(new Csv(list)).add(foo4.toString())
+ .set("kind", "class")
+ .set(PlaceMojo.ATTR_RELATED, "---")
+ .set("hash", new FileHash(foo4));
new Moja<>(UnplaceMojo.class)
.with("placed", list.toFile())
.with("placedFormat", "csv")
@@ -56,5 +78,21 @@ public final class UnplaceMojoTest {
Files.exists(foo),
Matchers.is(false)
);
+ MatcherAssert.assertThat(
+ Files.exists(foo2),
+ Matchers.is(false)
+ );
+ MatcherAssert.assertThat(
+ Files.exists(foo3),
+ Matchers.is(false)
+ );
+ MatcherAssert.assertThat(
+ Files.exists(foo4),
+ Matchers.is(false)
+ );
+ MatcherAssert.assertThat(
+ Files.exists(Paths.get(String.valueOf(pparent))),
+ Matchers.is(false)
+ );
}
} | ['eo-maven-plugin/src/test/java/org/eolang/maven/UnplaceMojoTest.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/UnplaceMojo.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 489,774 | 107,332 | 15,728 | 154 | 364 | 71 | 8 | 1 | 188 | 30 | 45 | 1 | 0 | 0 | 1970-01-01T00:27:38 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,444 | objectionary/eo/899/640 | objectionary | eo | https://github.com/objectionary/eo/issues/640 | https://github.com/objectionary/eo/pull/899 | https://github.com/objectionary/eo/pull/899 | 1 | resolve | RegisterMojo.java:80-85: Here, the "property" attribute... | The puzzle `636-57a3ebdc` from #636 has to be resolved:
https://github.com/objectionary/eo/blob/59079f6a983651efc77280ec322a1a011a92b936/eo-maven-plugin/src/main/java/org/eolang/maven/RegisterMojo.java#L80-L85
The puzzle was created by @yegor256 on 16-May-22.
Estimate: 30 minutes, role: DEV.
If you have any technical questions, don't ask me, submit new tickets instead. The task will be \\"done\\" when the problem is fixed and the text of the puzzle is _removed_ from the source code. Here is more about [PDD](http://www.yegor256.com/2009/03/04/pdd.html) and [about me](http://www.yegor256.com/2017/04/05/pdd-in-action.html).
| d4ecc1ec78b081fe3bcc9dbc3c3b0522d333acda | f52ceb38154f2554d65f6cd4ec6133f4de5876a8 | https://github.com/objectionary/eo/compare/d4ecc1ec78b081fe3bcc9dbc3c3b0522d333acda...f52ceb38154f2554d65f6cd4ec6133f4de5876a8 | diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/RegisterMojo.java b/eo-maven-plugin/src/main/java/org/eolang/maven/RegisterMojo.java
index 2b134b31c..4ccbc409b 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/RegisterMojo.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/RegisterMojo.java
@@ -74,16 +74,11 @@ public final class RegisterMojo extends SafeMojo {
/**
* List of inclusion GLOB filters for finding EO files
- * in the {@code <includeSources>} directory, which can be
+ * in the {@code <includeSources>} directory, which can be
* pretty global (or even a root one).
- *
+ * @implNote {@code property} attribute is omitted for collection
+ * properties since there is no way of passing it via command line.
* @checkstyle MemberNameCheck (15 lines)
- * @todo #636:30min Here, the "property" attribute of the @Parameter
- * annotation is not set. If we set it, in order to enable configuration
- * through command line arguments, the default value won't be set.
- * I don't know how to fix this. Let's investigate what is the right
- * way according to Maven traditions. If we fix this, let's also
- * fix "excludeSources" here and "include/excludeBinaries" in PlaceMojo.
*/
@Parameter
private Set<String> includeSources = new SetOf<>("**.eo"); | ['eo-maven-plugin/src/main/java/org/eolang/maven/RegisterMojo.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 489,837 | 107,348 | 15,730 | 154 | 736 | 183 | 11 | 1 | 636 | 66 | 205 | 10 | 3 | 0 | 1970-01-01T00:27:38 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,437 | objectionary/eo/1457/877 | objectionary | eo | https://github.com/objectionary/eo/issues/877 | https://github.com/objectionary/eo/pull/1457 | https://github.com/objectionary/eo/pull/1457 | 1 | closes | Fix checkstyle warnings for `PhDefault` | Split from #739
Refactor the class to pass all checkstyle checks.
Current warnings:
```
[INFO] Checkstyle: src/main/java/org/eolang/PhDefault.java[44]: Class Data Abstraction Coupling is 10 (max allowed is 7) classes [AtAbsent, AtNamed, AtPhiSensitive, AtSimple, CachedPhi, Data.ToPhi, ExFailure, Indented, ThreadLocal, Vertices]. (ClassDataAbstractionCouplingCheck)
[INFO] Checkstyle: src/main/java/org/eolang/PhDefault.java[59]: Variable 'vertex' must be private and have accessor methods. (VisibilityModifierCheck)
[INFO] Checkstyle: src/main/java/org/eolang/PhDefault.java[116]: Return count is 2 (max allowed for non-void methods/lambdas is 1). (ReturnCountCheck)
[INFO] Checkstyle: src/main/java/org/eolang/PhDefault.java[216]: Return count is 2 (max allowed for non-void methods/lambdas is 1). (ReturnCountCheck)
[INFO] Checkstyle: src/main/java/org/eolang/PhDefault.java[274]: Return count is 2 (max allowed for non-void methods/lambdas is 1). (ReturnCountCheck)
[INFO] Checkstyle: src/main/java/org/eolang/PhDefault.java[295]: Avoid inline conditionals. (AvoidInlineConditionalsCheck)
``` | c6ecefc10995b794e3e3b57c0364d5fd031108c5 | b866b95c3a67c30ba4eabca92a48dc14be9227f6 | https://github.com/objectionary/eo/compare/c6ecefc10995b794e3e3b57c0364d5fd031108c5...b866b95c3a67c30ba4eabca92a48dc14be9227f6 | diff --git a/eo-runtime/src/main/java/org/eolang/PhDefault.java b/eo-runtime/src/main/java/org/eolang/PhDefault.java
index 42e104148..46a390478 100644
--- a/eo-runtime/src/main/java/org/eolang/PhDefault.java
+++ b/eo-runtime/src/main/java/org/eolang/PhDefault.java
@@ -44,6 +44,7 @@ import java.util.stream.Collectors;
* @since 0.1
* @checkstyle DesignForExtensionCheck (500 lines)
*/
+@SuppressWarnings({"PMD.TooManyMethods", "PMD.ConstructorShouldDoInitialization"})
public abstract class PhDefault implements Phi, Cloneable {
/**
@@ -104,6 +105,7 @@ public abstract class PhDefault implements Phi, Cloneable {
*
* @param sigma Sigma
*/
+ @SuppressWarnings("PMD.ConstructorOnlyInitializesOrCallOtherConstructors")
public PhDefault(final Phi sigma) {
this.vertex = PhDefault.VTX.next();
this.attrs = new HashMap<>(0);
@@ -124,7 +126,7 @@ public abstract class PhDefault implements Phi, Cloneable {
@Override
public String φTerm() {
- if (PhDefault.TERMS.get() == null) {
+ if (null == PhDefault.TERMS.get()) {
PhDefault.TERMS.set(new HashSet<>());
}
String txt;
@@ -176,7 +178,7 @@ public abstract class PhDefault implements Phi, Cloneable {
@Override
public final Phi copy() {
try {
- final PhDefault copy = PhDefault.class.cast(this.clone());
+ final PhDefault copy = (PhDefault) this.clone();
copy.vertex = PhDefault.VTX.next();
copy.cached = new CachedPhi();
final Map<String, Attr> map = new HashMap<>(this.attrs.size());
@@ -192,7 +194,7 @@ public abstract class PhDefault implements Phi, Cloneable {
@Override
public final Attr attr(final int pos) {
- if (pos < 0) {
+ if (0 > pos) {
throw new ExFailure(
String.format(
"Attribute position can't be negative (%d)",
@@ -228,16 +230,16 @@ public abstract class PhDefault implements Phi, Cloneable {
@Override
public final Attr attr(final String name) {
- NESTING.set(NESTING.get() + 1);
+ PhDefault.NESTING.set(PhDefault.NESTING.get() + 1);
Attr attr;
if ("ν".equals(name)) {
attr = new AtSimple(new Data.ToPhi((long) this.hashCode()));
} else {
attr = this.attrs.get(name);
}
- if (attr == null) {
+ if (null == attr) {
final Attr aphi = this.attrs.get("φ");
- if (aphi == null) {
+ if (null == aphi) {
attr = new AtAbsent(
name,
String.format(
@@ -264,13 +266,13 @@ public abstract class PhDefault implements Phi, Cloneable {
PhDefault.debug(
String.format(
"%s\\uD835\\uDD38('%s' for %s) ➜ %s",
- padding(),
+ PhDefault.padding(),
name,
this,
attr
)
);
- NESTING.set(NESTING.get() - 1);
+ PhDefault.NESTING.set(PhDefault.NESTING.get() - 1);
return attr;
}
@@ -324,7 +326,7 @@ public abstract class PhDefault implements Phi, Cloneable {
private String oname() {
String txt = this.getClass().getSimpleName();
final XmirObject xmir = this.getClass().getAnnotation(XmirObject.class);
- if (xmir != null) {
+ if (null != xmir) {
txt = xmir.oname();
if ("@".equals(txt)) {
txt = "φ";
@@ -351,6 +353,6 @@ public abstract class PhDefault implements Phi, Cloneable {
* @return Padding string.
*/
private static String padding() {
- return String.join("", Collections.nCopies(NESTING.get(), "·"));
+ return String.join("", Collections.nCopies(PhDefault.NESTING.get(), "·"));
}
} | ['eo-runtime/src/main/java/org/eolang/PhDefault.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 602,101 | 131,420 | 19,234 | 180 | 1,047 | 272 | 22 | 1 | 1,110 | 105 | 299 | 12 | 0 | 1 | 1970-01-01T00:27:48 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,436 | objectionary/eo/1635/1563 | objectionary | eo | https://github.com/objectionary/eo/issues/1563 | https://github.com/objectionary/eo/pull/1635 | https://github.com/objectionary/eo/pull/1635 | 1 | closes | Can't dataize eo program with `cage`: `IndexOutOfBoundsException` | I'm trying to dataize the next `eo` program:
```
+alias org.eolang.txt.sprintf
+alias org.eolang.io.stdout
[val] > container
val > @
[] > loop
cage 0 > index
seq > @
index.write container 1
stdout
sprintf
"%s"
index
index.write container 2
stdout
sprintf
"%s"
index
index.write container 3
stdout
sprintf
"%s"
index
TRUE
```
Expected behaviour: program compiles and dataizes successfully.
Actual behaviour: I get the next exception:
```sh
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.get(ArrayList.java:459)
at org.eolang.PhDefault.attr(PhDefault.java:231)
at org.eolang.PhNamed.attr(PhNamed.java:87)
at org.eolang.PhSafe.attr(PhSafe.java:83)
at org.eolang.PhNamed.attr(PhNamed.java:87)
at org.eolang.PhImmovable.attr(PhImmovable.java:80)
at org.eolang.PhLocated.attr(PhLocated.java:94)
at org.eolang.PhOnce.attr(PhOnce.java:91)
at org.eolang.PhOnce.attr(PhOnce.java:91)
at org.eolang.PhWith.lambda$new$3(PhWith.java:86)
at org.eolang.Data$Once.lambda$take$0(Data.java:119)
at java.base/java.util.concurrent.atomic.AtomicReference.updateAndGet(AtomicReference.java:209)
at org.eolang.Data$Once.take(Data.java:115)
at org.eolang.PhOnce.attr(PhOnce.java:96)
at org.eolang.Dataized.take(Dataized.java:87)
at EOorg.EOeolang.EOseq.lambda$new$0(EOseq.java:63)
at org.eolang.AtComposite.get(AtComposite.java:73)
at org.eolang.CachedPhi.get(CachedPhi.java:81)
at org.eolang.PhDefault.attr(PhDefault.java:255)
at org.eolang.PhLocated.attr(PhLocated.java:99)
at org.eolang.PhOnce.attr(PhOnce.java:96)
at org.eolang.PhOnce.attr(PhOnce.java:96)
at org.eolang.PhOnce.attr(PhOnce.java:96)
at org.eolang.PhOnce.attr(PhOnce.java:96)
at org.eolang.PhOnce.attr(PhOnce.java:96)
at org.eolang.PhOnce.attr(PhOnce.java:96)
at org.eolang.PhOnce.attr(PhOnce.java:96)
at org.eolang.PhOnce.attr(PhOnce.java:96)
at org.eolang.PhDefault.attr(PhDefault.java:256)
at org.eolang.Dataized.take(Dataized.java:87)
at org.eolang.Dataized.take(Dataized.java:127)
at org.eolang.Main.run(Main.java:190)
at org.eolang.Main.main(Main.java:98)
```
| 3a77b348d0a6c25626294f6ee5be23e6ab2a924f | b9439ff760fe9ead2dd5c6c0487fc854684da568 | https://github.com/objectionary/eo/compare/3a77b348d0a6c25626294f6ee5be23e6ab2a924f...b9439ff760fe9ead2dd5c6c0487fc854684da568 | diff --git a/eo-runtime/src/main/java/org/eolang/PhDefault.java b/eo-runtime/src/main/java/org/eolang/PhDefault.java
index 46a390478..8635926ad 100644
--- a/eo-runtime/src/main/java/org/eolang/PhDefault.java
+++ b/eo-runtime/src/main/java/org/eolang/PhDefault.java
@@ -210,22 +210,25 @@ public abstract class PhDefault implements Phi, Cloneable {
)
);
}
- int idx;
- for (idx = 0; idx < pos; ++idx) {
+ Attr attr = this.attr(this.order.get(0));
+ for (int idx = 0; idx <= pos; ++idx) {
if (idx >= this.order.size()) {
throw new ExFailure(
String.format(
- "There are just %d attributes here, can't read the %d-th one",
- this.order.size(), pos
+ "%s has just %d attribute(s), can't read the %d-th one",
+ this,
+ this.order.size(),
+ pos
)
);
}
final String name = this.order.get(idx);
+ attr = this.attr(this.order.get(idx));
if (this.attrs.get(name) instanceof AtVararg) {
break;
}
}
- return this.attr(this.order.get(idx));
+ return attr;
}
@Override | ['eo-runtime/src/main/java/org/eolang/PhDefault.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 607,614 | 133,113 | 19,393 | 181 | 603 | 128 | 13 | 1 | 2,613 | 155 | 714 | 71 | 0 | 2 | 1970-01-01T00:27:52 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
9,434 | objectionary/eo/1880/1645 | objectionary | eo | https://github.com/objectionary/eo/issues/1645 | https://github.com/objectionary/eo/pull/1880 | https://github.com/objectionary/eo/pull/1880 | 1 | closes | ChResolve.java:38-40: Need to rename this class to a more... | The puzzle `1569-cc8ee668` from #1569 has to be resolved:
https://github.com/objectionary/eo/blob/ece321e208aa459ff46c05aeaebb61a3287d9f99/eo-maven-plugin/src/main/java/org/eolang/maven/hash/ChResolve.java#L38-L40
The puzzle was created by rultor on 30-Dec-22.
Estimate: 30 minutes, role: DEV.
If you have any technical questions, don't ask me, submit new tickets instead. The task will be \\"done\\" when the problem is fixed and the text of the puzzle is _removed_ from the source code. Here is more about [PDD](http://www.yegor256.com/2009/03/04/pdd.html) and [about me](http://www.yegor256.com/2017/04/05/pdd-in-action.html).
| f5e655ca99f2d8d4855c9fd6e5b0c72a8d46ae10 | 6bcc61183407425af88e15e22c490e4e524b1cf9 | https://github.com/objectionary/eo/compare/f5e655ca99f2d8d4855c9fd6e5b0c72a8d46ae10...6bcc61183407425af88e15e22c490e4e524b1cf9 | diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/ProbeMojo.java b/eo-maven-plugin/src/main/java/org/eolang/maven/ProbeMojo.java
index 5ca98b751..c22686ae1 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/ProbeMojo.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/ProbeMojo.java
@@ -38,8 +38,8 @@ import org.apache.maven.plugins.annotations.Parameter;
import org.cactoos.iterable.Filtered;
import org.cactoos.iterator.Mapped;
import org.cactoos.list.ListOf;
+import org.eolang.maven.hash.ChCompound;
import org.eolang.maven.hash.ChNarrow;
-import org.eolang.maven.hash.ChResolve;
import org.eolang.maven.hash.CommitHash;
import org.eolang.maven.objectionary.Objectionary;
import org.eolang.maven.objectionary.OyFallbackSwap;
@@ -120,7 +120,7 @@ public final class ProbeMojo extends SafeMojo {
row -> row.exists(AssembleMojo.ATTR_XMIR2)
&& !row.exists(AssembleMojo.ATTR_PROBED)
);
- final CommitHash hash = new ChResolve(
+ final CommitHash hash = new ChCompound(
this.offlineHashFile, this.offlineHash, this.tag
);
if (this.objectionary == null) {
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/PullMojo.java b/eo-maven-plugin/src/main/java/org/eolang/maven/PullMojo.java
index 960a7bfbe..61f57bcf2 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/PullMojo.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/PullMojo.java
@@ -34,8 +34,8 @@ import java.util.Collection;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
+import org.eolang.maven.hash.ChCompound;
import org.eolang.maven.hash.ChNarrow;
-import org.eolang.maven.hash.ChResolve;
import org.eolang.maven.hash.CommitHash;
import org.eolang.maven.objectionary.Objectionary;
import org.eolang.maven.objectionary.OyCaching;
@@ -128,7 +128,7 @@ public final class PullMojo extends SafeMojo implements CompilationStep {
row -> !row.exists(AssembleMojo.ATTR_EO)
&& !row.exists(AssembleMojo.ATTR_XMIR)
);
- final CommitHash hash = new ChResolve(
+ final CommitHash hash = new ChCompound(
this.offlineHashFile, this.offlineHash, this.tag
);
if (this.objectionary == null) {
diff --git a/eo-maven-plugin/src/main/java/org/eolang/maven/hash/ChResolve.java b/eo-maven-plugin/src/main/java/org/eolang/maven/hash/ChCompound.java
similarity index 90%
rename from eo-maven-plugin/src/main/java/org/eolang/maven/hash/ChResolve.java
rename to eo-maven-plugin/src/main/java/org/eolang/maven/hash/ChCompound.java
index b04eb38dc..a6c5f4b45 100644
--- a/eo-maven-plugin/src/main/java/org/eolang/maven/hash/ChResolve.java
+++ b/eo-maven-plugin/src/main/java/org/eolang/maven/hash/ChCompound.java
@@ -35,11 +35,8 @@ import java.nio.file.Path;
* be used to change the behavior of an object.
* Need to use composable decorators to make this class
* not configurable.
- * @todo #1569:30min Need to rename this class to a more correct one.
- * The correct one name will consist of prefix "Ch" and a noun or
- * adjective.
*/
-public final class ChResolve implements CommitHash {
+public final class ChCompound implements CommitHash {
/**
* Read hashes from local file.
@@ -65,7 +62,7 @@ public final class ChResolve implements CommitHash {
* @param text Hash by pattern
* @param label The Git hash to pull objects from
*/
- public ChResolve(final Path data, final String text, final String label) {
+ public ChCompound(final Path data, final String text, final String label) {
this.file = data;
this.hash = text;
this.tag = label;
diff --git a/eo-maven-plugin/src/test/java/org/eolang/maven/PullMojoTest.java b/eo-maven-plugin/src/test/java/org/eolang/maven/PullMojoTest.java
index cf6be3a83..a56942277 100644
--- a/eo-maven-plugin/src/test/java/org/eolang/maven/PullMojoTest.java
+++ b/eo-maven-plugin/src/test/java/org/eolang/maven/PullMojoTest.java
@@ -32,7 +32,7 @@ import java.util.LinkedList;
import org.cactoos.io.InputOf;
import org.cactoos.io.ResourceOf;
import org.cactoos.text.TextOf;
-import org.eolang.maven.hash.ChResolve;
+import org.eolang.maven.hash.ChCompound;
import org.eolang.maven.objectionary.Objectionary;
import org.eolang.maven.objectionary.OyRemote;
import org.eolang.maven.util.Home;
@@ -115,7 +115,7 @@ final class PullMojoTest {
.with("foreign", foreign)
.execute();
final Objectionary objectionary = new OyRemote(
- new ChResolve(null, null, "master")
+ new ChCompound(null, null, "master")
);
new Moja<>(ProbeMojo.class)
.with("targetDir", target)
diff --git a/eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChResolveTest.java b/eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChCompoundTest.java
similarity index 93%
rename from eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChResolveTest.java
rename to eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChCompoundTest.java
index ee9caac14..878de6e9c 100644
--- a/eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChResolveTest.java
+++ b/eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChCompoundTest.java
@@ -37,16 +37,16 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
/**
- * Test case for {@link ChResolve}.
+ * Test case for {@link ChCompound}.
* @since 0.28.14
*/
-final class ChResolveTest {
+final class ChCompoundTest {
@Test
@ExtendWith(OnlineCondition.class)
void getsCommitHashValueFromRemoteTag() {
MatcherAssert.assertThat(
- new ChResolve(
+ new ChCompound(
null,
null,
"0.26.0"
@@ -58,7 +58,7 @@ final class ChResolveTest {
@Test
void getsCommitHashValueFromPattern() {
MatcherAssert.assertThat(
- new ChResolve(
+ new ChCompound(
null,
"master:m23ss3h,3.1.*:abc2sd3",
"master"
@@ -72,7 +72,7 @@ final class ChResolveTest {
final Path file = temp.resolve("tags.txt");
new Home().save(new ResourceOf("org/eolang/maven/commits/tags.txt"), file);
MatcherAssert.assertThat(
- new ChResolve(
+ new ChCompound(
file,
null,
"master"
@@ -86,7 +86,7 @@ final class ChResolveTest {
void catchesAnExceptionWhenNoArguments() {
Assertions.assertThrows(
NullPointerException.class,
- () -> new ChResolve(null, null, null).value()
+ () -> new ChCompound(null, null, null).value()
);
}
| ['eo-maven-plugin/src/test/java/org/eolang/maven/hash/ChResolveTest.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/PullMojo.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/hash/ChResolve.java', 'eo-maven-plugin/src/main/java/org/eolang/maven/ProbeMojo.java', 'eo-maven-plugin/src/test/java/org/eolang/maven/PullMojoTest.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 659,496 | 144,681 | 20,981 | 194 | 358 | 76 | 8 | 3 | 637 | 66 | 204 | 10 | 3 | 0 | 1970-01-01T00:27:58 | 814 | Java | {'Java': 1396574, 'XSLT': 298556, 'TeX': 138771, 'Groovy': 16462, 'Rust': 5709, 'ANTLR': 3211, 'Makefile': 2212, 'Shell': 1454, 'Perl': 114} | MIT License |
8,804 | jreleaser/jreleaser/156/152 | jreleaser | jreleaser | https://github.com/jreleaser/jreleaser/issues/152 | https://github.com/jreleaser/jreleaser/pull/156 | https://github.com/jreleaser/jreleaser/pull/156 | 1 | fixes | [signing] ECDH keys not being recognized | This is an upstream issue. This issue only exists for upgrading as soon as upstream is fixed.
Follow-up to https://github.com/jreleaser/jreleaser/issues/136.
Of course I created a new key using Curve25519.
```
[INFO] Writing output properties to out/jreleaser/output.properties
[ERROR] JReleaser failed after 1.012 s
org.jreleaser.model.JReleaserException: Unexpected error when signing release.
at org.jreleaser.workflow.SignWorkflowItem.invoke(SignWorkflowItem.java:35)
at org.jreleaser.workflow.WorkflowImpl.execute(WorkflowImpl.java:51)
at org.jreleaser.cli.Sign.doExecute(Sign.java:34)
at org.jreleaser.cli.AbstractModelCommand.execute(AbstractModelCommand.java:64)
at org.jreleaser.cli.AbstractCommand.call(AbstractCommand.java:72)
at org.jreleaser.cli.AbstractModelCommand.call(AbstractModelCommand.java:38)
at org.jreleaser.cli.AbstractCommand.call(AbstractCommand.java:37)
at picocli.CommandLine.executeUserObject(CommandLine.java:1953)
at picocli.CommandLine.access$1300(CommandLine.java:145)
at picocli.CommandLine$RunLast.executeUserObjectOfLastSubcommandWithSameParent(CommandLine.java:2352)
at picocli.CommandLine$RunLast.handle(CommandLine.java:2346)
at picocli.CommandLine$RunLast.handle(CommandLine.java:2311)
at picocli.CommandLine$AbstractParseResultHandler.execute(CommandLine.java:2179)
at picocli.CommandLine.execute(CommandLine.java:2078)
at org.jreleaser.cli.Main.execute(Main.java:73)
at org.jreleaser.cli.Main.run(Main.java:59)
at org.jreleaser.cli.Main.main(Main.java:51)
Caused by: org.jreleaser.util.signing.SigningException: Unexpected error when initializing signature generator
at org.jreleaser.engine.sign.Signer.initSignatureGenerator(Signer.java:218)
at org.jreleaser.engine.sign.Signer.sign(Signer.java:194)
at org.jreleaser.engine.sign.Signer.sign(Signer.java:104)
at org.jreleaser.workflow.SignWorkflowItem.invoke(SignWorkflowItem.java:33)
... 16 more
Caused by: org.bouncycastle.openpgp.PGPException: unknown algorithm tag in signature:18
at org.bouncycastle.openpgp.operator.jcajce.OperatorHelper.createSignature(Unknown Source)
at org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder.build(Unknown Source)
at org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder.build(Unknown Source)
at org.bouncycastle.openpgp.PGPSignatureGenerator.init(Unknown Source)
at org.jreleaser.engine.sign.Signer.initSignatureGenerator(Signer.java:214)
... 19 more
```
### Task List
- [X] Steps to reproduce provided
- [X] Stacktrace (if present) provided
- [ ] Example that reproduces the problem (link to git repository is ideal)
- [X] Full description of the issue provided (see below)
### Steps to Reproduce
1. Create an ECDH key using GnuPG or similar
2. use in jreleaser
### Expected Behaviour
Key being used
### Actual Behaviour
Exception: https://github.com/bcgit/bc-java/blob/4a937ecd3ed3934fecb742063ea2fea6e7b9af8d/pg/src/main/java/org/bouncycastle/openpgp/operator/jcajce/OperatorHelper.java#L276
also
https://github.com/bcgit/bc-java/blob/4a937ecd3ed3934fecb742063ea2fea6e7b9af8d/pg/src/main/java/org/bouncycastle/bcpg/PublicKeyAlgorithmTags.java#L17
### Environment Information
- **Operating System**: Ubuntu 20.04
- **JReleaser Version:** 0.3.0 or 0.4.0-SNAPSHOT
- **JDK Version:** 11 OpenJ9
| b1583b5b647af649925cb575eca46fda87bfc83a | 902fc827809871000e7d4d4679a5e47148fe2adb | https://github.com/jreleaser/jreleaser/compare/b1583b5b647af649925cb575eca46fda87bfc83a...902fc827809871000e7d4d4679a5e47148fe2adb | diff --git a/core/jreleaser-utils/src/main/java/org/jreleaser/util/signing/Keyring.java b/core/jreleaser-utils/src/main/java/org/jreleaser/util/signing/Keyring.java
index adc5fa79..71e2a0be 100644
--- a/core/jreleaser-utils/src/main/java/org/jreleaser/util/signing/Keyring.java
+++ b/core/jreleaser-utils/src/main/java/org/jreleaser/util/signing/Keyring.java
@@ -17,6 +17,11 @@
*/
package org.jreleaser.util.signing;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collections;
+import java.util.Iterator;
+import org.bouncycastle.bcpg.PublicKeyAlgorithmTags;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
@@ -27,11 +32,6 @@ import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator;
import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collections;
-import java.util.Iterator;
-
/**
* Adapted from {@code name.neuhalfen.projects.crypto.bouncycastle.openpgp.keys.keyrings.InMemoryKeyring}
* Original author: Jens Neuhalfen
@@ -109,7 +109,7 @@ public abstract class Keyring {
Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys();
while (keyIter.hasNext()) {
PGPPublicKey key = keyIter.next();
- if (key.isEncryptionKey()) {
+ if (isSigningKey(key)) {
return key;
}
}
@@ -117,4 +117,25 @@ public abstract class Keyring {
throw new SigningException("Did not find public key for signing.");
}
+
+ /**
+ * Returns {@code true} if the given key can be used for signing.
+ *
+ * <p>There is no Method key.isSigningKey(), and encryption does not always mean signing.
+ * The algorithms here need to be kept in sync with {@code org.bouncycastle.openpgp.operator.jcajce.OperatorHelper#createSignature}.
+ *
+ * @param key they key to check if it is usable for signing.
+ * @return {@code true} if the given key can be used for signing.
+ */
+ private static boolean isSigningKey(PGPPublicKey key) {
+ final int algorithm = key.getAlgorithm();
+
+ return algorithm == PublicKeyAlgorithmTags.EDDSA ||
+ algorithm == PublicKeyAlgorithmTags.ECDSA ||
+ algorithm == PublicKeyAlgorithmTags.ELGAMAL_GENERAL ||
+ algorithm == PublicKeyAlgorithmTags.ELGAMAL_ENCRYPT ||
+ algorithm == PublicKeyAlgorithmTags.RSA_SIGN ||
+ algorithm == PublicKeyAlgorithmTags.RSA_GENERAL ||
+ algorithm == PublicKeyAlgorithmTags.DSA;
+ }
} | ['core/jreleaser-utils/src/main/java/org/jreleaser/util/signing/Keyring.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,474,594 | 313,556 | 45,965 | 469 | 1,409 | 293 | 33 | 1 | 3,759 | 216 | 923 | 73 | 3 | 1 | 1970-01-01T00:27:01 | 803 | Java | {'Java': 4664420, 'Groovy': 941002, 'Smarty': 176007, 'Shell': 50971, 'Tcl': 12113} | Apache License 2.0 |
816 | spring-cloud/spring-cloud-consul/230/229 | spring-cloud | spring-cloud-consul | https://github.com/spring-cloud/spring-cloud-consul/issues/229 | https://github.com/spring-cloud/spring-cloud-consul/pull/230 | https://github.com/spring-cloud/spring-cloud-consul/pull/230 | 1 | fix | Consul ConfigWatch not working for FILES config format | Watching Consul for config changes stopped working with release 1.1 in case of using FILES config format. I ran into this as part of upgrading to Spring Camden.RELEASE (that updates from spring-cloud-consul 1.0.2 to 1.1.0).
I did some debugging and think I know what the root cause is:
- ConfigWatch always a trailing slash to the context paths looked at in Consul
- This essentially means that ConfigWatch always looks at folders - this is conceptually incorrect 'FILES' mode - this actually is the problem root cause
- Watching this incorrect path always leads to a HTTP 404 from Consul (since the file is no folder but a leaf in the Consul tree)
- This still worked with Brixton / 1.0.2 by accident since 1.02 did not even look at the response code and only at the index returned by Consul
- Release 1.1 added code in ConfigWatch that looks at the Consul response value and ignores HTTP 404 responses (which is correct)
- Any changes to the config files are now skipped with Camden / 1.1.0 and do not lead to config change events
The fix would require to look at the configured config format `spring.cloud.consul.config.format` and avoid implicitly adding a trailing slash in case `FILES` is desired.
| ee007651e58fc2530b5f893c1477afb3d78c7d24 | 68b4459c3b7494252d47f596f5818777b22b7008 | https://github.com/spring-cloud/spring-cloud-consul/compare/ee007651e58fc2530b5f893c1477afb3d78c7d24...68b4459c3b7494252d47f596f5818777b22b7008 | diff --git a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConfigWatch.java b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConfigWatch.java
index d9622bfd..d7e174d3 100644
--- a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConfigWatch.java
+++ b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConfigWatch.java
@@ -36,6 +36,8 @@ import lombok.Data;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.util.ReflectionUtils;
+import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.FILES;
+
/**
* @author Spencer Gibb
*/
@@ -70,7 +72,9 @@ public class ConfigWatch implements Closeable, ApplicationEventPublisherAware {
public void watchConfigKeyValues() {
if (this.running.get()) {
for (String context : this.contexts) {
- if (!context.endsWith("/")) {
+
+ // turn the context into a Consul folder path (unless our config format are FILES)
+ if (properties.getFormat() != FILES && !context.endsWith("/")) {
context = context + "/";
}
diff --git a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConfigWatchTests.java b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConfigWatchTests.java
index 37d2f0b2..5c271bda 100644
--- a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConfigWatchTests.java
+++ b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConfigWatchTests.java
@@ -20,6 +20,7 @@ import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.kv.model.GetValue;
+import org.junit.Before;
import org.junit.Test;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.context.ApplicationEventPublisher;
@@ -34,17 +35,25 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.FILES;
/**
* @author Spencer Gibb
*/
public class ConfigWatchTests {
+ private ConsulConfigProperties configProperties;
+
+ @Before
+ public void setUp() throws Exception {
+ configProperties = new ConsulConfigProperties();
+ }
+
@Test
public void watchPublishesEvent() {
ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
- setupWatch(eventPublisher, new GetValue());
+ setupWatch(eventPublisher, new GetValue(), configProperties, "/app/");
verify(eventPublisher, times(1)).publishEvent(any(RefreshEvent.class));
}
@@ -53,12 +62,22 @@ public class ConfigWatchTests {
public void watchWithNullValueDoesNotPublishEvent() {
ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
- setupWatch(eventPublisher, null);
+ setupWatch(eventPublisher, null, configProperties, "/app/");
verify(eventPublisher, never()).publishEvent(any(RefreshEvent.class));
}
- private void setupWatch(ApplicationEventPublisher eventPublisher, GetValue getValue) {
+ @Test
+ public void watchForFileFormatPublishesEvent() {
+ ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
+
+ configProperties.setFormat(FILES);
+ setupWatch(eventPublisher, new GetValue(), configProperties, "/config/app.yml" );
+
+ verify(eventPublisher, times(1)).publishEvent(any(RefreshEvent.class));
+ }
+
+ private void setupWatch(ApplicationEventPublisher eventPublisher, GetValue getValue, ConsulConfigProperties configProperties, String context ) {
ConsulClient consul = mock(ConsulClient.class);
List<GetValue> getValues = null;
@@ -67,11 +86,11 @@ public class ConfigWatchTests {
}
Response<List<GetValue>> response = new Response<>(getValues, 1L, false, 1L);
- when(consul.getKVValues(eq("/app/"), any(QueryParams.class))).thenReturn(response);
+ when(consul.getKVValues(eq(context), any(QueryParams.class))).thenReturn(response);
- ConfigWatch watch = new ConfigWatch(new ConsulConfigProperties(), Arrays.asList("/app/"), consul);
+ ConfigWatch watch = new ConfigWatch(configProperties, Arrays.asList(context), consul);
watch.setApplicationEventPublisher(eventPublisher);
- watch.getConsulIndexes().put("/app/", 0L);
+ watch.getConsulIndexes().put(context, 0L);
watch.start();
watch.watchConfigKeyValues(); | ['spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConfigWatch.java', 'spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConfigWatchTests.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 110,780 | 23,740 | 3,551 | 41 | 288 | 59 | 6 | 1 | 1,207 | 209 | 282 | 12 | 0 | 0 | 1970-01-01T00:24:35 | 793 | Java | {'Java': 560522, 'CSS': 34264, 'HTML': 28643, 'Batchfile': 5822, 'Shell': 542} | Apache License 2.0 |
529 | opengamma/strata/1313/1312 | opengamma | strata | https://github.com/OpenGamma/Strata/issues/1312 | https://github.com/OpenGamma/Strata/pull/1313 | https://github.com/OpenGamma/Strata/pull/1313 | 1 | fixes | MultiCurrencyAmountArray.of(size, fn) doesn't work with empty MultiCurrencyAmounts | The following code produces a `MultiCurrencyAmountArray` of size zero even though it is created from two `MultiCurrencyAmounts`
```
MultiCurrencyAmountArray array = MultiCurrencyAmountArray.of(
MultiCurrencyAmount.empty(),
MultiCurrencyAmount.empty());
```
The following code always produces a `MultiCurrencyAmountArray` with a size of zero regardless of the requested size:
```
MultiCurrencyAmountArray.of(size, () -> MultiCurrencyAmount.empty());
```
The size of the array is derived from the size of the internal arrays holding the currency values. If there are no values a size of zero is incorrectly returned.
| e118c05ed7fb826ed8ce9cb019ce51297497e912 | e558988a726306271478b1539eb440ca71efb400 | https://github.com/opengamma/strata/compare/e118c05ed7fb826ed8ce9cb019ce51297497e912...e558988a726306271478b1539eb440ca71efb400 | diff --git a/modules/basics/src/main/java/com/opengamma/strata/basics/currency/MultiCurrencyAmountArray.java b/modules/basics/src/main/java/com/opengamma/strata/basics/currency/MultiCurrencyAmountArray.java
index c9ec298a4..129fd33a9 100644
--- a/modules/basics/src/main/java/com/opengamma/strata/basics/currency/MultiCurrencyAmountArray.java
+++ b/modules/basics/src/main/java/com/opengamma/strata/basics/currency/MultiCurrencyAmountArray.java
@@ -55,15 +55,17 @@ import com.opengamma.strata.collect.array.DoubleArray;
public final class MultiCurrencyAmountArray
implements FxConvertible<CurrencyAmountArray>, ImmutableBean, Serializable {
+ /**
+ * The size of this array.
+ */
+ @PropertyDefinition(validate = "notNegative")
+ private final int size;
+
/**
* The currency values, keyed by currency.
*/
@PropertyDefinition(validate = "notNull")
private final ImmutableSortedMap<Currency, DoubleArray> values;
- /**
- * The number of values for each currency.
- */
- private final int size; // derived
//-------------------------------------------------------------------------
/**
@@ -93,7 +95,7 @@ public final class MultiCurrencyAmountArray
}
}
Map<Currency, DoubleArray> doubleArrayMap = MapStream.of(valueMap).mapValues(v -> DoubleArray.ofUnsafe(v)).toMap();
- return new MultiCurrencyAmountArray(doubleArrayMap);
+ return new MultiCurrencyAmountArray(size, doubleArrayMap);
}
/**
@@ -115,21 +117,26 @@ public final class MultiCurrencyAmountArray
array[i] = ca.getAmount();
}
}
- return new MultiCurrencyAmountArray(MapStream.of(map).mapValues(array -> DoubleArray.ofUnsafe(array)).toMap());
+ return new MultiCurrencyAmountArray(size, MapStream.of(map).mapValues(array -> DoubleArray.ofUnsafe(array)).toMap());
}
/**
* Obtains an instance from a map of amounts.
* <p>
* Each currency is associated with an array of amounts.
- * All the arrays must have the same number of elements in each array.
+ * All the arrays must have the same number of elements.
+ * <p>
+ * If the map is empty the returned array will have a size of zero. To create an empty array
+ * with a non-zero size use one of the other {@code of} methods.
*
* @param values map of currencies to values
* @return an instance containing the values from the map
*/
public static MultiCurrencyAmountArray of(Map<Currency, DoubleArray> values) {
values.values().stream().reduce((a1, a2) -> checkSize(a1, a2));
- return new MultiCurrencyAmountArray(values);
+ // All of the values must have the same size so use the size of the first
+ int size = values.isEmpty() ? 0 : values.values().iterator().next().size();
+ return new MultiCurrencyAmountArray(size, values);
}
/**
@@ -152,14 +159,9 @@ public final class MultiCurrencyAmountArray
}
@ImmutableConstructor
- private MultiCurrencyAmountArray(Map<Currency, DoubleArray> values) {
+ private MultiCurrencyAmountArray(int size, Map<Currency, DoubleArray> values) {
this.values = ImmutableSortedMap.copyOf(values);
- if (values.isEmpty()) {
- size = 0;
- } else {
- // All currencies must have the same number of values so we can just take the size of the first
- size = values.values().iterator().next().size();
- }
+ this.size = size;
}
// validate when deserializing
@@ -405,6 +407,15 @@ public final class MultiCurrencyAmountArray
return metaBean().metaPropertyMap().keySet();
}
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the size of this array.
+ * @return the value of the property
+ */
+ public int getSize() {
+ return size;
+ }
+
//-----------------------------------------------------------------------
/**
* Gets the currency values, keyed by currency.
@@ -422,7 +433,8 @@ public final class MultiCurrencyAmountArray
}
if (obj != null && obj.getClass() == this.getClass()) {
MultiCurrencyAmountArray other = (MultiCurrencyAmountArray) obj;
- return JodaBeanUtils.equal(values, other.values);
+ return (size == other.size) &&
+ JodaBeanUtils.equal(values, other.values);
}
return false;
}
@@ -430,14 +442,16 @@ public final class MultiCurrencyAmountArray
@Override
public int hashCode() {
int hash = getClass().hashCode();
+ hash = hash * 31 + JodaBeanUtils.hashCode(size);
hash = hash * 31 + JodaBeanUtils.hashCode(values);
return hash;
}
@Override
public String toString() {
- StringBuilder buf = new StringBuilder(64);
+ StringBuilder buf = new StringBuilder(96);
buf.append("MultiCurrencyAmountArray{");
+ buf.append("size").append('=').append(size).append(',').append(' ');
buf.append("values").append('=').append(JodaBeanUtils.toString(values));
buf.append('}');
return buf.toString();
@@ -453,6 +467,11 @@ public final class MultiCurrencyAmountArray
*/
static final Meta INSTANCE = new Meta();
+ /**
+ * The meta-property for the {@code size} property.
+ */
+ private final MetaProperty<Integer> size = DirectMetaProperty.ofImmutable(
+ this, "size", MultiCurrencyAmountArray.class, Integer.TYPE);
/**
* The meta-property for the {@code values} property.
*/
@@ -464,6 +483,7 @@ public final class MultiCurrencyAmountArray
*/
private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
+ "size",
"values");
/**
@@ -475,6 +495,8 @@ public final class MultiCurrencyAmountArray
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
+ case 3530753: // size
+ return size;
case -823812830: // values
return values;
}
@@ -497,6 +519,14 @@ public final class MultiCurrencyAmountArray
}
//-----------------------------------------------------------------------
+ /**
+ * The meta-property for the {@code size} property.
+ * @return the meta-property, not null
+ */
+ public MetaProperty<Integer> size() {
+ return size;
+ }
+
/**
* The meta-property for the {@code values} property.
* @return the meta-property, not null
@@ -509,6 +539,8 @@ public final class MultiCurrencyAmountArray
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
+ case 3530753: // size
+ return ((MultiCurrencyAmountArray) bean).getSize();
case -823812830: // values
return ((MultiCurrencyAmountArray) bean).getValues();
}
@@ -532,6 +564,7 @@ public final class MultiCurrencyAmountArray
*/
private static final class Builder extends DirectFieldsBeanBuilder<MultiCurrencyAmountArray> {
+ private int size;
private SortedMap<Currency, DoubleArray> values = ImmutableSortedMap.of();
/**
@@ -544,6 +577,8 @@ public final class MultiCurrencyAmountArray
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
+ case 3530753: // size
+ return size;
case -823812830: // values
return values;
default:
@@ -555,6 +590,9 @@ public final class MultiCurrencyAmountArray
@Override
public Builder set(String propertyName, Object newValue) {
switch (propertyName.hashCode()) {
+ case 3530753: // size
+ this.size = (Integer) newValue;
+ break;
case -823812830: // values
this.values = (SortedMap<Currency, DoubleArray>) newValue;
break;
@@ -591,14 +629,16 @@ public final class MultiCurrencyAmountArray
@Override
public MultiCurrencyAmountArray build() {
return new MultiCurrencyAmountArray(
+ size,
values);
}
//-----------------------------------------------------------------------
@Override
public String toString() {
- StringBuilder buf = new StringBuilder(64);
+ StringBuilder buf = new StringBuilder(96);
buf.append("MultiCurrencyAmountArray.Builder{");
+ buf.append("size").append('=').append(JodaBeanUtils.toString(size)).append(',').append(' ');
buf.append("values").append('=').append(JodaBeanUtils.toString(values));
buf.append('}');
return buf.toString();
diff --git a/modules/basics/src/test/java/com/opengamma/strata/basics/currency/MultiCurrencyAmountArrayTest.java b/modules/basics/src/test/java/com/opengamma/strata/basics/currency/MultiCurrencyAmountArrayTest.java
index 790322d1f..f8764f6bc 100644
--- a/modules/basics/src/test/java/com/opengamma/strata/basics/currency/MultiCurrencyAmountArrayTest.java
+++ b/modules/basics/src/test/java/com/opengamma/strata/basics/currency/MultiCurrencyAmountArrayTest.java
@@ -75,6 +75,15 @@ public class MultiCurrencyAmountArrayTest {
assertThrowsIllegalArg(() -> raggedArray.getValues(Currency.AUD));
}
+ public void test_empty_amounts() {
+ MultiCurrencyAmountArray array = MultiCurrencyAmountArray.of(
+ MultiCurrencyAmount.empty(),
+ MultiCurrencyAmount.empty());
+ assertThat(array.size()).isEqualTo(2);
+ assertThat(array.get(0)).isEqualTo(MultiCurrencyAmount.empty());
+ assertThat(array.get(1)).isEqualTo(MultiCurrencyAmount.empty());
+ }
+
public void test_of_function() {
MultiCurrencyAmount mca1 = MultiCurrencyAmount.of(CurrencyAmount.of(Currency.GBP, 10), CurrencyAmount.of(Currency.USD, 20));
MultiCurrencyAmount mca2 = MultiCurrencyAmount.of(CurrencyAmount.of(Currency.GBP, 10), CurrencyAmount.of(Currency.EUR, 30));
@@ -87,14 +96,31 @@ public class MultiCurrencyAmountArrayTest {
assertThat(test.get(2)).isEqualTo(mca3.plus(Currency.GBP, 0).plus(Currency.EUR, 0));
}
+ public void test_of_function_empty_amounts() {
+ MultiCurrencyAmountArray test = MultiCurrencyAmountArray.of(3, i -> MultiCurrencyAmount.empty());
+ assertThat(test.size()).isEqualTo(3);
+ }
+
public void test_of_map() {
MultiCurrencyAmountArray array = MultiCurrencyAmountArray.of(
ImmutableMap.of(
Currency.GBP, DoubleArray.of(20, 21, 22),
- Currency.USD, DoubleArray.of(30, 32, 33),
Currency.EUR, DoubleArray.of(40, 43, 44)));
- assertThat(array).isEqualTo(VALUES_ARRAY);
+ MultiCurrencyAmountArray expected = MultiCurrencyAmountArray.of(
+ ImmutableList.of(
+ MultiCurrencyAmount.of(
+ CurrencyAmount.of(Currency.GBP, 20),
+ CurrencyAmount.of(Currency.EUR, 40)),
+ MultiCurrencyAmount.of(
+ CurrencyAmount.of(Currency.GBP, 21),
+ CurrencyAmount.of(Currency.EUR, 43)),
+ MultiCurrencyAmount.of(
+ CurrencyAmount.of(Currency.GBP, 22),
+ CurrencyAmount.of(Currency.EUR, 44))));
+
+ assertThat(array.size()).isEqualTo(3);
+ assertThat(array).isEqualTo(expected);
assertThrowsIllegalArg(
() -> MultiCurrencyAmountArray.of(
@@ -102,6 +128,9 @@ public class MultiCurrencyAmountArrayTest {
Currency.GBP, DoubleArray.of(20, 21),
Currency.EUR, DoubleArray.of(40, 43, 44))),
"Arrays must have the same size.*");
+
+ MultiCurrencyAmountArray empty = MultiCurrencyAmountArray.of(ImmutableMap.of());
+ assertThat(empty.size()).isEqualTo(0);
}
public void test_getValues() {
diff --git a/modules/data/src/test/java/com/opengamma/strata/data/scenario/MultiCurrencyScenarioArrayTest.java b/modules/data/src/test/java/com/opengamma/strata/data/scenario/MultiCurrencyScenarioArrayTest.java
index 79b2e1a5b..b0c108b0a 100644
--- a/modules/data/src/test/java/com/opengamma/strata/data/scenario/MultiCurrencyScenarioArrayTest.java
+++ b/modules/data/src/test/java/com/opengamma/strata/data/scenario/MultiCurrencyScenarioArrayTest.java
@@ -73,6 +73,15 @@ public class MultiCurrencyScenarioArrayTest {
assertThrowsIllegalArg(() -> raggedArray.getValues(Currency.AUD));
}
+ public void emptyAmounts() {
+ MultiCurrencyScenarioArray array = MultiCurrencyScenarioArray.of(
+ MultiCurrencyAmount.empty(),
+ MultiCurrencyAmount.empty());
+ assertThat(array.getScenarioCount()).isEqualTo(2);
+ assertThat(array.get(0)).isEqualTo(MultiCurrencyAmount.empty());
+ assertThat(array.get(1)).isEqualTo(MultiCurrencyAmount.empty());
+ }
+
public void createByFunction() {
MultiCurrencyAmount mca1 = MultiCurrencyAmount.of(CurrencyAmount.of(Currency.GBP, 10), CurrencyAmount.of(Currency.USD, 20));
MultiCurrencyAmount mca2 = MultiCurrencyAmount.of(CurrencyAmount.of(Currency.GBP, 10), CurrencyAmount.of(Currency.EUR, 30));
@@ -85,6 +94,11 @@ public class MultiCurrencyScenarioArrayTest {
assertThat(test.get(2)).isEqualTo(mca3.plus(Currency.GBP, 0).plus(Currency.EUR, 0));
}
+ public void createByFunctionEmptyAmounts() {
+ MultiCurrencyScenarioArray test = MultiCurrencyScenarioArray.of(3, i -> MultiCurrencyAmount.empty());
+ assertThat(test.getScenarioCount()).isEqualTo(3);
+ }
+
public void mapFactoryMethod() {
MultiCurrencyScenarioArray array = MultiCurrencyScenarioArray.of(
ImmutableMap.of( | ['modules/basics/src/main/java/com/opengamma/strata/basics/currency/MultiCurrencyAmountArray.java', 'modules/basics/src/test/java/com/opengamma/strata/basics/currency/MultiCurrencyAmountArrayTest.java', 'modules/data/src/test/java/com/opengamma/strata/data/scenario/MultiCurrencyScenarioArrayTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 14,048,268 | 3,191,096 | 400,885 | 1,526 | 3,124 | 702 | 76 | 1 | 627 | 78 | 128 | 16 | 0 | 2 | 1970-01-01T00:24:32 | 771 | Java | {'Java': 30371987} | Apache License 2.0 |
10,015 | jolokia/jolokia/233/150 | jolokia | jolokia | https://github.com/jolokia/jolokia/issues/150 | https://github.com/jolokia/jolokia/pull/233 | https://github.com/jolokia/jolokia/pull/233 | 1 | fixed | HistoryKey should empty pathes as null | The HistoryKey curently distinguishes between pathes which are empty ('') or null. Since they are semantically the same they should be treated the same.
| d375bf3903a467ac02d33a927d318b5090c8549b | d432b141315abd0bdcd119da56f41e07ddda3f23 | https://github.com/jolokia/jolokia/compare/d375bf3903a467ac02d33a927d318b5090c8549b...d432b141315abd0bdcd119da56f41e07ddda3f23 | diff --git a/agent/core/src/main/java/org/jolokia/history/HistoryKey.java b/agent/core/src/main/java/org/jolokia/history/HistoryKey.java
index be494b66..d35f4b8f 100644
--- a/agent/core/src/main/java/org/jolokia/history/HistoryKey.java
+++ b/agent/core/src/main/java/org/jolokia/history/HistoryKey.java
@@ -144,7 +144,7 @@ public class HistoryKey implements Serializable {
type = "attribute";
mBean = new ObjectName(pMBean);
secondary = pAttribute;
- path = pPath;
+ path = sanitize(pPath);
target = pTarget;
}
diff --git a/agent/core/src/main/java/org/jolokia/http/AgentServlet.java b/agent/core/src/main/java/org/jolokia/http/AgentServlet.java
index 0a1a28cf..d55658a9 100755
--- a/agent/core/src/main/java/org/jolokia/http/AgentServlet.java
+++ b/agent/core/src/main/java/org/jolokia/http/AgentServlet.java
@@ -328,15 +328,19 @@ public class AgentServlet extends HttpServlet {
// Lookup the Agent URL if needed
AgentDetails details = backendManager.getAgentDetails();
if (details.isInitRequired()) {
- if (details.isUrlMissing()) {
- String url = getBaseUrl(NetworkUtil.sanitizeLocalUrl(pReq.getRequestURL().toString()),
- extractServletPath(pReq));
- details.setUrl(url);
- }
- if (details.isSecuredMissing()) {
- details.setSecured(pReq.getAuthType() != null);
+ synchronized (details) {
+ if (details.isInitRequired()) {
+ if (details.isUrlMissing()) {
+ String url = getBaseUrl(NetworkUtil.sanitizeLocalUrl(pReq.getRequestURL().toString()),
+ extractServletPath(pReq));
+ details.setUrl(url);
+ }
+ if (details.isSecuredMissing()) {
+ details.setSecured(pReq.getAuthType() != null);
+ }
+ details.seal();
+ }
}
- details.seal();
}
}
| ['agent/core/src/main/java/org/jolokia/history/HistoryKey.java', 'agent/core/src/main/java/org/jolokia/http/AgentServlet.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 1,162,253 | 245,729 | 32,620 | 253 | 1,049 | 178 | 22 | 2 | 153 | 24 | 33 | 2 | 0 | 0 | 1970-01-01T00:24:09 | 767 | Java | {'Java': 2138039, 'JavaScript': 270770, 'XSLT': 35279, 'CSS': 28848, 'HTML': 9125, 'Shell': 7394} | Apache License 2.0 |
560 | yegor256/takes/466/445 | yegor256 | takes | https://github.com/yegor256/takes/issues/445 | https://github.com/yegor256/takes/pull/466 | https://github.com/yegor256/takes/pull/466#issuecomment-166032931 | 2 | fix | RqHref.Base reads first line of header without checking format | `org.takes.rq.RqHref.Base` just reads first header and takes second element after space splitting :
`this.head().iterator().next().split(" ", 3)[1]`
It should check if the header format satisfies HTTP specifications.
<hr id='w'>
- `445-5323c196`/#473 (by Vladimir Maximenko)
| d6d4c56cfca8c20bf2ab6a14f79d90bb29ad5d4d | 7394ad60d4b81fad9fa6c70f2f2bf1c5a8ef5189 | https://github.com/yegor256/takes/compare/d6d4c56cfca8c20bf2ab6a14f79d90bb29ad5d4d...7394ad60d4b81fad9fa6c70f2f2bf1c5a8ef5189 | diff --git a/src/main/java/org/takes/rq/RqHref.java b/src/main/java/org/takes/rq/RqHref.java
index 6a84fa107..f52b61321 100644
--- a/src/main/java/org/takes/rq/RqHref.java
+++ b/src/main/java/org/takes/rq/RqHref.java
@@ -27,6 +27,8 @@ import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.Iterator;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import lombok.EqualsAndHashCode;
import org.takes.HttpException;
import org.takes.Request;
@@ -60,6 +62,16 @@ public interface RqHref extends Request {
*/
@EqualsAndHashCode(callSuper = true)
final class Base extends RqWrap implements RqHref {
+
+ /**
+ * HTTP Request-Line pattern.
+ * @see <a href="http://www
+ * .w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1">RFC 2616</a>
+ */
+ private static final Pattern REQUEST_PATTERN = Pattern.compile(
+ "([!-~]+) ([^ ]+)( [^ ]+)?"
+ );
+
/**
* Ctor.
* @param req Original request
@@ -67,16 +79,36 @@ public interface RqHref extends Request {
public Base(final Request req) {
super(req);
}
+
+ // @todo #445:30min/DEV RqMethod already validates Request-Line and
+ // extracts HTTP Method from it. We should extract all important
+ // information from Request-Line (HTTP method, URI and HTTP version)
+ // in one place to enforce DRY principle.
@Override
public Href href() throws IOException {
+ if (!this.head().iterator().hasNext()) {
+ throw new HttpException(
+ HttpURLConnection.HTTP_BAD_REQUEST,
+ "HTTP Request should have Request-Line"
+ );
+ }
+ final String line = this.head().iterator().next();
+ final Matcher matcher =
+ REQUEST_PATTERN.matcher(line);
+ if (!matcher.matches()) {
+ throw new HttpException(
+ HttpURLConnection.HTTP_BAD_REQUEST,
+ String.format("Illegal Request-Line: %s", line)
+ );
+ }
+ final String uri = matcher.group(2);
return new Href(
String.format(
"http://%s%s",
new RqHeaders.Smart(
new RqHeaders.Base(this)
).single("host"),
- // @checkstyle MagicNumber (1 line)
- this.head().iterator().next().split(" ", 3)[1]
+ uri
)
);
}
diff --git a/src/test/java/org/takes/rq/RqHrefTest.java b/src/test/java/org/takes/rq/RqHrefTest.java
index 52c3787d2..ff2ab8b0b 100644
--- a/src/test/java/org/takes/rq/RqHrefTest.java
+++ b/src/test/java/org/takes/rq/RqHrefTest.java
@@ -25,9 +25,11 @@ package org.takes.rq;
import java.io.IOException;
import java.util.Arrays;
+import java.util.Collections;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
+import org.takes.HttpException;
/**
* Test case for {@link RqHref.Base}.
@@ -58,6 +60,36 @@ public final class RqHrefTest {
);
}
+ /**
+ * RqHref.Base should throw {@link HttpException} when parsing
+ * Request without Request-Line.
+ * @throws IOException If some problem inside
+ */
+ @Test(expected = HttpException.class)
+ public void failsOnAbsentRequestLine() throws IOException {
+ new RqHref.Base(
+ new RqSimple(Collections.<String>emptyList(), null)
+ ).href();
+ }
+
+ /**
+ * RqHref.Base should throw {@link HttpException} when parsing
+ * Request with illegal Request-Line.
+ * @throws IOException If some problem inside
+ */
+ @Test(expected = HttpException.class)
+ public void failsOnIllegalRequestLine() throws IOException {
+ new RqHref.Base(
+ new RqFake(
+ Arrays.asList(
+ "GIVE/contacts",
+ "Host: 2.example.com"
+ ),
+ ""
+ )
+ ).href();
+ }
+
/**
* RqHref.Base can extract params.
* @throws IOException If some problem inside | ['src/main/java/org/takes/rq/RqHref.java', 'src/test/java/org/takes/rq/RqHrefTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 722,034 | 160,560 | 22,520 | 214 | 1,499 | 300 | 36 | 1 | 276 | 33 | 74 | 7 | 0 | 0 | 1970-01-01T00:24:10 | 767 | Java | {'Java': 1584245, 'XSLT': 22893, 'HTML': 4294} | MIT License |
786 | authorjapps/zerocode/379/378 | authorjapps | zerocode | https://github.com/authorjapps/zerocode/issues/378 | https://github.com/authorjapps/zerocode/pull/379 | https://github.com/authorjapps/zerocode/pull/379#issuecomment-610539658 | 1 | resolves | Report to have the method details | AC1:
As a developer
I want to see the methods failed in my automated tests
So that I can see the granular details in my report
| e5ec83a6945e4eec163b3ce65bbea3094c5fda5d | 414dd1659d756135e9ca182c1085aacd40cc79fa | https://github.com/authorjapps/zerocode/compare/e5ec83a6945e4eec163b3ce65bbea3094c5fda5d...414dd1659d756135e9ca182c1085aacd40cc79fa | diff --git a/core/src/main/java/org/jsmart/zerocode/core/domain/builders/ZeroCodeCsvReportBuilder.java b/core/src/main/java/org/jsmart/zerocode/core/domain/builders/ZeroCodeCsvReportBuilder.java
index 4bb77e61..9346fa9c 100644
--- a/core/src/main/java/org/jsmart/zerocode/core/domain/builders/ZeroCodeCsvReportBuilder.java
+++ b/core/src/main/java/org/jsmart/zerocode/core/domain/builders/ZeroCodeCsvReportBuilder.java
@@ -9,6 +9,7 @@ public class ZeroCodeCsvReportBuilder {
private Integer stepLoop;
private String correlationId;
private String result;
+ private String method;
String requestTimeStamp;
String responseTimeStamp;
private Double responseDelayMilliSec;
@@ -19,7 +20,7 @@ public class ZeroCodeCsvReportBuilder {
public ZeroCodeCsvReport build() {
ZeroCodeCsvReport built = new ZeroCodeCsvReport(scenarioName,scenarioLoop,stepName, stepLoop,
- correlationId, result, requestTimeStamp, responseTimeStamp, responseDelayMilliSec);
+ correlationId, result, method, requestTimeStamp, responseTimeStamp, responseDelayMilliSec);
return built;
}
@@ -53,6 +54,11 @@ public class ZeroCodeCsvReportBuilder {
return this;
}
+ public ZeroCodeCsvReportBuilder method(String method) {
+ this.method = method;
+ return this;
+ }
+
public ZeroCodeCsvReportBuilder requestTimeStamp(String requestTimeStamp) {
this.requestTimeStamp = requestTimeStamp;
return this;
diff --git a/core/src/main/java/org/jsmart/zerocode/core/domain/builders/ZeroCodeReportStepBuilder.java b/core/src/main/java/org/jsmart/zerocode/core/domain/builders/ZeroCodeReportStepBuilder.java
index b8f83817..7a2a2f89 100644
--- a/core/src/main/java/org/jsmart/zerocode/core/domain/builders/ZeroCodeReportStepBuilder.java
+++ b/core/src/main/java/org/jsmart/zerocode/core/domain/builders/ZeroCodeReportStepBuilder.java
@@ -8,6 +8,7 @@ public class ZeroCodeReportStepBuilder {
Integer loop;
String name;
String url;
+ String method;
String correlationId;
String operation;
LocalDateTime requestTimeStamp;
@@ -26,7 +27,7 @@ public class ZeroCodeReportStepBuilder {
public ZeroCodeReportStep build() {
ZeroCodeReportStep built = new ZeroCodeReportStep(
- loop, name, url,
+ loop, name, url, method,
correlationId, operation, requestTimeStamp,
responseTimeStamp, responseDelay, result,
request, response, assertions, customLog);
@@ -48,6 +49,10 @@ public class ZeroCodeReportStepBuilder {
return this;
}
+ public ZeroCodeReportStepBuilder method(String method) {
+ this.method = method;
+ return this;
+ }
public ZeroCodeReportStepBuilder correlationId(String correlationId) {
this.correlationId = correlationId;
return this;
diff --git a/core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportStep.java b/core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportStep.java
index de7749c4..ddfb08fd 100644
--- a/core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportStep.java
+++ b/core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportStep.java
@@ -13,6 +13,7 @@ public class ZeroCodeReportStep {
private final Integer loop;
private final String name;
private final String url;
+ private final String method;
private final String correlationId;
private final String operation;
@JsonSerialize(using = LocalDateTimeSerializer.class)
@@ -33,6 +34,7 @@ public class ZeroCodeReportStep {
@JsonProperty("stepLoop") Integer loop,
@JsonProperty("name") String name,
@JsonProperty("url") String url,
+ @JsonProperty("method") String method,
@JsonProperty("correlationId") String correlationId,
@JsonProperty("operation") String operation,
@JsonProperty("requestTimeStamp") LocalDateTime requestTimeStamp,
@@ -46,6 +48,7 @@ public class ZeroCodeReportStep {
this.loop = loop;
this.name = name;
this.url = url;
+ this.method=method;
this.correlationId = correlationId;
this.operation = operation;
this.requestTimeStamp = requestTimeStamp;
@@ -70,6 +73,10 @@ public class ZeroCodeReportStep {
return url;
}
+ public String getMethod() {
+ return method;
+ }
+
public String getCorrelationId() {
return correlationId;
}
@@ -114,6 +121,7 @@ public class ZeroCodeReportStep {
"loop=" + loop +
", name='" + name + '\\'' +
", url='" + url + '\\'' +
+ ", method='" + method + '\\'' +
", correlationId='" + correlationId + '\\'' +
", operation='" + operation + '\\'' +
", requestTimeStamp=" + requestTimeStamp +
diff --git a/core/src/main/java/org/jsmart/zerocode/core/domain/reports/csv/ZeroCodeCsvReport.java b/core/src/main/java/org/jsmart/zerocode/core/domain/reports/csv/ZeroCodeCsvReport.java
index eca84061..9d694164 100644
--- a/core/src/main/java/org/jsmart/zerocode/core/domain/reports/csv/ZeroCodeCsvReport.java
+++ b/core/src/main/java/org/jsmart/zerocode/core/domain/reports/csv/ZeroCodeCsvReport.java
@@ -7,12 +7,13 @@ public class ZeroCodeCsvReport {
private Integer stepLoop;
private String correlationId;
private String result;
+ private String method;
String requestTimeStamp;
String responseTimeStamp;
private Double responseDelayMilliSec;
public ZeroCodeCsvReport(String scenarioName, Integer scenarioLoop, String stepName, Integer stepLoop,
- String correlationId, String result, String requestTimeStamp,
+ String correlationId, String result, String method, String requestTimeStamp,
String responseTimeStamp, Double responseDelayMilliSec) {
this.scenarioName = scenarioName;
this.scenarioLoop = scenarioLoop;
@@ -20,6 +21,7 @@ public class ZeroCodeCsvReport {
this.stepLoop = stepLoop;
this.correlationId = correlationId;
this.result = result;
+ this.method=method;
this.requestTimeStamp = requestTimeStamp;
this.responseTimeStamp = responseTimeStamp;
this.responseDelayMilliSec = responseDelayMilliSec;
@@ -49,6 +51,10 @@ public class ZeroCodeCsvReport {
return result;
}
+ public String getMethod() {
+ return method;
+ }
+
public Double getResponseDelayMilliSec() {
return responseDelayMilliSec;
}
@@ -70,6 +76,7 @@ public class ZeroCodeCsvReport {
", stepLoop=" + stepLoop +
", correlationId='" + correlationId + '\\'' +
", result='" + result + '\\'' +
+ ", method='" + method + '\\'' +
", requestTimeStamp=" + requestTimeStamp +
", responseTimeStamp=" + responseTimeStamp +
", responseDelayMilliSec=" + responseDelayMilliSec +
diff --git a/core/src/main/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImpl.java b/core/src/main/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImpl.java
index 8b774f52..dc3e6cc9 100644
--- a/core/src/main/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImpl.java
+++ b/core/src/main/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImpl.java
@@ -254,6 +254,7 @@ public class ZeroCodeReportGeneratorImpl implements ZeroCodeReportGenerator {
.addColumn("responseDelayMilliSec", CsvSchema.ColumnType.NUMBER)
.addColumn("responseTimeStamp")
.addColumn("result")
+ .addColumn("method")
.build();
CsvMapper csvMapper = new CsvMapper();
@@ -293,6 +294,7 @@ public class ZeroCodeReportGeneratorImpl implements ZeroCodeReportGenerator {
csvFileBuilder.stepName(thisStep.getName());
csvFileBuilder.correlationId(thisStep.getCorrelationId());
csvFileBuilder.result(thisStep.getResult());
+ csvFileBuilder.method(thisStep.getOperation());
csvFileBuilder.requestTimeStamp(thisStep.getRequestTimeStamp().toString());
csvFileBuilder.responseTimeStamp(thisStep.getResponseTimeStamp().toString());
csvFileBuilder.responseDelayMilliSec(thisStep.getResponseDelay());
diff --git a/core/src/test/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportTest.java b/core/src/test/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportTest.java
index 77c31a98..3eed9c75 100644
--- a/core/src/test/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportTest.java
+++ b/core/src/test/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportTest.java
@@ -41,7 +41,7 @@ public class ZeroCodeReportTest {
.loop(3)
.correlationId("correlation Id")
.name("step_create")
- .operation("POST-POST")
+ .method("POST-POST")
.url("/home/googly")
.result("PASS")
.build()))
@@ -53,6 +53,7 @@ public class ZeroCodeReportTest {
assertThat(jsonNode.get("timeStamp"), is(notNullValue()));
assertThat(jsonNode.get("results").get(0).get("loop").asInt(), is(1));
assertThat(jsonNode.get("results").get(0).get("steps").get(0).get("loop").asInt(), is(3));
+ assertThat(jsonNode.get("results").get(0).get("steps").get(0).get("method").asText(), is("POST-POST"));
}
@Test | ['core/src/main/java/org/jsmart/zerocode/core/domain/builders/ZeroCodeCsvReportBuilder.java', 'core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportStep.java', 'core/src/main/java/org/jsmart/zerocode/core/domain/reports/csv/ZeroCodeCsvReport.java', 'core/src/main/java/org/jsmart/zerocode/core/domain/builders/ZeroCodeReportStepBuilder.java', 'core/src/main/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImpl.java', 'core/src/test/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportTest.java'] | {'.java': 6} | 6 | 6 | 0 | 0 | 6 | 451,351 | 88,040 | 12,608 | 187 | 1,284 | 230 | 34 | 5 | 133 | 26 | 32 | 6 | 0 | 0 | 1970-01-01T00:26:26 | 763 | Java | {'Java': 950563, 'Shell': 268, 'Dockerfile': 225} | Apache License 2.0 |
787 | authorjapps/zerocode/390/389 | authorjapps | zerocode | https://github.com/authorjapps/zerocode/issues/389 | https://github.com/authorjapps/zerocode/pull/390 | https://github.com/authorjapps/zerocode/pull/390#issuecomment-626149062 | 1 | solves | Retry report showing wrong scenario status if finally the step has passed | From Slack:
Cyril EDME:
Hi,
i would like some feedback on a use case before post any ticket.
Did someone created a scenario with a first step that trigger an asynchrone treatment then assert it with a second step (sync, by REST API using the retry policy) ?
In the end it works, my second step first attempt fail but the second succeed, perfect. But in the report it's recorded as fail (even if the test is green), which is incorrect. The detail of the steps with the first attempt in fail status is correct tho.
***
But in the report it's recorded as fail (even if the test is green), which is incorrect.
@ Cyril EDME, the issue you are facing is the report issue when retry mechanism is used?
e.g.
```
"retry":{
"max": 5
"delay": 500
}
```
Even if let's say first 4 retries failed and 5th one passed, the test goes green(expected), but report shows FAILED (unexpected)?
Is the report missing the 5th entry which has PASSED ?
Can you paste here a result of just one test-scenario run's
Console log : with all retry entries
CSV report : what it has captured
HTML file
Just for 1 test-scenario please which will be simple to analyze and less noisy!
***
The reporting code is below which marks the Scenario as failed if it has at least 1 step failure.
> org.jsmart.zerocode.core.report.ZeroCodeReportGeneratorImpl#generateExtentReport
This behaviour is correct in a normal usecase, but not for a retry-step usecase.
Possible fix:
- Check if one of the retries has passed, then only mark the scenario as PASSED.
- Basically if one of the retries succeeds, then it doesn't retry any more. e.g. if max retry is 5, and the 3rd once succeeds, then it comes out from that step(does not retry for 4th and 5th time) and continues for the next step.
- Then see if the Extent report is correctly rendering this i.e. marking the Scenario as PASSED
[Download and unzip this - retry html and csv report.zip](https://github.com/authorjapps/zerocode/files/4585271/retry.html.and.csv.report.zip)
AC1:
===
Mark the scenario as `Pass`(Green) if any of the retries succeeds for the retry-step(s) and all other steps in this scenario have passed.
AC2:
===
Remove the `redundant failed retry steps` from extent-report view. This will leave with the final outcome of the step(wither Passed or Failed) with just the 1 entry which is the correct for the HTML report view.
In case the test-engineers need to see the failed retry steps, then they can look at the logs in the `target` folder.
AC3:
===
If AC2 solution is implemented, then remove the `redundant failed retry steps` from CSV records to make both consistent with each other.
AC4(Tech-Debt):
=============
Create a tech-debt ticket to raise an issue with `Extent Project` to allow overriding the final scenario status(green or Pass in this case) even if the scenario has a failed step. This seems like not possible currently.
First check in the `Extent Slack channel` prior to raise as issue.
| 8212e722d6eb33e1cfc6a9e4516fa7caee990cfe | 6c62c654d8e59ffb98e4cdef43f809f31f579f45 | https://github.com/authorjapps/zerocode/compare/8212e722d6eb33e1cfc6a9e4516fa7caee990cfe...6c62c654d8e59ffb98e4cdef43f809f31f579f45 | diff --git a/core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeExecResult.java b/core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeExecResult.java
index faab8c7d..ae17016b 100644
--- a/core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeExecResult.java
+++ b/core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeExecResult.java
@@ -35,6 +35,10 @@ public class ZeroCodeExecResult {
return steps;
}
+ public void setSteps(List<ZeroCodeReportStep> steps) {
+ this.steps = steps;
+ }
+
@Override
public String toString() {
return "ZeroCodeExecResult{" +
diff --git a/core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportStep.java b/core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportStep.java
index ddfb08fd..07d6c6f2 100644
--- a/core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportStep.java
+++ b/core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportStep.java
@@ -61,6 +61,12 @@ public class ZeroCodeReportStep {
this.customLog = customLog;
}
+
+ public ZeroCodeReportStep(String correlationId,String result){
+ this(null,null,null,null,correlationId,null,null,null,null,result,null,null,null,null);
+ }
+
+
public Integer getLoop() {
return loop;
}
diff --git a/core/src/main/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImpl.java b/core/src/main/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImpl.java
index dc3e6cc9..bd5b6668 100644
--- a/core/src/main/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImpl.java
+++ b/core/src/main/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImpl.java
@@ -18,7 +18,9 @@ import org.jsmart.zerocode.core.domain.builders.HighChartColumnHtmlBuilder;
import org.jsmart.zerocode.core.domain.builders.ZeroCodeChartKeyValueArrayBuilder;
import org.jsmart.zerocode.core.domain.builders.ZeroCodeChartKeyValueBuilder;
import org.jsmart.zerocode.core.domain.builders.ZeroCodeCsvReportBuilder;
+import org.jsmart.zerocode.core.domain.reports.ZeroCodeExecResult;
import org.jsmart.zerocode.core.domain.reports.ZeroCodeReport;
+import org.jsmart.zerocode.core.domain.reports.ZeroCodeReportStep;
import org.jsmart.zerocode.core.domain.reports.chart.HighChartColumnHtml;
import org.jsmart.zerocode.core.domain.reports.csv.ZeroCodeCsvReport;
import org.slf4j.Logger;
@@ -28,10 +30,7 @@ import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
+import java.util.*;
import java.util.stream.Collectors;
import static java.util.Collections.emptyList;
@@ -82,10 +81,26 @@ public class ZeroCodeReportGeneratorImpl implements ZeroCodeReportGenerator {
this.mapper = mapper;
}
+ /**
+ * Gets unique steps from a scenario. In case of retries, the steps have same correlation id and if
+ * one of the retries is successful, we include it in the result(not the one which failed).
+ * In a normal case(without retry), both PASS and FAIL will be included as usual.
+ * @param steps
+ * @return
+ */
+ List<ZeroCodeReportStep> getUniqueSteps(List<ZeroCodeReportStep> steps){
+ Map<String,ZeroCodeReportStep> result = new HashMap<>();
+ steps.forEach(step->{
+ result.merge(step.getCorrelationId(), step,
+ (s1, s2) -> RESULT_PASS.equals(s1.getResult()) ? s1 : s2);
+ });
+ return new ArrayList<>(result.values());
+ }
+
@Override
public void generateExtentReport() {
- if(interactiveHtmlReportDisabled){
+ if (interactiveHtmlReportDisabled) {
return;
}
@@ -100,22 +115,22 @@ public class ZeroCodeReportGeneratorImpl implements ZeroCodeReportGenerator {
test.assignCategory(DEFAULT_REGRESSION_CATEGORY);
test.assignAuthor(optionalAuthor(thisScenario.getScenarioName()));
-
- thisScenario.getSteps().forEach(thisStep -> {
+ List<ZeroCodeReportStep> thisScenarioUniqueSteps = getUniqueSteps(thisScenario.getSteps());
+ thisScenarioUniqueSteps.forEach(thisStep -> {
test.getModel().setStartTime(utilDateOf(thisStep.getRequestTimeStamp()));
test.getModel().setEndTime(utilDateOf(thisStep.getResponseTimeStamp()));
final Status testStatus = thisStep.getResult().equals(RESULT_PASS) ? Status.PASS : Status.FAIL;
-
+
ExtentTest step = test.createNode(thisStep.getName(), TEST_STEP_CORRELATION_ID + " " + thisStep.getCorrelationId());
-
- if(testStatus.equals(Status.PASS)) {
- step.pass(thisStep.getResult());
- }else {
- step.info(MarkupHelper.createCodeBlock(thisStep.getOperation() + "\\t" + thisStep.getUrl()));
- step.info(MarkupHelper.createCodeBlock(thisStep.getRequest(), CodeLanguage.JSON));
+
+ if (testStatus.equals(Status.PASS)) {
+ step.pass(thisStep.getResult());
+ } else {
+ step.info(MarkupHelper.createCodeBlock(thisStep.getOperation() + "\\t" + thisStep.getUrl()));
+ step.info(MarkupHelper.createCodeBlock(thisStep.getRequest(), CodeLanguage.JSON));
step.info(MarkupHelper.createCodeBlock(thisStep.getResponse(), CodeLanguage.JSON));
- step.fail(MarkupHelper.createCodeBlock("Reason:\\n" + thisStep.getAssertions()));
+ step.fail(MarkupHelper.createCodeBlock("Reason:\\n" + thisStep.getAssertions()));
}
extentReports.flush();
});
@@ -133,13 +148,13 @@ public class ZeroCodeReportGeneratorImpl implements ZeroCodeReportGenerator {
// (might be disabled by current runner)
// Then it's good to link it to that spike report.
// ------------------------------------------------
- if(spikeChartReportEnabled || spikeChartFileName != null){
+ if (spikeChartReportEnabled || spikeChartFileName != null) {
final String reportName = getReportName();
String linkCodeToTargetSpikeChartHtml =
String.format("<code> <a href='%s' style=\\"color: #006; background: #ff6;\\"> %s </a></code>",
- spikeChartFileName,
- LINK_LABEL_NAME);
+ spikeChartFileName,
+ LINK_LABEL_NAME);
ExtentReportsFactory.reportName(reportName + linkCodeToTargetSpikeChartHtml);
}
@@ -148,33 +163,33 @@ public class ZeroCodeReportGeneratorImpl implements ZeroCodeReportGenerator {
protected String optionalAuthor(String scenarioName) {
String authorName = substringBetween(scenarioName, AUTHOR_MARKER, AUTHOR_MARKER);
- if(authorName == null){
+ if (authorName == null) {
authorName = substringBetween(scenarioName, AUTHOR_MARKER, ",");
}
- if(authorName == null){
+ if (authorName == null) {
authorName = substringBetween(scenarioName, AUTHOR_MARKER, " ");
}
- if(authorName == null){
+ if (authorName == null) {
authorName = scenarioName.substring(scenarioName.lastIndexOf(AUTHOR_MARKER) + AUTHOR_MARKER.length());
}
- if(scenarioName.lastIndexOf(AUTHOR_MARKER) == -1 || StringUtils.isEmpty(authorName)){
+ if (scenarioName.lastIndexOf(AUTHOR_MARKER) == -1 || StringUtils.isEmpty(authorName)) {
authorName = ANONYMOUS_AUTHOR;
}
return authorName;
}
-
+
protected String onlyScenarioName(String scenarioName) {
-
- int index = scenarioName.indexOf(AUTHOR_MARKER);
- if(index == -1) {
- return scenarioName;
- }else {
- return scenarioName.substring(0, index -1);
- }
+
+ int index = scenarioName.indexOf(AUTHOR_MARKER);
+ if (index == -1) {
+ return scenarioName;
+ } else {
+ return scenarioName.substring(0, index - 1);
+ }
}
@Override
@@ -198,7 +213,7 @@ public class ZeroCodeReportGeneratorImpl implements ZeroCodeReportGenerator {
/*
* Generate: Spike Chart using HighChart
*/
- if(spikeChartReportEnabled){
+ if (spikeChartReportEnabled) {
HighChartColumnHtml highChartColumnHtml = convertCsvRowsToHighChartData(zeroCodeCsvFlattenedRows);
generateHighChartReport(highChartColumnHtml);
}
@@ -331,7 +346,11 @@ public class ZeroCodeReportGeneratorImpl implements ZeroCodeReportGenerator {
}
})
.collect(Collectors.toList());
-
+ for (ZeroCodeReport zeroCodeReport : scenarioReports) {
+ for (ZeroCodeExecResult zeroCodeExecResult : zeroCodeReport.getResults()) {
+ zeroCodeExecResult.setSteps(getUniqueSteps(zeroCodeExecResult.getSteps()));
+ }
+ }
return scenarioReports;
}
@@ -342,7 +361,7 @@ public class ZeroCodeReportGeneratorImpl implements ZeroCodeReportGenerator {
return name.endsWith(".json");
});
- if(files == null || files.length == 0){
+ if (files == null || files.length == 0) {
LOGGER.error("\\n\\t\\t\\t************\\nNow files were found in folder:{}, hence could not proceed. " +
"\\n(If this was intentional, then you can safely ignore this error)" +
diff --git a/core/src/test/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImplTest.java b/core/src/test/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImplTest.java
index b05c464f..469272bc 100644
--- a/core/src/test/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImplTest.java
+++ b/core/src/test/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImplTest.java
@@ -2,14 +2,21 @@ package org.jsmart.zerocode.core.report;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsmart.zerocode.core.di.provider.ObjectMapperProvider;
+import org.jsmart.zerocode.core.domain.reports.ZeroCodeReportStep;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
+import java.util.ArrayList;
+import java.util.List;
+
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
+import static org.jsmart.zerocode.core.constants.ZeroCodeReportConstants.RESULT_FAIL;
+import static org.jsmart.zerocode.core.constants.ZeroCodeReportConstants.RESULT_PASS;
+import static org.junit.Assert.assertEquals;
public class ZeroCodeReportGeneratorImplTest {
@@ -76,4 +83,38 @@ public class ZeroCodeReportGeneratorImplTest {
}
+ @Test
+ public void testGettingUniqueStepsForMultipleRetries(){
+ List<ZeroCodeReportStep> steps = new ArrayList<ZeroCodeReportStep>(){
+ {
+ add(new ZeroCodeReportStep("testCorrelationId",RESULT_PASS));
+ add(new ZeroCodeReportStep("testCorrelationId",RESULT_FAIL));
+ }
+ };
+ List<ZeroCodeReportStep> uniqueSteps = zeroCodeReportGenerator.getUniqueSteps(steps);
+ assertEquals(uniqueSteps.size() , 1);
+ assertEquals(uniqueSteps.get(0).getResult(),RESULT_PASS);
+ }
+
+ @Test
+ public void testGettingUniqueStepsForNoRetries(){
+ List<ZeroCodeReportStep> steps = new ArrayList<ZeroCodeReportStep>(){
+ {
+ add(new ZeroCodeReportStep("testCorrelationId1",RESULT_PASS));
+ add(new ZeroCodeReportStep("testCorrelationId2",RESULT_FAIL));
+ add(new ZeroCodeReportStep("testCorrelationId3",RESULT_FAIL));
+ }
+ };
+ List<ZeroCodeReportStep> uniqueSteps = zeroCodeReportGenerator.getUniqueSteps(steps);
+ assertEquals(uniqueSteps.size() , 3);
+ assertEquals(uniqueSteps.stream().filter(step->step.getResult().equals(RESULT_PASS)).count(),1);
+ assertEquals(uniqueSteps.stream().filter(step->step.getResult().equals(RESULT_FAIL)).count(),2);
+
+ assertThat(uniqueSteps.get(0).getCorrelationId(),is("testCorrelationId3")); // order different to original
+ assertThat(uniqueSteps.get(1).getCorrelationId(),is("testCorrelationId1")); // order different to original
+ assertThat(uniqueSteps.get(2).getCorrelationId(),is("testCorrelationId2")); // order different to original
+
+ // order different to original: Not really an issue, as the CSV can be sorted ACS or DESC by a an external tool
+ }
+
}
\\ No newline at end of file | ['core/src/main/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImpl.java', 'core/src/test/java/org/jsmart/zerocode/core/report/ZeroCodeReportGeneratorImplTest.java', 'core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeReportStep.java', 'core/src/main/java/org/jsmart/zerocode/core/domain/reports/ZeroCodeExecResult.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 453,904 | 88,491 | 12,692 | 189 | 4,132 | 846 | 95 | 3 | 3,016 | 499 | 716 | 63 | 1 | 1 | 1970-01-01T00:26:28 | 763 | Java | {'Java': 950563, 'Shell': 268, 'Dockerfile': 225} | Apache License 2.0 |
1,449 | stargate/stargate/2018/205 | stargate | stargate | https://github.com/stargate/stargate/issues/205 | https://github.com/stargate/stargate/pull/2018 | https://github.com/stargate/stargate/pull/2018 | 1 | fixes | GET by primary key with frozen<udt> using REST V1 is returning 500 error | There are two issues here:
1. seems that having frozen<some udt> is causing 500
2. after removing problematic column 500 became 400 without error in stargate.log
```
http 'http://10.101.37.135:8082/v1/keyspaces/ks1/tables/table4/rows/8275984804989873180;5276317386634354038;28639;1005107841;1544552259' x-cassandra-token:$TOKEN
HTTP/1.1 500 Internal Server Error
Content-Length: 55
Content-Type: application/json
Date: Tue, 06 Oct 2020 11:59:06 GMT
{
"code": 500,
"description": "Server error: Unknown type"
}
```
Schema for ks1.table4:
```
CREATE TABLE ks1.table4 (
pk0 varint,
pk1 varint,
pk2 smallint,
pk3 int,
pk4 int,
ck0 smallint,
ck1 text,
col0 frozen<udt_167785279>,
col1 date,
col10 map<tinyint, double>,
col11 float,
col2 timestamp,
col3 timeuuid,
col4 bigint,
col5 ascii,
col6 map<tinyint, varint>,
col7 float,
col8 duration,
col9 map<ascii, decimal>,
PRIMARY KEY ((pk0, pk1, pk2, pk3, pk4), ck0, ck1)
```
in the Stargate logs:
```
10.151.0.16 - - [06/Oct/2020:11:59:06 +0000] "GET /v1/keyspaces/ks1/tables/table4/rows/8275984804989873180;5276317386634354038;28639;1005107841;1544552259 HTTP/1.1" 500 55 "-" "HTTPie/0.9.2" 15
ERROR [2020-10-06 11:59:06,152] io.stargate.web.resources.RequestHandler: Error when executing request
! java.lang.UnsupportedOperationException: Unknown type
! at io.stargate.db.datastore.Row.getValue(Row.java:272)
! at io.stargate.db.datastore.Row.getValue(Row.java:203)
! at io.stargate.web.resources.Converters.row2Map(Converters.java:75)
! at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
! at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1384)
! at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
! at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
! at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
! at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
! at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:566)
! at io.stargate.web.resources.RowResource.lambda$getOne$0(RowResource.java:100)
! at io.stargate.web.resources.RequestHandler.handle(RequestHandler.java:37)
! at io.stargate.web.resources.RowResource.getOne(RowResource.java:85)
! at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
! at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
! at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
! at java.lang.reflect.Method.invoke(Method.java:498)
! at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:52)
! at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:124)
! at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:167)
! at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:176)
! at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:79)
! at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:469)
! at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:391)
! at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:80)
! at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:253)
! at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248)
! at org.glassfish.jersey.internal.Errors$1.call(Errors.java:244)
! at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
! at org.glassfish.jersey.internal.Errors.process(Errors.java:274)
! at org.glassfish.jersey.internal.Errors.process(Errors.java:244)
! at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:265)
! at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:232)
! at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:680)
! at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:394)
! at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:346)
! at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:366)
! at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:319)
! at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:205)
! at io.dropwizard.jetty.NonblockingServletHolder.handle(NonblockingServletHolder.java:50)
! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1617)
! at io.dropwizard.servlets.ThreadNameFilter.doFilter(ThreadNameFilter.java:35)
! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1604)
! at io.dropwizard.jersey.filter.AllowedMethodsFilter.handle(AllowedMethodsFilter.java:47)
! at io.dropwizard.jersey.filter.AllowedMethodsFilter.doFilter(AllowedMethodsFilter.java:41)
! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1604)
! at org.eclipse.jetty.servlets.CrossOriginFilter.handle(CrossOriginFilter.java:319)
! at org.eclipse.jetty.servlets.CrossOriginFilter.doFilter(CrossOriginFilter.java:273)
! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1604)
! at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:545)
! at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:233)
! at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1297)
! at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:188)
! at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:485)
! at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:186)
! at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1212)
! at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
! at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
! at com.codahale.metrics.jetty9.InstrumentedHandler.handle(InstrumentedHandler.java:249)
! at io.dropwizard.jetty.RoutingHandler.handle(RoutingHandler.java:52)
! at org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:767)
! at org.eclipse.jetty.server.handler.RequestLogHandler.handle(RequestLogHandler.java:54)
! at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:173)
! at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
! at org.eclipse.jetty.server.Server.handle(Server.java:500)
! at org.eclipse.jetty.server.HttpChannel.lambda$handle$1(HttpChannel.java:383)
! at org.eclipse.jetty.server.HttpChannel.dispatch(HttpChannel.java:547)
! at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:375)
! at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:270)
! at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:311)
! at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)
! at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:117)
! at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:336)
! at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:313)
! at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:171)
! at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:129)
! at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:388)
! at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:806)
! at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:938)
! at java.lang.Thread.run(Thread.java:748)
```
To check which column is causing issues I have removed `col0`.
And here comes a surprise - I started to get 400 after this removal:
```
http 'http://10.101.37.135:8082/v1/keyspaces/ks1/tables/table4/rows/8275984804989873180;5276317386634354038;28639;1005107841;1544552259' x-cassandra-token:$TOKEN
HTTP/1.1 400 Bad Request
Content-Length: 47
Content-Type: application/json
Date: Tue, 06 Oct 2020 12:01:19 GMT
{
"code": 400,
"message": "Unable to process JSON"
}
```
| 55f5778ad231bc2f09ae56d208aea55d25f8a598 | c76c618c2de4e030755ac20061b4ef3db717245a | https://github.com/stargate/stargate/compare/55f5778ad231bc2f09ae56d208aea55d25f8a598...c76c618c2de4e030755ac20061b4ef3db717245a | diff --git a/restapi/src/main/java/io/stargate/web/resources/Converters.java b/restapi/src/main/java/io/stargate/web/resources/Converters.java
index 37e5d29a..2f21cb43 100644
--- a/restapi/src/main/java/io/stargate/web/resources/Converters.java
+++ b/restapi/src/main/java/io/stargate/web/resources/Converters.java
@@ -115,6 +115,20 @@ public class Converters {
if (value instanceof Object[]) {
value = Arrays.asList((Object[]) value);
}
+ if (value instanceof UdtValue) {
+ UdtValue udtValue = (UdtValue) value;
+ com.datastax.oss.driver.api.core.type.UserDefinedType udtType = udtValue.getType();
+ Map<String, Object> jsonObject = Maps.newLinkedHashMapWithExpectedSize(udtValue.size());
+ for (int i = 0; i < udtValue.size(); i++) {
+ CqlIdentifier fieldName = udtType.getFieldNames().get(i);
+ Object internalValue = udtValue.getObject(fieldName);
+ if (internalValue instanceof Object[]) {
+ internalValue = Arrays.asList((Object[]) internalValue);
+ }
+ jsonObject.put(fieldName.asInternal(), internalValue);
+ }
+ value = jsonObject;
+ }
map.put(column.name(), value);
}
return map;
diff --git a/testing/src/main/java/io/stargate/it/http/RestApiv1Test.java b/testing/src/main/java/io/stargate/it/http/RestApiv1Test.java
index ac8260b5..81c0ce10 100644
--- a/testing/src/main/java/io/stargate/it/http/RestApiv1Test.java
+++ b/testing/src/main/java/io/stargate/it/http/RestApiv1Test.java
@@ -1065,6 +1065,37 @@ public class RestApiv1Test extends BaseIntegrationTest {
HttpStatus.SC_BAD_REQUEST);
}
+ @Test
+ public void queryWithUdtCol() throws IOException {
+ String tableName = "tbl_query_" + System.currentTimeMillis();
+ // createTable(tableName);
+ session.execute("create type " + keyspace + ".udt_167785279 (a int, b int)");
+ session.execute(
+ "create table "
+ + keyspace
+ + "."
+ + tableName
+ + " ( pk0 varint, pk1 varint, pk2 smallint, pk3 int, pk4 int, ck0 smallint, ck1 text, col0 frozen<udt_167785279>, col1 date, col10 map<tinyint, double>, col11 float, col2 timestamp, col3 timeuuid, col4 bigint, col5 ascii, col6 map<tinyint, varint>, col7 float, col8 duration, col9 map<ascii, decimal>, PRIMARY KEY ((pk0, pk1, pk2, pk3, pk4), ck0, ck1))");
+ session.execute(
+ "insert into "
+ + keyspace
+ + "."
+ + tableName
+ + " (pk0,pk1,pk2,pk3,pk4,ck0,ck1,col0) values(8275984804989873180, 5276317386634354038, 28639,1005107841,1544552257, 10,'a',{a:1, b:2})");
+
+ String body =
+ RestUtils.get(
+ authToken,
+ String.format(
+ "%s:8082/v1/keyspaces/%s/tables/%s/rows/8275984804989873180;5276317386634354038;28639;1005107841;1544552257",
+ host, keyspace, tableName),
+ HttpStatus.SC_OK);
+
+ RowResponse rowResponse = objectMapper.readValue(body, RowResponse.class);
+ assertThat(rowResponse.getCount()).isEqualTo(1);
+ assertThat(rowResponse.getRows().get(0).get("col0")).isNotNull();
+ }
+
@Test
public void deleteRowWithClustering() throws IOException {
String tableName = "tbl_deleterows_clustering_" + System.currentTimeMillis(); | ['restapi/src/main/java/io/stargate/web/resources/Converters.java', 'testing/src/main/java/io/stargate/it/http/RestApiv1Test.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 4,638,416 | 996,141 | 127,815 | 876 | 2,301 | 608 | 45 | 2 | 8,856 | 441 | 2,252 | 142 | 2 | 4 | 1970-01-01T00:27:40 | 760 | Java | {'Java': 9863787, 'HTML': 792732, 'Shell': 22681, 'Dockerfile': 1151, 'Makefile': 892} | Apache License 2.0 |
62 | apache/mina-sshd/264/263 | apache | mina-sshd | https://github.com/apache/mina-sshd/issues/263 | https://github.com/apache/mina-sshd/pull/264 | https://github.com/apache/mina-sshd/pull/264 | 1 | fixes | Race condition in BufferedIoOutputStream | SFTP tests are flaky. Turns out that they are running into
```
23:13:59.123 | ERROR | MinaProcessor-25 | o.a.s.c.c.BufferedIoOutputStream | org.apache.sshd.common.channel.BufferedIoOutputStream 219 | finishWrite(sftp-out@0)[ChannelAsyncOutputStream[ChannelSession[id=0, recipient=0]-ServerSessionImpl[testTransferIntegrityWithBufferLargerThanPacket[REKEY_BLOCK_SIZE 65,536]@/127.0.0.1:59555]] cmd=SSH_MSG_CHANNEL_DATA] - pending byte counts underflow (-64525) after 18070131 bytes
23:13:59.123 | ERROR | m-42976-thread-1 | o.a.s.s.s.SftpSubsystem | org.apache.sshd.common.util.logging.LoggingUtils 693 | run(ServerSessionImpl[testTransferIntegrityWithBufferLargerThanPacket[REKEY_BLOCK_SIZE 65,536]@/127.0.0.1:59555]) SshChannelBufferedOutputException caught in SFTP subsystem after 863 buffers: Pending byte counts underflow
23:23:59.498 | INFO | )-timer-thread-1 | o.a.s.s.s.ServerSessionImpl | org.apache.sshd.common.session.helpers.SessionHelper 1183 | Disconnecting(ServerSessionImpl[testTransferIntegrityWithBufferLargerThanPacket[REKEY_BLOCK_SIZE 65,536]@/127.0.0.1:59555]): SSH2_DISCONNECT_PROTOCOL_ERROR - Detected IdleTimeout after 600375/600000 ms.
Finished org.apache.sshd.sftp.client.SftpTransferTest:testTransferIntegrityWithBufferLargerThanPacket[REKEY_BLOCK_SIZE 65,536] in 610192 ms
```
Let's ignore the fact that test hangs for 10 minutes until that timeout expires; that a different minor problem. The real problem is the "pending byte counts underflow", which indicates that the `BufferedIoOutputStream` somehow managed to write more data than was passed to it.
This is a race condition between `BufferedIoOutputStream.startWriting()` and `BufferedIoOutputStream.finishWrite()`. The following sequence of events is possible when a write that was in progress just finished and the user of the stream just initiates a new write:
1. Thread 1: `startWriting` gets the head of the write queue -- this is still the future/buffer that was just written
2. Thread 2: `finishWrite` removes that write from the write queue
3. Thread 2: `finishWrite` clears the "current" write
4. Thread 1: `startWriting` sets the "current" write and happily writes the future/buffer again.
Combined with the fact that the underlying `ChannelAsyncOutputStream` may in some cases copy the buffer and actually write that copy, but doesn't consume the original buffer in that case, this leads to the same data being written again, and when that second write finishes, this byte count gets subtracted again from the number of total bytes to be written. So the count is added once but subtracted twice, and eventually this "pending byte counts underflow" is hit.
This race condition in `BufferedIoOutputStream` needs to be fixed. Optionally `ChannelAsyncOutputStream` should consume the original buffer if it makes a copy; though I'm undecided on that: if it did, it might have hidden this bug (because then the second write of that buffer would have been a zero-byte write).
(The problem is not specific to the MINA transport back-end; it also occurs with NIO2 from time to time. CI builds are green because the race condition appears to be hit infrequently, and on a re-run the test usually succeeds.)
| ae3851ab90bde0f6d873b1afb1c0887ae5b07e73 | ba82c132472c25168e17bae9e5878b8f1b9af252 | https://github.com/apache/mina-sshd/compare/ae3851ab90bde0f6d873b1afb1c0887ae5b07e73...ba82c132472c25168e17bae9e5878b8f1b9af252 | diff --git a/sshd-core/src/main/java/org/apache/sshd/common/channel/BufferedIoOutputStream.java b/sshd-core/src/main/java/org/apache/sshd/common/channel/BufferedIoOutputStream.java
index 1e3a23c35..d024f3b04 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/channel/BufferedIoOutputStream.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/channel/BufferedIoOutputStream.java
@@ -152,38 +152,56 @@ public class BufferedIoOutputStream extends AbstractInnerCloseable implements Io
}
}
- protected void startWriting() throws IOException {
- IoWriteFutureImpl future = writes.peek();
- // No more pending requests
- if (future == null) {
- return;
- }
+ private IoWriteFutureImpl getWriteRequest() {
+ IoWriteFutureImpl future = null;
+ while (future == null) {
+ future = writes.peek();
+ // No more pending requests
+ if (future == null) {
+ return null;
+ }
+
+ // Don't try to write any further if pending exception signaled
+ Throwable pendingError = pendingException.get();
+ if (pendingError != null) {
+ log.error("startWriting({})[{}] propagate to {} write requests pending error={}[{}]", getId(), out,
+ writes.size(), getClass().getSimpleName(), pendingError.getMessage());
- // Don't try to write any further if pending exception signaled
- Throwable pendingError = pendingException.get();
- if (pendingError != null) {
- log.error("startWriting({})[{}] propagate to {} write requests pending error={}[{}]",
- getId(), out, writes.size(), getClass().getSimpleName(), pendingError.getMessage());
+ IoWriteFutureImpl currentFuture = currentWrite.getAndSet(null);
+ for (IoWriteFutureImpl pendingWrite : writes) {
+ // Checking reference by design
+ if (UnaryEquator.isSameReference(pendingWrite, currentFuture)) {
+ continue; // will be taken care of when its listener is eventually called
+ }
- IoWriteFutureImpl currentFuture = currentWrite.getAndSet(null);
- for (IoWriteFutureImpl pendingWrite : writes) {
- // Checking reference by design
- if (UnaryEquator.isSameReference(pendingWrite, currentFuture)) {
- continue; // will be taken care of when its listener is eventually called
+ future.setValue(pendingError);
}
- future.setValue(pendingError);
+ writes.clear();
+ return null;
}
- writes.clear();
- return;
+ // Cannot honor this request yet since other pending one incomplete
+ if (!currentWrite.compareAndSet(null, future)) {
+ return null;
+ }
+
+ if (future.isDone()) {
+ // A write was on-going, and finishWrite hadn't removed the future yet when we got it
+ // above. See https://github.com/apache/mina-sshd/issues/263 .
+ // Re-try.
+ currentWrite.set(null);
+ future = null;
+ }
}
+ return future;
+ }
- // Cannot honor this request yet since other pending one incomplete
- if (!currentWrite.compareAndSet(null, future)) {
+ protected void startWriting() throws IOException {
+ IoWriteFutureImpl future = getWriteRequest();
+ if (future == null) {
return;
}
-
Buffer buffer = future.getBuffer();
int bufferSize = buffer.available();
out.writeBuffer(buffer).addListener(f -> {
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelAsyncOutputStream.java b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelAsyncOutputStream.java
index e9ac8dfb3..48fef0918 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelAsyncOutputStream.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelAsyncOutputStream.java
@@ -294,7 +294,9 @@ public class ChannelAsyncOutputStream extends AbstractCloseable implements IoOut
if (chunkLength < stillToSend && !(f instanceof BufferedFuture)) {
// We can send only part of the data remaining: copy the buffer (if it hasn't been copied before) because
// the original may be re-used, then send the bit we can send, and queue up a future for sending the rest.
- f = new BufferedFuture(future.getId(), new ByteArrayBuffer(buffer.getCompactData()));
+ Buffer copied = new ByteArrayBuffer(stillToSend);
+ copied.putBuffer(buffer, false);
+ f = new BufferedFuture(future.getId(), copied);
f.addListener(w -> future.setValue(w.getException() != null ? w.getException() : w.isWritten()));
}
if (chunkLength <= 0) { | ['sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelAsyncOutputStream.java', 'sshd-core/src/main/java/org/apache/sshd/common/channel/BufferedIoOutputStream.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 5,869,786 | 1,239,736 | 151,119 | 1,002 | 3,348 | 610 | 66 | 2 | 3,279 | 388 | 792 | 25 | 0 | 1 | 1970-01-01T00:27:47 | 722 | Java | {'Java': 8381376, 'Shell': 37094, 'Batchfile': 15035, 'Python': 11690, 'HTML': 6129, 'Dockerfile': 1257} | Apache License 2.0 |
52 | apache/mina-sshd/399/398 | apache | mina-sshd | https://github.com/apache/mina-sshd/issues/398 | https://github.com/apache/mina-sshd/pull/399 | https://github.com/apache/mina-sshd/pull/399 | 1 | fixes | SftpInputStreamAsync#read(byte[], int, int) fails on calls with len = 0 | ### Version
2.9.2
### Bug description
When passing len = 0 on a second read call, after eofIndicator has already be set to true, the read method returns -1. This can lead to an incomplete read when using e.g. java.io.InputStream#readAllBytes or java.io.InputStream#readNBytes(int).
A possible solution would be an early return of 0 in case of len = 0
### Actual behavior
First reading offset 0, len 8192,
then offset 8192, len 0
then offset 8192, len 8192
Return in sum at most 8192 bytes (if available)
### Expected behavior
First reading offset 0, len 8192,
then offset 8192, len 0
then offset 8192, len 8192
Return in sum more 8192 bytes (if available)
### Relevant log output
_No response_
### Other information
_No response_ | 441ca31c9c5bf8c0b71aa9602b3e570e32be0703 | 511cd92a68d08c591a2a4030728971a1c36172c3 | https://github.com/apache/mina-sshd/compare/441ca31c9c5bf8c0b71aa9602b3e570e32be0703...511cd92a68d08c591a2a4030728971a1c36172c3 | diff --git a/sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/SftpInputStreamAsync.java b/sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/SftpInputStreamAsync.java
index 68e45f363..7979dcf0b 100644
--- a/sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/SftpInputStreamAsync.java
+++ b/sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/SftpInputStreamAsync.java
@@ -136,7 +136,7 @@ public class SftpInputStreamAsync extends InputStreamWithChannel implements Sftp
int l = buf.available();
buf.getRawBytes(b, offset.getAndAdd(l), l);
});
- if (res == 0 && eofIndicator) {
+ if (res == 0 && eofIndicator && hasNoData()) {
res = -1;
}
return res;
diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTest.java
index a0b408d1b..d2f9ec3fc 100644
--- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTest.java
+++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTest.java
@@ -284,6 +284,51 @@ public class SftpTest extends AbstractSftpClientTestSupport {
}
}
+ @Test // see SSHD-1287
+ public void testZeroRead() throws Exception {
+ Path targetPath = detectTargetFolder();
+ Path parentPath = targetPath.getParent();
+ Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(),
+ getCurrentTestName());
+ Path testFile = assertHierarchyTargetFolderExists(lclSftp).resolve("file.bin");
+ byte[] expected = new byte[4000];
+
+ Factory<? extends Random> factory = sshd.getRandomFactory();
+ Random rnd = factory.create();
+ rnd.fill(expected);
+ Files.write(testFile, expected);
+
+ String file = CommonTestSupportUtils.resolveRelativeRemotePath(parentPath, testFile);
+ try (SftpClient sftp = createSingleSessionClient()) {
+ byte[] actual = new byte[expected.length];
+ try (InputStream in = sftp.read(file)) {
+ int off = 0;
+ int n = 0;
+ while (off < actual.length) {
+ n = in.read(actual, off, 100);
+ if (n < 0) {
+ break;
+ }
+ off += n;
+ if (in.read(actual, off, 0) < 0) {
+ break;
+ }
+ }
+ assertEquals("Short read", actual.length, off);
+ if (n >= 0) {
+ n = in.read();
+ assertTrue("Stream not at eof", n < 0);
+ }
+ }
+ for (int index = 0; index < actual.length; index++) {
+ byte expByte = expected[index];
+ byte actByte = actual[index];
+ assertEquals("Mismatched values at index=" + index, Integer.toHexString(expByte & 0xFF),
+ Integer.toHexString(actByte & 0xFF));
+ }
+ }
+ }
+
@Test // see SSHD-1288
public void testReadWriteDownload() throws Exception {
Assume.assumeTrue("Not sure appending to a file opened for reading works on Windows", | ['sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTest.java', 'sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/SftpInputStreamAsync.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 5,996,660 | 1,265,808 | 154,038 | 1,025 | 96 | 28 | 2 | 1 | 782 | 124 | 204 | 36 | 0 | 0 | 1970-01-01T00:28:09 | 722 | Java | {'Java': 8381376, 'Shell': 37094, 'Batchfile': 15035, 'Python': 11690, 'HTML': 6129, 'Dockerfile': 1257} | Apache License 2.0 |
55 | apache/mina-sshd/308/302 | apache | mina-sshd | https://github.com/apache/mina-sshd/issues/302 | https://github.com/apache/mina-sshd/pull/308 | https://github.com/apache/mina-sshd/pull/308 | 2 | fixes | requestNewKeysExchange may cause KeyExchangeMessageHandler into dead lock,cpu 100% | ### Version
2.9.1
### Bug description
i observed in cases, the write packet thread is always running and in the interval i saw "equestNewKeysExchange(ClientSessionImpl[root@/47.104.92.124:22]) Initiating key re-exchange
method:o.a.s.c.s.ClientSessionImpl(AbstractSession.java:2404) " in log
### Actual behavior
after i saw log "equestNewKeysExchange(ClientSessionImpl[root@/47.104.92.124:22]) Initiating key re-exchange
method:o.a.s.c.s.ClientSessionImpl(AbstractSession.java:2404)",the write packet thread is soar to 100%,not stopped
### Expected behavior
i expect when the connection is closed the cpu is down,and the thread is stopped
### Relevant log output
```Shell
equestNewKeysExchange(ClientSessionImpl[root@/47.104.92.124:22]) Initiating key re-exchange
method:o.a.s.c.s.ClientSessionImpl(AbstractSession.java:2404)
```
### Other information
_No response_ | 4ad64c26ca22a0d9ef5945178cf58f092dd6150f | 379f79723c9c700454c246be6d8cfd5330dd32df | https://github.com/apache/mina-sshd/compare/4ad64c26ca22a0d9ef5945178cf58f092dd6150f...379f79723c9c700454c246be6d8cfd5330dd32df | diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/KeyExchangeMessageHandler.java b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/KeyExchangeMessageHandler.java
index 294935a0a..11501ef77 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/KeyExchangeMessageHandler.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/KeyExchangeMessageHandler.java
@@ -34,6 +34,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
import org.apache.sshd.common.SshConstants;
+import org.apache.sshd.common.SshException;
import org.apache.sshd.common.future.DefaultKeyExchangeFuture;
import org.apache.sshd.common.io.IoWriteFuture;
import org.apache.sshd.common.kex.KexState;
@@ -104,6 +105,11 @@ public class KeyExchangeMessageHandler {
*/
protected volatile boolean kexFlushed = true;
+ /**
+ * Indicates that the handler has been shut down.
+ */
+ protected volatile boolean shutDown;
+
/**
* Never {@code null}. Used to block some threads when writing packets while pending packets are still being flushed
* at the end of a KEX to avoid overrunning the flushing thread. Always set, initially fulfilled. At the beginning
@@ -194,6 +200,7 @@ public class KeyExchangeMessageHandler {
public void shutdown() {
SimpleImmutableEntry<Integer, DefaultKeyExchangeFuture> items = updateState(() -> {
kexFlushed = true;
+ shutDown = true;
return new SimpleImmutableEntry<Integer, DefaultKeyExchangeFuture>(
Integer.valueOf(pendingPackets.size()),
kexFlushedFuture);
@@ -229,33 +236,33 @@ public class KeyExchangeMessageHandler {
boolean enqueued = false;
boolean isLowLevelMessage = cmd <= SshConstants.SSH_MSG_KEX_LAST && cmd != SshConstants.SSH_MSG_SERVICE_REQUEST
&& cmd != SshConstants.SSH_MSG_SERVICE_ACCEPT;
+ IoWriteFuture future = null;
try {
if (isLowLevelMessage) {
// Low-level messages can always be sent.
- return session.doWritePacket(buffer);
+ future = session.doWritePacket(buffer);
+ } else {
+ future = writeOrEnqueue(cmd, buffer, timeout, unit);
+ enqueued = future instanceof PendingWriteFuture;
}
- IoWriteFuture future = writeOrEnqueue(cmd, buffer, timeout, unit);
- enqueued = future instanceof PendingWriteFuture;
- return future;
} finally {
session.resetIdleTimeout();
- if (!enqueued) {
- try {
- session.checkRekey();
- } catch (GeneralSecurityException e) {
- if (log.isDebugEnabled()) {
- log.debug("writePacket({}) failed ({}) to check re-key: {}", session, e.getClass().getSimpleName(),
- e.getMessage(), e);
- }
- throw ValidateUtils.initializeExceptionCause(
- new ProtocolException("Failed (" + e.getClass().getSimpleName() + ")"
- + " to check re-key necessity: " + e.getMessage()),
- e);
- } catch (Exception e) {
- ExceptionUtils.rethrowAsIoException(e);
+ }
+ if (!enqueued) {
+ try {
+ session.checkRekey();
+ } catch (GeneralSecurityException e) {
+ if (log.isDebugEnabled()) {
+ log.debug("writePacket({}) failed ({}) to check re-key: {}", session, e.getClass().getSimpleName(),
+ e.getMessage(), e);
}
+ throw ValidateUtils.initializeExceptionCause(new ProtocolException(
+ "Failed (" + e.getClass().getSimpleName() + ")" + " to check re-key necessity: " + e.getMessage()), e);
+ } catch (Exception e) {
+ ExceptionUtils.rethrowAsIoException(e);
}
}
+ return future;
}
/**
@@ -288,6 +295,9 @@ public class KeyExchangeMessageHandler {
// Use the readLock here to give KEX state updates and the flushing thread priority.
lock.readLock().lock();
try {
+ if (shutDown) {
+ throw new SshException("Write attempt on closing session: " + SshConstants.getCommandMessageName(cmd));
+ }
KexState state = session.kexState.get();
boolean kexDone = KexState.DONE.equals(state) || KexState.KEYS.equals(state);
if (kexDone && kexFlushed) { | ['sshd-core/src/main/java/org/apache/sshd/common/session/helpers/KeyExchangeMessageHandler.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 5,895,089 | 1,244,523 | 151,674 | 1,005 | 2,346 | 410 | 46 | 1 | 881 | 85 | 229 | 29 | 0 | 1 | 1970-01-01T00:27:53 | 722 | Java | {'Java': 8381376, 'Shell': 37094, 'Batchfile': 15035, 'Python': 11690, 'HTML': 6129, 'Dockerfile': 1257} | Apache License 2.0 |
58 | apache/mina-sshd/299/297 | apache | mina-sshd | https://github.com/apache/mina-sshd/issues/297 | https://github.com/apache/mina-sshd/pull/299 | https://github.com/apache/mina-sshd/pull/299 | 1 | fixes | SSHD Client failing on private key file with key password | ### Version
2.9.2
### Bug description
When attempting to run the SSH client with that private key file that is protected with a password the Mina SSH client doesn't make the connection.
The client was run using the command
`java -jar MinaSshClient-2.9.2.jar -i K:\\id_rsa [email protected]`
### Actual behavior
The client seems to fail to load the key resource with the following warning
`WARNING: org.apache.sshd.cli.client.SshCl: Failed (FailedLoginException) to load key resource=K:\\id_rsa: No password provider for encrypted key in K:\\id_rsa`
the connection subsequently fails with a "No more authentication methods available"
### Expected behavior
The client should prompt for a password for the key file or have another command line parameter to specify it.
### Relevant log output
_No response_
### Other information
I did a bit of debugging on this and for whatever reason the prompt for the password for the private key file isn't being triggered by the code in the _SshClientCliSupport_, _setupSessionIdentities_ method.
Whether or not it's the correct solution what I did in my own code is I used the setPasswordFinder method on the FileKeyPairProvider with the same code segment as for the client `setFilePasswordProvider` and it seemed to work.
| 8c08fc7dbb7c075e84f2cb2f33154965d0f6fddb | 10916864bf5d4885cda616f97aa29cdf11e02b3e | https://github.com/apache/mina-sshd/compare/8c08fc7dbb7c075e84f2cb2f33154965d0f6fddb...10916864bf5d4885cda616f97aa29cdf11e02b3e | diff --git a/sshd-common/src/main/java/org/apache/sshd/common/keyprovider/MultiKeyIdentityProvider.java b/sshd-common/src/main/java/org/apache/sshd/common/keyprovider/MultiKeyIdentityProvider.java
index 08e4429c8..697e8edcc 100644
--- a/sshd-common/src/main/java/org/apache/sshd/common/keyprovider/MultiKeyIdentityProvider.java
+++ b/sshd-common/src/main/java/org/apache/sshd/common/keyprovider/MultiKeyIdentityProvider.java
@@ -32,12 +32,17 @@ import org.apache.sshd.common.session.SessionContext;
* @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a>
*/
public class MultiKeyIdentityProvider implements KeyIdentityProvider {
+
protected final Iterable<? extends KeyIdentityProvider> providers;
public MultiKeyIdentityProvider(Iterable<? extends KeyIdentityProvider> providers) {
this.providers = providers;
}
+ public Iterable<? extends KeyIdentityProvider> getProviders() {
+ return providers == null ? Collections::emptyIterator : providers;
+ }
+
@Override
public Iterable<KeyPair> loadKeys(SessionContext session) {
return new Iterable<KeyPair>() {
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java b/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java
index 3c9cbc1ab..cc493b214 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java
@@ -78,6 +78,7 @@ import org.apache.sshd.common.NamedResource;
import org.apache.sshd.common.ServiceFactory;
import org.apache.sshd.common.channel.ChannelFactory;
import org.apache.sshd.common.config.keys.FilePasswordProvider;
+import org.apache.sshd.common.config.keys.FilePasswordProviderManager;
import org.apache.sshd.common.config.keys.KeyUtils;
import org.apache.sshd.common.config.keys.PublicKeyEntry;
import org.apache.sshd.common.future.SshFutureListener;
@@ -85,8 +86,10 @@ import org.apache.sshd.common.helpers.AbstractFactoryManager;
import org.apache.sshd.common.io.IoConnectFuture;
import org.apache.sshd.common.io.IoConnector;
import org.apache.sshd.common.io.IoSession;
+import org.apache.sshd.common.keyprovider.AbstractResourceKeyPairProvider;
import org.apache.sshd.common.keyprovider.KeyIdentityProvider;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
+import org.apache.sshd.common.keyprovider.MultiKeyIdentityProvider;
import org.apache.sshd.common.session.helpers.AbstractSession;
import org.apache.sshd.common.util.ExceptionUtils;
import org.apache.sshd.common.util.GenericUtils;
@@ -742,16 +745,49 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa
if (useDefaultIdentities) {
setupDefaultSessionIdentities(session, identities);
+ } else if (identities == null) {
+ session.setKeyIdentityProvider(KeyIdentityProvider.EMPTY_KEYS_PROVIDER);
} else {
- session.setKeyIdentityProvider(
- (identities == null)
- ? KeyIdentityProvider.EMPTY_KEYS_PROVIDER
- : identities);
+ session.setKeyIdentityProvider(ensureFilePasswordProvider(identities));
}
connectFuture.setSession(session);
}
+ /**
+ * Sets this client's {@link FilePasswordProvider} on the {@link KeyIdentityProvider} if it is an
+ * {@link AbstractResourceKeyPairProvider} or implements {@link FilePasswordProviderManager} and doesn't have one
+ * yet. If the given {@code identities} is a {@link MultiKeyIdentityProvider}, the wrapped identity providers are
+ * set up.
+ *
+ * @param identities {@link KeyIdentityProvider} to set up
+ * @return a {@link KeyIdentityProvider} configured with a {@link FilePasswordProvider}
+ * @see #getFilePasswordProvider()
+ */
+ protected KeyIdentityProvider ensureFilePasswordProvider(KeyIdentityProvider identities) {
+ if (identities instanceof AbstractResourceKeyPairProvider<?>) {
+ AbstractResourceKeyPairProvider<?> keyProvider = (AbstractResourceKeyPairProvider<?>) identities;
+ if (keyProvider.getPasswordFinder() == null) {
+ FilePasswordProvider passwordProvider = getFilePasswordProvider();
+ if (passwordProvider != null) {
+ keyProvider.setPasswordFinder(passwordProvider);
+ }
+ }
+ } else if (identities instanceof FilePasswordProviderManager) {
+ FilePasswordProviderManager keyProvider = (FilePasswordProviderManager) identities;
+ if (keyProvider.getFilePasswordProvider() == null) {
+ FilePasswordProvider passwordProvider = getFilePasswordProvider();
+ if (passwordProvider != null) {
+ keyProvider.setFilePasswordProvider(passwordProvider);
+ }
+ }
+ } else if (identities instanceof MultiKeyIdentityProvider) {
+ MultiKeyIdentityProvider multiProvider = (MultiKeyIdentityProvider) identities;
+ multiProvider.getProviders().forEach(this::ensureFilePasswordProvider);
+ }
+ return identities;
+ }
+
protected void setupDefaultSessionIdentities(
ClientSession session, KeyIdentityProvider extraIdentities)
throws IOException, GeneralSecurityException {
@@ -765,8 +801,9 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa
}
}
- // Prefer the extra identities to come first since they were probably indicate by the host-config entry
+ // Prefer the extra identities to come first since they were probably indicated by the host-config entry
KeyIdentityProvider kpEffective = KeyIdentityProvider.resolveKeyIdentityProvider(extraIdentities, kpSession);
+ kpEffective = ensureFilePasswordProvider(kpEffective);
if (!UnaryEquator.isSameReference(kpSession, kpEffective)) {
if (debugEnabled) {
log.debug("setupDefaultSessionIdentities({}) key identity provider enhanced", session);
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java
index a164956cd..dc63fd486 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java
@@ -31,6 +31,9 @@ import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
import java.security.KeyPair;
import java.util.Arrays;
import java.util.Collection;
@@ -76,6 +79,8 @@ import org.apache.sshd.common.channel.ChannelListener;
import org.apache.sshd.common.channel.StreamingChannel;
import org.apache.sshd.common.channel.exception.SshChannelClosedException;
import org.apache.sshd.common.config.keys.KeyUtils;
+import org.apache.sshd.common.config.keys.writer.openssh.OpenSSHKeyEncryptionContext;
+import org.apache.sshd.common.config.keys.writer.openssh.OpenSSHKeyPairResourceWriter;
import org.apache.sshd.common.future.CloseFuture;
import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.io.IoInputStream;
@@ -83,6 +88,7 @@ import org.apache.sshd.common.io.IoOutputStream;
import org.apache.sshd.common.io.IoReadFuture;
import org.apache.sshd.common.io.IoSession;
import org.apache.sshd.common.io.IoWriteFuture;
+import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
import org.apache.sshd.common.session.ConnectionService;
import org.apache.sshd.common.session.Session;
@@ -93,6 +99,7 @@ import org.apache.sshd.common.util.buffer.Buffer;
import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
import org.apache.sshd.common.util.io.output.NoCloseOutputStream;
import org.apache.sshd.common.util.net.SshdSocketAddress;
+import org.apache.sshd.common.util.security.SecurityUtils;
import org.apache.sshd.core.CoreModuleProperties;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.keyboard.DefaultKeyboardInteractiveAuthenticator;
@@ -1048,6 +1055,45 @@ public class ClientTest extends BaseTestSupport {
assertNull("Session closure not signalled", clientSessionHolder.get());
}
+ @Test
+ public void testPublicKeyAuthWithEncryptedKey() throws Exception {
+ // Create an encrypted private key file
+ KeyPair pair = SecurityUtils.getKeyPairGenerator("RSA").generateKeyPair();
+ Path keyFile = getTestResourcesFolder().resolve("userKey");
+ Files.deleteIfExists(keyFile);
+ OpenSSHKeyEncryptionContext options = new OpenSSHKeyEncryptionContext();
+ options.setPassword("test-passphrase");
+ options.setCipherName("AES");
+ options.setCipherMode("CTR");
+ options.setCipherType("256");
+ try (OutputStream out = Files.newOutputStream(keyFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
+ OpenSSHKeyPairResourceWriter.INSTANCE.writePrivateKey(pair, "test key", options, out);
+ }
+ // The server accepts only this key
+ sshd.setPublickeyAuthenticator((username, key, session) -> KeyUtils.compareKeys(key, pair.getPublic()));
+ sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE);
+ sshd.setKeyboardInteractiveAuthenticator(KeyboardInteractiveAuthenticator.NONE);
+ // Configure the client to use the encrypted key file
+ client.setKeyIdentityProvider(new FileKeyPairProvider(keyFile));
+ AtomicBoolean passwordProvided = new AtomicBoolean();
+ client.setFilePasswordProvider((session, file, index) -> {
+ passwordProvided.set(true);
+ return "test-passphrase";
+ });
+ client.setUserAuthFactories(Collections.singletonList(UserAuthPublicKeyFactory.INSTANCE));
+ client.start();
+
+ try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(CONNECT_TIMEOUT)
+ .getSession()) {
+ assertNotNull("Client session creation not signalled", clientSessionHolder.get());
+ session.auth().verify(AUTH_TIMEOUT);
+ assertTrue("Password provider should have been called", passwordProvided.get());
+ } finally {
+ client.stop();
+ }
+ assertNull("Session closure not signalled", clientSessionHolder.get());
+ }
+
@Test
public void testPublicKeyAuthNewWithFailureOnFirstIdentity() throws Exception {
SimpleGeneratorHostKeyProvider provider = new SimpleGeneratorHostKeyProvider(); | ['sshd-common/src/main/java/org/apache/sshd/common/keyprovider/MultiKeyIdentityProvider.java', 'sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java', 'sshd-core/src/main/java/org/apache/sshd/client/SshClient.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 5,889,730 | 1,243,467 | 151,573 | 1,005 | 3,035 | 546 | 52 | 2 | 1,299 | 192 | 297 | 37 | 0 | 0 | 1970-01-01T00:27:51 | 722 | Java | {'Java': 8381376, 'Shell': 37094, 'Batchfile': 15035, 'Python': 11690, 'HTML': 6129, 'Dockerfile': 1257} | Apache License 2.0 |
57 | apache/mina-sshd/303/298 | apache | mina-sshd | https://github.com/apache/mina-sshd/issues/298 | https://github.com/apache/mina-sshd/pull/303 | https://github.com/apache/mina-sshd/pull/303 | 1 | fixes | Server side heartbeat not working | ### Version
master
### Bug description
dependency:
```
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
<version>2.7.0</version>
</dependency>
```
Code:
```
SshServer sshd = SshServer.setUpDefaultServer();
sshd.setPort(3333);
sshd.setShellFactory(InteractiveProcessShellFactory.INSTANCE);
sshd.setSessionHeartbeat(SessionHeartbeatController.HeartbeatType.IGNORE, Duration.ofSeconds(5));
sshd.setKeyPairProvider(new ClassLoadableResourceKeyPairProvider(getClass().getClassLoader(), "rsa.key"));
sshd.setPasswordAuthenticator((username, password, session) -> username.equals(password));
sshd.start();
log.info("SSHD server started");
```
ssh Client:
```
user/passwd = test
ssh [email protected] -p3333
```
### Actual behavior
read [Server Setup Manual](https://github.com/apache/mina-sshd/blob/master/docs/server-setup.md) last section
I with my SSHD has ServerSide heartbeat,But setSessionHeartbeat API didn't working, ssh session didn't get any interval heartbeat
### Expected behavior
SSHD automatic send heartbeat message for each ssh session
### Relevant log output
_No response_
### Other information
_No response_ | 10916864bf5d4885cda616f97aa29cdf11e02b3e | dcc65db70639c45de50f80360a823115dc11b6d5 | https://github.com/apache/mina-sshd/compare/10916864bf5d4885cda616f97aa29cdf11e02b3e...dcc65db70639c45de50f80360a823115dc11b6d5 | diff --git a/sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java b/sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java
index 41d1eb0b6..b7970aae5 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java
@@ -287,7 +287,7 @@ public abstract class AbstractServerSession extends AbstractSession implements S
throw new SshException(SshConstants.SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE, "Unknown service: " + name);
}
- currentService.set(service, factory.getName(), false);
+ currentService.set(service, factory.getName(), true);
}
@Override
diff --git a/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java b/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java
index ec655841d..d91c13d12 100644
--- a/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java
@@ -56,9 +56,11 @@ import org.apache.sshd.common.channel.RemoteWindow;
import org.apache.sshd.common.channel.WindowClosedException;
import org.apache.sshd.common.io.IoSession;
import org.apache.sshd.common.kex.KexProposalOption;
+import org.apache.sshd.common.session.ReservedSessionMessagesHandler;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.common.session.SessionContext;
import org.apache.sshd.common.session.SessionDisconnectHandler;
+import org.apache.sshd.common.session.SessionHeartbeatController.HeartbeatType;
import org.apache.sshd.common.session.SessionListener;
import org.apache.sshd.common.session.helpers.AbstractConnectionService;
import org.apache.sshd.common.session.helpers.AbstractSession;
@@ -68,6 +70,7 @@ import org.apache.sshd.common.util.GenericUtils;
import org.apache.sshd.common.util.MapEntryUtils;
import org.apache.sshd.common.util.MapEntryUtils.NavigableMapBuilder;
import org.apache.sshd.common.util.OsUtils;
+import org.apache.sshd.common.util.buffer.Buffer;
import org.apache.sshd.core.CoreModuleProperties;
import org.apache.sshd.deprecated.ClientUserAuthServiceOld;
import org.apache.sshd.server.auth.keyboard.InteractiveChallenge;
@@ -691,6 +694,26 @@ public class ServerTest extends BaseTestSupport {
}
}
+ @Test
+ public void testServerHeartbeat() throws Exception {
+ sshd.setSessionHeartbeat(HeartbeatType.IGNORE, Duration.ofMillis(500));
+ sshd.start();
+ AtomicInteger ignoreMessageCount = new AtomicInteger(0);
+ client.setReservedSessionMessagesHandler(new ReservedSessionMessagesHandler() {
+
+ @Override
+ public void handleIgnoreMessage(Session session, Buffer buffer) throws Exception {
+ ignoreMessageCount.incrementAndGet();
+ }
+ });
+ client.start();
+ try (ClientSession s = createTestClientSession(sshd)) {
+ Thread.sleep(2000);
+ }
+ long ignoreMessages = ignoreMessageCount.get();
+ assertTrue("Epected some ignore messages (server-side heartbeat)", ignoreMessages > 0 && ignoreMessages <= 5);
+ }
+
@Test
public void testEnvironmentVariablesPropagationToServer() throws Exception {
AtomicReference<Environment> envHolder = new AtomicReference<>(null); | ['sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java', 'sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 5,892,095 | 1,243,917 | 151,615 | 1,005 | 126 | 22 | 2 | 1 | 1,232 | 97 | 291 | 52 | 1 | 3 | 1970-01-01T00:27:52 | 722 | Java | {'Java': 8381376, 'Shell': 37094, 'Batchfile': 15035, 'Python': 11690, 'HTML': 6129, 'Dockerfile': 1257} | Apache License 2.0 |
601 | openfoodfacts/openfoodfacts-androidapp/189/187 | openfoodfacts | openfoodfacts-androidapp | https://github.com/openfoodfacts/openfoodfacts-androidapp/issues/187 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/189 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/189 | 1 | fix | add a new product from scan fragment | From rhe scan fragment, when the product doesn't exist a popup appears and when i want to add the product the application crash | 60a1346091cc436d2c9ca7d0bc826833ca750f6e | 4fc7720a844aeae8a6d57151c64ab33ae8239e35 | https://github.com/openfoodfacts/openfoodfacts-androidapp/compare/60a1346091cc436d2c9ca7d0bc826833ca750f6e...4fc7720a844aeae8a6d57151c64ab33ae8239e35 | diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java
index 70d56b508..9306d75c3 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java
@@ -13,6 +13,8 @@ import com.orm.SugarRecord;
import net.steamcrafted.loadtoast.LoadToast;
+import org.apache.commons.lang3.StringUtils;
+
import java.io.File;
import java.util.Date;
import java.util.List;
@@ -25,7 +27,6 @@ import openfoodfacts.github.scrachx.openfood.models.AllergenRestResponse;
import openfoodfacts.github.scrachx.openfood.models.HistoryProduct;
import openfoodfacts.github.scrachx.openfood.models.Product;
import openfoodfacts.github.scrachx.openfood.models.ProductImage;
-import openfoodfacts.github.scrachx.openfood.models.ProductImageField;
import openfoodfacts.github.scrachx.openfood.models.Search;
import openfoodfacts.github.scrachx.openfood.models.SendProduct;
import openfoodfacts.github.scrachx.openfood.models.State;
@@ -37,6 +38,10 @@ import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
+import static openfoodfacts.github.scrachx.openfood.models.ProductImageField.FRONT;
+import static openfoodfacts.github.scrachx.openfood.models.ProductImageField.INGREDIENT;
+import static openfoodfacts.github.scrachx.openfood.models.ProductImageField.NUTRITION;
+
public class OpenFoodAPIClient {
private static final JacksonConverterFactory jacksonConverterFactory = JacksonConverterFactory.create();
@@ -293,44 +298,34 @@ public class OpenFoodAPIClient {
apiService.saveProduct(product.getBarcode(), product.getName(), product.getStores(), product.getUserId(), product.getPassword()).enqueue(new Callback<State>() {
@Override
public void onResponse(Call<State> call, Response<State> response) {
- if (!response.isSuccess()) {
+ if (!response.isSuccess() || response.body().getStatus() == 0) {
+ lt.error();
productSentCallback.onProductSentResponse(false);
return;
}
- long status = response.body().getStatus();
- if (status == 0) {
- String imguploadFront = product.getImgupload_front();
- if (!imguploadFront.isEmpty()) {
- ProductImage image = new ProductImage(product.getBarcode(), ProductImageField.FRONT, new File(imguploadFront));
- postImg(activity, image);
- }
-
- String imguploadIngredients = product.getImgupload_ingredients();
- if (!imguploadIngredients.isEmpty()) {
- ProductImage image = new ProductImage(product.getBarcode(), ProductImageField.INGREDIENT, new File(imguploadIngredients));
- postImg(activity, image);
- }
+ String imguploadFront = product.getImgupload_front();
+ ProductImage image = new ProductImage(product.getBarcode(), FRONT, new File(imguploadFront));
+ postImg(activity, image);
- String imguploadNutrition = product.getImgupload_nutrition();
- if (!imguploadNutrition.isEmpty()) {
- ProductImage image = new ProductImage(product.getBarcode(), ProductImageField.NUTRITION, new File(imguploadNutrition));
- postImg(activity, image);
- }
+ String imguploadIngredients = product.getImgupload_ingredients();
+ if (StringUtils.isNotEmpty(imguploadIngredients)) {
+ postImg(activity, new ProductImage(product.getBarcode(), INGREDIENT, new File(imguploadIngredients)));
+ }
- lt.error();
- productSentCallback.onProductSentResponse(false);
- } else {
- lt.success();
- productSentCallback.onProductSentResponse(true);
+ String imguploadNutrition = product.getImgupload_nutrition();
+ if (StringUtils.isNotBlank(imguploadNutrition)) {
+ postImg(activity, new ProductImage(product.getBarcode(), NUTRITION, new File(imguploadNutrition)));
}
+ lt.success();
+ productSentCallback.onProductSentResponse(true);
}
@Override
public void onFailure(Call<State> call, Throwable t) {
- productSentCallback.onProductSentResponse(false);
lt.error();
+ productSentCallback.onProductSentResponse(false);
}
});
}
diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/SaveProductOfflineActivity.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/SaveProductOfflineActivity.java
index 2c9796cc1..48e5d2506 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/SaveProductOfflineActivity.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/SaveProductOfflineActivity.java
@@ -25,6 +25,8 @@ import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.squareup.picasso.Picasso;
+import org.apache.commons.lang3.StringUtils;
+
import java.io.File;
import java.util.List;
@@ -116,6 +118,9 @@ public class SaveProductOfflineActivity extends BaseActivity {
int spinnerPosition = unitAdapter.getPosition(mProduct.getWeight_unit());
spinnerW.setSelection(spinnerPosition);
spinnerI.setSelection(0);
+ } else {
+ mProduct = new SendProduct();
+ mProduct.setBarcode(mBarcode);
}
}
@OnItemSelected(value = R.id.spinnerUnitWeight, callback = OnItemSelected.Callback.ITEM_SELECTED)
@@ -128,7 +133,7 @@ public class SaveProductOfflineActivity extends BaseActivity {
mImage[0] = spinnerI.getItemAtPosition(pos).toString();
if(pos == 0) {
- if(!mProduct.getImgupload_front().isEmpty()) {
+ if(StringUtils.isNotBlank(mProduct.getImgupload_front())) {
imgSave.setVisibility(View.VISIBLE);
Picasso.with(this)
.load(new File(mProduct.getImgupload_front()))
@@ -139,7 +144,7 @@ public class SaveProductOfflineActivity extends BaseActivity {
imgSave.setVisibility(View.GONE);
}
} else if(pos == 1) {
- if(!mProduct.getImgupload_nutrition().isEmpty()) {
+ if(StringUtils.isNotBlank(mProduct.getImgupload_nutrition())) {
imgSave.setVisibility(View.VISIBLE);
Picasso.with(this)
.load(new File(mProduct.getImgupload_nutrition()))
@@ -150,7 +155,7 @@ public class SaveProductOfflineActivity extends BaseActivity {
imgSave.setVisibility(View.GONE);
}
} else {
- if(!mProduct.getImgupload_ingredients().isEmpty()) {
+ if(StringUtils.isNotBlank(mProduct.getImgupload_ingredients())) {
imgSave.setVisibility(View.VISIBLE);
Picasso.with(this)
.load(new File(mProduct.getImgupload_ingredients()))
@@ -171,60 +176,62 @@ public class SaveProductOfflineActivity extends BaseActivity {
@OnClick(R.id.buttonSaveProduct)
protected void onSaveProduct() {
- if (!mProduct.getImgupload_front().isEmpty()) {
+ if (mProduct.getImgupload_front().isEmpty()) {
+ Toast.makeText(getApplicationContext(), R.string.txtPictureNeeded, Toast.LENGTH_LONG).show();
+ return;
+ }
- mProduct.setBarcode(mBarcode);
- mProduct.setName(name.getText().toString());
- mProduct.setWeight(weight.getText().toString());
- mProduct.setWeight_unit(mUnit[0]);
- mProduct.setStores(store.getText().toString());
-
- final SharedPreferences settingsUser = getSharedPreferences("login", 0);
- String login = settingsUser.getString("user", "");
- String password = settingsUser.getString("pass", "");
- if(!login.isEmpty() && !password.isEmpty()) {
- mProduct.setUserId(login);
- mProduct.setPassword(password);
- }
+ mProduct.setBarcode(mBarcode);
+ mProduct.setName(name.getText().toString());
+ mProduct.setWeight(weight.getText().toString());
+ mProduct.setWeight_unit(mUnit[0]);
+ mProduct.setStores(store.getText().toString());
+
+ final SharedPreferences settingsUser = getSharedPreferences("login", 0);
+ String login = settingsUser.getString("user", "");
+ String password = settingsUser.getString("pass", "");
+ if (!login.isEmpty() && !password.isEmpty()) {
+ mProduct.setUserId(login);
+ mProduct.setPassword(password);
+ }
+ Utils.compressImage(mProduct.getImgupload_front());
+
+ if (StringUtils.isNotBlank(mProduct.getImgupload_ingredients())) {
Utils.compressImage(mProduct.getImgupload_ingredients());
+ }
+
+ if(StringUtils.isNotBlank(mProduct.getImgupload_nutrition())) {
Utils.compressImage(mProduct.getImgupload_nutrition());
- Utils.compressImage(mProduct.getImgupload_front());
-
- ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
- boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
-
- if(isConnected) {
- api.post(this, mProduct, new OpenFoodAPIClient.OnProductSentCallback() {
- @Override
- public void onProductSentResponse(boolean value) {
- if(!value) {
- if (mProduct != null) {
- mProduct.save();
- }
- Toast.makeText(getApplicationContext(), R.string.txtDialogsContentInfoSave, Toast.LENGTH_LONG).show();
- } else {
- Toast.makeText(getApplicationContext(), R.string.product_sent, Toast.LENGTH_LONG).show();
- }
- Intent intent = new Intent(getApplicationContext(), MainActivity.class);
- intent.putExtra("openOfflineEdit",true);
- startActivity(intent);
- finish();
+ }
+
+ ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
+ NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
+ boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
+
+ if (isConnected) {
+ api.post(this, mProduct, new OpenFoodAPIClient.OnProductSentCallback() {
+ @Override
+ public void onProductSentResponse(boolean value) {
+ if (!value) {
+ mProduct.save();
+ Toast.makeText(getApplicationContext(), R.string.txtDialogsContentInfoSave, Toast.LENGTH_LONG).show();
+ } else {
+ Toast.makeText(getApplicationContext(), R.string.product_sent, Toast.LENGTH_LONG).show();
}
- });
- } else {
- if (mProduct != null) {
- mProduct.save();
+ Intent intent = new Intent(getApplicationContext(), MainActivity.class);
+ intent.putExtra("openOfflineEdit", true);
+ startActivity(intent);
+ finish();
}
- Toast.makeText(getApplicationContext(), R.string.txtDialogsContentInfoSave, Toast.LENGTH_LONG).show();
- Intent intent = new Intent(getApplicationContext(), MainActivity.class);
- intent.putExtra("openOfflineEdit",true);
- startActivity(intent);
- finish();
- }
+ });
} else {
- Toast.makeText(getApplicationContext(), R.string.txtPictureNeeded, Toast.LENGTH_LONG).show();
+ mProduct.save();
+ Toast.makeText(getApplicationContext(), R.string.txtDialogsContentInfoSave, Toast.LENGTH_LONG).show();
+ Intent intent = new Intent(getApplicationContext(), MainActivity.class);
+ intent.putExtra("openOfflineEdit", true);
+ startActivity(intent);
+ finish();
}
}
| ['app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java', 'app/src/main/java/openfoodfacts/github/scrachx/openfood/views/SaveProductOfflineActivity.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 287,234 | 57,728 | 9,365 | 52 | 8,599 | 1,416 | 154 | 2 | 128 | 23 | 26 | 1 | 0 | 0 | 1970-01-01T00:24:38 | 719 | Kotlin | {'Kotlin': 1463953, 'Java': 124506, 'Ruby': 13166, 'Shell': 543, 'Makefile': 241} | Apache License 2.0 |
602 | openfoodfacts/openfoodfacts-androidapp/137/86 | openfoodfacts | openfoodfacts-androidapp | https://github.com/openfoodfacts/openfoodfacts-androidapp/issues/86 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/137 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/137 | 1 | fix | Fields for which we have no data should not be shown (avoid displaying "null" as the value) | In the ingredients and nutrition tabs, if a product does not have data for some fields, then the value is shown as "null". For nutrition it becomes concatenated as "null (nullnull)"
| 3e564d69ff7519baa989e14a5e1c77bd59ef72ec | 6c696411d890383dfb1060db0bf6796231c79946 | https://github.com/openfoodfacts/openfoodfacts-androidapp/compare/3e564d69ff7519baa989e14a5e1c77bd59ef72ec...6c696411d890383dfb1060db0bf6796231c79946 | diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/NutritionProductFragment.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/NutritionProductFragment.java
index 3aa1d5c33..f927bc5bc 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/NutritionProductFragment.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/NutritionProductFragment.java
@@ -4,17 +4,21 @@ import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
+import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
+
import java.util.ArrayList;
+
import butterknife.BindView;
import openfoodfacts.github.scrachx.openfood.R;
import openfoodfacts.github.scrachx.openfood.models.NutrientLevelItem;
import openfoodfacts.github.scrachx.openfood.models.NutrientLevels;
+import openfoodfacts.github.scrachx.openfood.models.Product;
import openfoodfacts.github.scrachx.openfood.models.State;
import openfoodfacts.github.scrachx.openfood.views.adapters.NutrientLevelListAdapter;
@@ -36,68 +40,89 @@ public class NutritionProductFragment extends BaseFragment {
Intent intent = getActivity().getIntent();
State state = (State) intent.getExtras().getSerializable("state");
- NutrientLevels nt = state.getProduct().getNutrientLevels();
- ArrayList<NutrientLevelItem> levelItem;
- NutrientLevelListAdapter adapter;
-
- if (nt == null) {
- levelItem = new ArrayList<>();
+ final Product product = state.getProduct();
+ NutrientLevels nt = product.getNutrientLevels();
+ ArrayList<NutrientLevelItem> levelItem = new ArrayList<>();
+
+ if (nt == null || (nt.getFat() == null && nt.getSalt() == null
+ && nt.getSaturatedFat() == null && nt.getSugars() == null)) {
levelItem.add(new NutrientLevelItem(getString(R.string.txtNoData), R.drawable.error_image));
- adapter = new NutrientLevelListAdapter(getContext(), levelItem);
- lv.setAdapter(adapter);
} else {
- String saltTxt = Html.fromHtml("<b>" + getString(R.string.txtSalt) + "</b>" + ' ' + nt.getSalt() + " (" + state.getProduct().getNutriments().getSalt100g() + state.getProduct().getNutriments().getSaltUnit() + ")").toString();
- String fatTxt = Html.fromHtml("<b>" + getString(R.string.txtFat) + "</b>" + ' ' + nt.getFat() + " (" + state.getProduct().getNutriments().getFat100g() + state.getProduct().getNutriments().getFatUnit() + ")").toString();
- String sugarsTxt = Html.fromHtml("<b>" + getString(R.string.txtSugars) + "</b>" + ' ' + nt.getSugars() + " (" + state.getProduct().getNutriments().getSugars100g() + state.getProduct().getNutriments().getSugarsUnit() + ")").toString();
- String saturatedFatTxt = Html.fromHtml("<b>" + getString(R.string.txtSaturatedFat) + "</b>" + ' ' + nt.getSaturatedFat() + " (" + state.getProduct().getNutriments().getSaturatedFat100g() + state.getProduct().getNutriments().getSaturatedFatUnit() + ")").toString();
-
- String saltImg = nt.getSalt();
- String fatImg = nt.getFat();
- String sugarsImg = nt.getSugars();
- String saturatedFatImg = nt.getSaturatedFat();
-
- levelItem = new ArrayList<>();
- levelItem.add(new NutrientLevelItem(saltTxt, getImageLevel(saltImg)));
- levelItem.add(new NutrientLevelItem(fatTxt, getImageLevel(fatImg)));
- levelItem.add(new NutrientLevelItem(sugarsTxt, getImageLevel(sugarsImg)));
- levelItem.add(new NutrientLevelItem(saturatedFatTxt, getImageLevel(saturatedFatImg)));
-
- adapter = new NutrientLevelListAdapter(getContext(), levelItem);
- lv.setAdapter(adapter);
- img.setImageResource(getImageGrade(state.getProduct().getNutritionGradeFr()));
+ String saltTxt = Html.fromHtml("<b>" + getString(R.string.txtSalt) + "</b>" + ' ' + nt.getSalt() + " (" + product.getNutriments().getSalt100g() + product.getNutriments().getSaltUnit() + ")").toString();
+ String fatTxt = Html.fromHtml("<b>" + getString(R.string.txtFat) + "</b>" + ' ' + nt.getFat() + " (" + product.getNutriments().getFat100g() + product.getNutriments().getFatUnit() + ")").toString();
+ String sugarsTxt = Html.fromHtml("<b>" + getString(R.string.txtSugars) + "</b>" + ' ' + nt.getSugars() + " (" + product.getNutriments().getSugars100g() + product.getNutriments().getSugarsUnit() + ")").toString();
+ String saturatedFatTxt = Html.fromHtml("<b>" + getString(R.string.txtSaturatedFat) + "</b>" + ' ' + nt.getSaturatedFat() + " (" + product.getNutriments().getSaturatedFat100g() + product.getNutriments().getSaturatedFatUnit() + ")").toString();
+
+ levelItem.add(new NutrientLevelItem(saltTxt, getImageLevel(nt.getSalt())));
+ levelItem.add(new NutrientLevelItem(fatTxt, getImageLevel(nt.getFat())));
+ levelItem.add(new NutrientLevelItem(sugarsTxt, getImageLevel(nt.getSugars())));
+ levelItem.add(new NutrientLevelItem(saturatedFatTxt, getImageLevel(nt.getSaturatedFat())));
+
+ img.setImageResource(getImageGrade(product.getNutritionGradeFr()));
}
- serving.setText(Html.fromHtml("<b>" + getString(R.string.txtServingSize) + "</b>" + ' ' + state.getProduct().getServingSize()));
+ lv.setAdapter(new NutrientLevelListAdapter(getContext(), levelItem));
+
+ String servingSize = product.getServingSize();
+ if (TextUtils.isEmpty(servingSize)) {
+ servingSize = getString(R.string.txtNoData);
+ }
+ serving.setText(Html.fromHtml("<b>" + getString(R.string.txtServingSize) + "</b>" + ' ' + servingSize));
}
private int getImageGrade(String grade) {
- if (grade != null) {
- grade.toLowerCase();
- if (grade.compareToIgnoreCase("a") == 0) {
- return R.drawable.nnc_a;
- } else if (grade.compareToIgnoreCase("b") == 0) {
- return R.drawable.nnc_b;
- } else if (grade.compareToIgnoreCase("c") == 0) {
- return R.drawable.nnc_c;
- } else if (grade.compareToIgnoreCase("d") == 0) {
- return R.drawable.nnc_d;
- } else if (grade.compareToIgnoreCase("e") == 0) {
- return R.drawable.nnc_e;
- }
+ int drawable;
+
+ if (grade == null) {
+ return R.drawable.ic_error;
}
- return R.drawable.ic_error;
+
+ switch (grade.toLowerCase()) {
+ case "a":
+ drawable = R.drawable.nnc_a;
+ break;
+ case "b":
+ drawable = R.drawable.nnc_b;
+ break;
+ case "c":
+ drawable = R.drawable.nnc_c;
+ break;
+ case "d":
+ drawable = R.drawable.nnc_d;
+ break;
+ case "e":
+ drawable = R.drawable.nnc_e;
+ break;
+ default:
+ drawable = R.drawable.ic_error;
+ break;
+ }
+
+ return drawable;
}
private int getImageLevel(String nutrient) {
- if (nutrient != null) {
- if (nutrient.compareToIgnoreCase("moderate") == 0) {
- return R.drawable.ic_circle_yellow;
- } else if (nutrient.compareToIgnoreCase("low") == 0) {
- return R.drawable.ic_circle_green;
- } else if (nutrient.compareToIgnoreCase("high") == 0) {
- return R.drawable.ic_circle_red;
- }
+ int drawable;
+
+ if (nutrient == null) {
+ return R.drawable.ic_error;
}
- return R.drawable.ic_error;
+
+ switch (nutrient.toLowerCase()) {
+ case "moderate":
+ drawable = R.drawable.ic_circle_yellow;
+ break;
+ case "low":
+ drawable = R.drawable.ic_circle_green;
+ break;
+ case "high":
+ drawable = R.drawable.ic_circle_red;
+ break;
+ default:
+ drawable = R.drawable.ic_error;
+ break;
+ }
+
+ return drawable;
}
}
diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/models/NutrientLevelItem.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/models/NutrientLevelItem.java
index cbf8dafaf..3b2a64c46 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/models/NutrientLevelItem.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/models/NutrientLevelItem.java
@@ -2,17 +2,14 @@ package openfoodfacts.github.scrachx.openfood.models;
public class NutrientLevelItem {
- private String title;
- private int icon;
-
- public NutrientLevelItem(){}
+ private final String title;
+ private final int icon;
public NutrientLevelItem(String title, int icon){
this.title = title;
this.icon = icon;
}
-
public String getTitle(){
return this.title;
}
@@ -21,12 +18,4 @@ public class NutrientLevelItem {
return this.icon;
}
- public void setTitle(String title){
- this.title = title;
- }
-
- public void setIcon(int icon){
- this.icon = icon;
- }
-
}
diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/adapters/NutrientLevelListAdapter.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/adapters/NutrientLevelListAdapter.java
index b00000404..522ccbf35 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/adapters/NutrientLevelListAdapter.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/adapters/NutrientLevelListAdapter.java
@@ -1,6 +1,5 @@
package openfoodfacts.github.scrachx.openfood.views.adapters;
-import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
@@ -9,13 +8,17 @@ import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
+
+import java.util.ArrayList;
+import java.util.List;
+
import openfoodfacts.github.scrachx.openfood.R;
import openfoodfacts.github.scrachx.openfood.models.NutrientLevelItem;
public class NutrientLevelListAdapter extends BaseAdapter {
private Context context;
- private ArrayList<NutrientLevelItem> nutrientLevelItems;
+ private List<NutrientLevelItem> nutrientLevelItems;
public NutrientLevelListAdapter(Context context, ArrayList<NutrientLevelItem> navDrawerItems){
this.context = context; | ['app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/NutritionProductFragment.java', 'app/src/main/java/openfoodfacts/github/scrachx/openfood/models/NutrientLevelItem.java', 'app/src/main/java/openfoodfacts/github/scrachx/openfood/views/adapters/NutrientLevelListAdapter.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 283,680 | 57,505 | 9,210 | 43 | 7,378 | 1,626 | 149 | 3 | 182 | 31 | 39 | 2 | 0 | 0 | 1970-01-01T00:24:35 | 719 | Kotlin | {'Kotlin': 1463953, 'Java': 124506, 'Ruby': 13166, 'Shell': 543, 'Makefile': 241} | Apache License 2.0 |
599 | openfoodfacts/openfoodfacts-androidapp/350/335 | openfoodfacts | openfoodfacts-androidapp | https://github.com/openfoodfacts/openfoodfacts-androidapp/issues/335 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/350 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/350 | 1 | closes | Weight does not seem to go through on new products | Steps to reproduce:
- Send new product with units and value
Result:
- No units nor value stored. | e5218a1372a394a39d2933ee0ff0a072b72628f5 | 99c74d325a51954d8169467ea871f78bbb253ae9 | https://github.com/openfoodfacts/openfoodfacts-androidapp/compare/e5218a1372a394a39d2933ee0ff0a072b72628f5...99c74d325a51954d8169467ea871f78bbb253ae9 | diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java
index 00ab17275..c735286b4 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java
@@ -210,7 +210,7 @@ public class OpenFoodAPIClient {
lt.setTextColor(activity.getResources().getColor(R.color.white));
lt.show();
- apiService.saveProduct(product.getBarcode(), product.getName(), product.getBrands(), product.getUserId(), product.getPassword(), PRODUCT_API_COMMENT).enqueue(new Callback<State>() {
+ apiService.saveProduct(product.getBarcode(), product.getName(), product.getBrands(), product.getQuantity(), product.getUserId(), product.getPassword(), PRODUCT_API_COMMENT).enqueue(new Callback<State>() {
@Override
public void onResponse(Call<State> call, Response<State> response) {
if (!response.isSuccess() || response.body().getStatus() == 0) {
diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIService.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIService.java
index 6a83d310b..246c18610 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIService.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIService.java
@@ -49,6 +49,7 @@ public interface OpenFoodAPIService {
Call<State> saveProduct(@Query("code") String code,
@Query("product_name") String name,
@Query("brands") String brands,
+ @Query("quantity") String quantity,
@Query("user_id") String login,
@Query("password") String password,
@Query("comment") String comment);
diff --git a/app/src/test/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIServiceTest.java b/app/src/test/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIServiceTest.java
index 81baf5a47..720617eb9 100644
--- a/app/src/test/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIServiceTest.java
+++ b/app/src/test/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIServiceTest.java
@@ -221,9 +221,11 @@ public class OpenFoodAPIServiceTest {
product.setBarcode("978020137962");
product.setName("coca");
product.setBrands("auchan");
+ product.setWeight("300");
+ product.setWeight_unit("g");
// Response<State> execute = serviceWrite.saveProduct(product).execute();
- Response<State> execute = serviceWrite.saveProduct(product.getBarcode(), product.getName(), product.getBrands(), null, null, PRODUCT_API_COMMENT).execute();
+ Response<State> execute = serviceWrite.saveProduct(product.getBarcode(), product.getName(), product.getBrands(), product.getQuantity(), null, null, PRODUCT_API_COMMENT).execute();
assertTrue(execute.isSuccess());
@@ -236,6 +238,7 @@ public class OpenFoodAPIServiceTest {
assertEquals(product.getName(), savedProduct.getProductName());
assertEquals(product.getBrands(), savedProduct.getBrands());
assertTrue(savedProduct.getBrandsTags().contains(product.getBrands()));
+ assertEquals(product.getWeight() + " " + product.getWeight_unit(), savedProduct.getQuantity());
}
@Test | ['app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java', 'app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIService.java', 'app/src/test/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIServiceTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 371,513 | 78,145 | 12,457 | 63 | 468 | 79 | 3 | 2 | 107 | 18 | 24 | 7 | 0 | 0 | 1970-01-01T00:24:42 | 719 | Kotlin | {'Kotlin': 1463953, 'Java': 124506, 'Ruby': 13166, 'Shell': 543, 'Makefile': 241} | Apache License 2.0 |
592 | openfoodfacts/openfoodfacts-androidapp/1560/1060 | openfoodfacts | openfoodfacts-androidapp | https://github.com/openfoodfacts/openfoodfacts-androidapp/issues/1060 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/1560 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/1560 | 1 | closes | java.lang.IllegalStateException android.widget.RelativeLayout$DependencyGraph.getSortedViews | Yesterday, 11:16 PM on app version 40
OnePlus One (A0001), 3072MB RAM, Android 6.0
Report 1 of 1
java.lang.IllegalStateException:
at android.widget.RelativeLayout$DependencyGraph.getSortedViews (RelativeLayout.java:1724)
at android.widget.RelativeLayout.sortChildren (RelativeLayout.java:382)
at android.widget.RelativeLayout.onMeasure (RelativeLayout.java:389)
at android.view.View.measure (View.java:18799)
at android.widget.ListView.setupChild (ListView.java:1958)
at android.widget.ListView.makeAndAddView (ListView.java:1879)
at android.widget.ListView.fillDown (ListView.java:702)
at android.widget.ListView.fillFromTop (ListView.java:763)
at android.widget.ListView.layoutChildren (ListView.java:1685)
at android.widget.AbsListView.onLayout (AbsListView.java:2148)
at android.view.View.layout (View.java:16639)
at android.view.ViewGroup.layout (ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame (LinearLayout.java:1735)
at android.widget.LinearLayout.layoutVertical (LinearLayout.java:1579)
at android.widget.LinearLayout.onLayout (LinearLayout.java:1488)
at android.view.View.layout (View.java:16639)
at android.view.ViewGroup.layout (ViewGroup.java:5437)
at android.support.constraint.ConstraintLayout.onLayout (ConstraintLayout.java:1197)
at android.view.View.layout (View.java:16639)
at android.view.ViewGroup.layout (ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren (FrameLayout.java:336)
at android.widget.FrameLayout.onLayout (FrameLayout.java:273)
at android.view.View.layout (View.java:16639)
at android.view.ViewGroup.layout (ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame (LinearLayout.java:1735)
at android.widget.LinearLayout.layoutVertical (LinearLayout.java:1579)
at android.widget.LinearLayout.onLayout (LinearLayout.java:1488)
at android.view.View.layout (View.java:16639)
at android.view.ViewGroup.layout (ViewGroup.java:5437)
at android.support.v4.widget.DrawerLayout.onLayout (DrawerLayout.java:1172)
at android.view.View.layout (View.java:16639)
at android.view.ViewGroup.layout (ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren (FrameLayout.java:336)
at android.widget.FrameLayout.onLayout (FrameLayout.java:273)
at android.view.View.layout (View.java:16639)
at android.view.ViewGroup.layout (ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame (LinearLayout.java:1735)
at android.widget.LinearLayout.layoutVertical (LinearLayout.java:1579)
at android.widget.LinearLayout.onLayout (LinearLayout.java:1488)
at android.view.View.layout (View.java:16639)
at android.view.ViewGroup.layout (ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren (FrameLayout.java:336)
at android.widget.FrameLayout.onLayout (FrameLayout.java:273)
at android.view.View.layout (View.java:16639)
at android.view.ViewGroup.layout (ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame (LinearLayout.java:1735)
at android.widget.LinearLayout.layoutVertical (LinearLayout.java:1579)
at android.widget.LinearLayout.onLayout (LinearLayout.java:1488)
at android.view.View.layout (View.java:16639)
at android.view.ViewGroup.layout (ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren (FrameLayout.java:336)
at android.widget.FrameLayout.onLayout (FrameLayout.java:273)
at com.android.internal.policy.PhoneWindow$DecorView.onLayout (PhoneWindow.java:2934)
at android.view.View.layout (View.java:16639)
at android.view.ViewGroup.layout (ViewGroup.java:5437)
at android.view.ViewRootImpl.performLayout (ViewRootImpl.java:2179)
at android.view.ViewRootImpl.performTraversals (ViewRootImpl.java:1939)
at android.view.ViewRootImpl.doTraversal (ViewRootImpl.java:1115)
at android.view.ViewRootImpl$TraversalRunnable.run (ViewRootImpl.java:6023)
at android.view.Choreographer$CallbackRecord.run (Choreographer.java:858)
at android.view.Choreographer.doCallbacks (Choreographer.java:670)
at android.view.Choreographer.doFrame (Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run (Choreographer.java:844)
at android.os.Handler.handleCallback (Handler.java:739)
at android.os.Handler.dispatchMessage (Handler.java:95)
at android.os.Looper.loop (Looper.java:148)
at android.app.ActivityThread.main (ActivityThread.java:5461)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:616) | 8b73d9e31ffed901b8f4e998f70af3534e487e10 | 976d049c64b0ffa72b31aa7642cbd95380e18f9d | https://github.com/openfoodfacts/openfoodfacts-androidapp/compare/8b73d9e31ffed901b8f4e998f70af3534e487e10...976d049c64b0ffa72b31aa7642cbd95380e18f9d | diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/product/ingredients/IngredientsProductFragment.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/product/ingredients/IngredientsProductFragment.java
index 7c44ae1bc..b971a4847 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/product/ingredients/IngredientsProductFragment.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/product/ingredients/IngredientsProductFragment.java
@@ -155,10 +155,8 @@ public class IngredientsProductFragment extends BaseFragment implements IIngredi
super.refreshView(state);
mState = state;
- try {
+ if(getArguments()!=null){
mSendProduct = (SendProduct) getArguments().getSerializable("sendProduct");
- } catch (NullPointerException e) {
- e.printStackTrace();
}
mAdditiveDao = Utils.getAppDaoSession(getActivity()).getAdditiveDao(); | ['app/src/main/java/openfoodfacts/github/scrachx/openfood/views/product/ingredients/IngredientsProductFragment.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 743,997 | 142,532 | 20,532 | 154 | 127 | 22 | 4 | 1 | 4,676 | 230 | 1,098 | 74 | 0 | 0 | 1970-01-01T00:25:25 | 719 | Kotlin | {'Kotlin': 1463953, 'Java': 124506, 'Ruby': 13166, 'Shell': 543, 'Makefile': 241} | Apache License 2.0 |
597 | openfoodfacts/openfoodfacts-androidapp/533/512 | openfoodfacts | openfoodfacts-androidapp | https://github.com/openfoodfacts/openfoodfacts-androidapp/issues/512 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/533 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/533 | 1 | closes | Uploaded images are not attributed to the user | Uploaded images are not attributed to the user
```
5 mars 2017 à 19:09:12 CET - Images sélectionnées (Ajout : front_en) - new image nutrition_en : 2.4 - voir
5 mars 2017 à 19:09:12 CET - openfoodfacts-contributors Images téléchargées (Ajout : 2) - new image 2 - image upload - voir
5 mars 2017 à 19:09:12 CET - openfoodfacts-contributors Images téléchargées (Ajout : 1) - new image 1 - image upload - voir
5 mars 2017 à 19:09:06 CET - sebleouf Informations (Ajout : lang, product_name, quantity, countries, nutrition_data_per) - (app)new android app - voir``` | d8303fa5cbd06acd8f72fb4f2a328a50160d7a02 | 106e6cde6275a1edf517053961fc1afb06908a81 | https://github.com/openfoodfacts/openfoodfacts-androidapp/compare/d8303fa5cbd06acd8f72fb4f2a328a50160d7a02...106e6cde6275a1edf517053961fc1afb06908a81 | diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java
index 950460a61..39ea7b1ed 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java
@@ -6,7 +6,6 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
-import android.support.annotation.NonNull;
import android.support.v7.preference.PreferenceManager;
import android.text.Html;
import android.view.View;
@@ -31,6 +30,7 @@ import java.util.Map;
import java.util.concurrent.TimeUnit;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
+import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import openfoodfacts.github.scrachx.openfood.BuildConfig;
@@ -368,6 +368,16 @@ public class OpenFoodAPIClient {
imgMap.put("imgupload_nutrition\\"; filename=\\"nutrition_" + lang + ".png\\"", image.getImguploadNutrition());
imgMap.put("imgupload_other\\"; filename=\\"other_" + lang + ".png\\"", image.getImguploadOther());
+ // Attribute the upload to the connected user
+ final SharedPreferences settings = context.getSharedPreferences("login", 0);
+ final String login = settings.getString("user", "");
+ final String password = settings.getString("pass", "");
+
+ if (!login.isEmpty() && !password.isEmpty()) {
+ imgMap.put("user_id", RequestBody.create(MediaType.parse("text/plain"), login));
+ imgMap.put("password", RequestBody.create(MediaType.parse("text/plain"), password));
+ }
+
apiService.saveImage(imgMap)
.enqueue(new Callback<JsonNode>() {
@Override | ['app/src/main/java/openfoodfacts/github/scrachx/openfood/network/OpenFoodAPIClient.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 316,717 | 61,148 | 8,688 | 70 | 601 | 108 | 12 | 1 | 564 | 95 | 177 | 6 | 0 | 1 | 1970-01-01T00:24:50 | 719 | Kotlin | {'Kotlin': 1463953, 'Java': 124506, 'Ruby': 13166, 'Shell': 543, 'Makefile': 241} | Apache License 2.0 |
594 | openfoodfacts/openfoodfacts-androidapp/743/468 | openfoodfacts | openfoodfacts-androidapp | https://github.com/openfoodfacts/openfoodfacts-androidapp/issues/468 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/743 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/743 | 1 | fix | Add spaces after commas in Product View | Add spaces after commas in Product View
- Packaging
- Manufacturing Places
- Purchase place
Check that all fields have proper spaces after commas, so that we're consistant across fields. | 51ef2bbc1c8ee13bd7d3be8a9281cf662f469eb7 | 57d21d61d766afa48c802d402089cdcafcca2e51 | https://github.com/openfoodfacts/openfoodfacts-androidapp/compare/51ef2bbc1c8ee13bd7d3be8a9281cf662f469eb7...57d21d61d766afa48c802d402089cdcafcca2e51 | diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/SearchProductsResultsFragment.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/SearchProductsResultsFragment.java
index 956615d9d..c486737c6 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/SearchProductsResultsFragment.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/SearchProductsResultsFragment.java
@@ -10,6 +10,7 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
+import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
@@ -156,7 +157,6 @@ public class SearchProductsResultsFragment extends BaseFragment {
public void loadNextDataFromApi(int offset) {
api.searchProduct(getArguments().getString("query"), offset, getActivity(),
new OpenFoodAPIClient.OnProductsCallback() {
-
@Override
public void onProductsResponse(boolean isResponseOk, List<Product> products, int countProducts) {
final int posStart = mProducts.size();
diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/models/Product.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/models/Product.java
index e27303ff3..f40dd0b1d 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/models/Product.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/models/Product.java
@@ -269,7 +269,7 @@ public class Product implements Serializable {
* @return The stores
*/
public String getStores() {
- return stores;
+ return stores.replace(",",", ");
}
@@ -293,7 +293,7 @@ public class Product implements Serializable {
* @return The countries
*/
public String getCountries() {
- return countries;
+ return countries.replace(",",", ");
}
@@ -301,7 +301,7 @@ public class Product implements Serializable {
* @return The brands
*/
public String getBrands() {
- return brands;
+ return brands.replace(",", ", ");
}
@@ -309,7 +309,7 @@ public class Product implements Serializable {
* @return The packaging
*/
public String getPackaging() {
- return packaging;
+ return packaging.replace(",",", ");
}
| ['app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/SearchProductsResultsFragment.java', 'app/src/main/java/openfoodfacts/github/scrachx/openfood/models/Product.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 353,113 | 67,984 | 9,755 | 92 | 307 | 49 | 10 | 2 | 193 | 30 | 38 | 6 | 0 | 0 | 1970-01-01T00:25:18 | 719 | Kotlin | {'Kotlin': 1463953, 'Java': 124506, 'Ruby': 13166, 'Shell': 543, 'Makefile': 241} | Apache License 2.0 |
598 | openfoodfacts/openfoodfacts-androidapp/381/380 | openfoodfacts | openfoodfacts-androidapp | https://github.com/openfoodfacts/openfoodfacts-androidapp/issues/380 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/381 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/381 | 1 | closes | CRASH when clicking on deleted product | This happens in the product history when clicking on a deleted product.
```
01-02 13:55:58.344 17934-17934/openfoodfacts.github.scrachx.openfood E/AndroidRuntime: FATAL EXCEPTION: main
Process: openfoodfacts.github.scrachx.openfood, PID: 17934
java.lang.StringIndexOutOfBoundsException: length=13; index=-1
at java.lang.String.indexAndLength(String.java:294)
at java.lang.String.substring(String.java:1067)
at openfoodfacts.github.scrachx.openfood.fragments.IngredientsProductFragment.onViewCreated(IngredientsProductFragment.java:78)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1132)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1295)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1643)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:166)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1272)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1646)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18794)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
at android.view.View.measure(View.java:18794)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
``` | 88d591d9fbbba6186024523851559301467148c0 | 41dc6a702bd6c7a27c66dd3276f9ee4975c4acb4 | https://github.com/openfoodfacts/openfoodfacts-androidapp/compare/88d591d9fbbba6186024523851559301467148c0...41dc6a702bd6c7a27c66dd3276f9ee4975c4acb4 | diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/IngredientsProductFragment.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/IngredientsProductFragment.java
index 9e6099f12..82729998b 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/IngredientsProductFragment.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/IngredientsProductFragment.java
@@ -1,6 +1,7 @@
package openfoodfacts.github.scrachx.openfood.fragments;
import android.content.Intent;
+import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
@@ -73,10 +74,10 @@ public class IngredientsProductFragment extends BaseFragment {
}
if(mState != null && product.getIngredientsText() != null) {
- SpannableStringBuilder txtIngredients = new SpannableStringBuilder(Html.fromHtml(product.getIngredientsText().replace("_","")));
- txtIngredients = setSpanBoldBetweenTokens(txtIngredients);
- if(!txtIngredients.toString().substring(txtIngredients.toString().indexOf(":")).trim().isEmpty()) {
- ingredientsProduct.setText(txtIngredients);
+ String txtIngredients = product.getIngredientsText().replace("_","").trim();
+ if(!txtIngredients.isEmpty()) {
+ String ingredientsValue = setSpanBoldBetweenTokens(txtIngredients).toString();
+ ingredientsProduct.setText(ingredientsValue);
} else {
ingredientsProduct.setVisibility(View.GONE);
}
@@ -167,7 +168,7 @@ public class IngredientsProductFragment extends BaseFragment {
final String tm = m.group();
for (String l: cleanAllergensMultipleOccurrences()) {
if(l.equalsIgnoreCase(tm.replaceAll("[(),.-]+", ""))) {
- StyleSpan bold = new StyleSpan(android.graphics.Typeface.BOLD);
+ StyleSpan bold = new StyleSpan(Typeface.BOLD);
if(tm.contains("(")) {
ssb.setSpan(bold, m.start()+1, m.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if(tm.contains(")")) { | ['app/src/main/java/openfoodfacts/github/scrachx/openfood/fragments/IngredientsProductFragment.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 349,887 | 72,990 | 11,558 | 63 | 869 | 141 | 11 | 1 | 9,303 | 139 | 1,021 | 62 | 0 | 1 | 1970-01-01T00:24:43 | 719 | Kotlin | {'Kotlin': 1463953, 'Java': 124506, 'Ruby': 13166, 'Shell': 543, 'Makefile': 241} | Apache License 2.0 |
593 | openfoodfacts/openfoodfacts-androidapp/949/948 | openfoodfacts | openfoodfacts-androidapp | https://github.com/openfoodfacts/openfoodfacts-androidapp/issues/948 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/949 | https://github.com/openfoodfacts/openfoodfacts-androidapp/pull/949 | 1 | fixed | Back button closes the activity in fragments | **Checklist**
- [x] Bug Report - The issue you are reporting might be there already. Please search on the [issues tracker](https://github.com/openfoodfacts/openfoodfacts-androidapp/issues) before creating or reporting a issue.
- [x] Before reporting, please ensure (if you can) that you have tested it with the latest (dev) version of the software.
- [x] Don't forget to tag your issue, it makes it easier to discover.
**Summary:**
Back button closes the activity instead of going back to Home. Examples:
- Search by barcode
- Allergen alert
- Preferences
- Offline edit
**Steps to reproduce:**
Go to the section. Press back button.
**Expected behavior:**
Go to home
**Observed behavior:**
Activity closes | b65cb54504053f98f54ab0c4ef1ae94da89f9692 | ef37b7fae9f7259bcf4389549a2eb6544e1d8f44 | https://github.com/openfoodfacts/openfoodfacts-androidapp/compare/b65cb54504053f98f54ab0c4ef1ae94da89f9692...ef37b7fae9f7259bcf4389549a2eb6544e1d8f44 | diff --git a/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/MainActivity.java b/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/MainActivity.java
index 75eabfab3..7317c19ad 100644
--- a/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/MainActivity.java
+++ b/app/src/main/java/openfoodfacts/github/scrachx/openfood/views/MainActivity.java
@@ -172,7 +172,8 @@ public class MainActivity extends BaseActivity implements CustomTabActivityHelpe
}
@Override
- public void onDrawerClosed(View drawerView) {}
+ public void onDrawerClosed(View drawerView) {
+ }
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
@@ -295,7 +296,7 @@ public class MainActivity extends BaseActivity implements CustomTabActivityHelpe
}
if (fragment != null) {
- getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
+ getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).addToBackStack(null).commit();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment"); | ['app/src/main/java/openfoodfacts/github/scrachx/openfood/views/MainActivity.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 411,643 | 78,994 | 11,347 | 102 | 428 | 58 | 5 | 1 | 743 | 107 | 168 | 25 | 1 | 0 | 1970-01-01T00:25:19 | 719 | Kotlin | {'Kotlin': 1463953, 'Java': 124506, 'Ruby': 13166, 'Shell': 543, 'Makefile': 241} | Apache License 2.0 |
9,235 | apache/hop/2158/2156 | apache | hop | https://github.com/apache/hop/issues/2156 | https://github.com/apache/hop/pull/2158 | https://github.com/apache/hop/pull/2158 | 1 | fix | [Bug]: Unable to insert a variable in Write to log action with Ctrl+Space | ### Apache Hop version?
2.3
### Java version?
11
### Operating system
Windows
### What happened?
Unable to insert a variable in Write to log action with Ctrl+Space in widget "Log Message".
Ctrl+Space work in "Log subject" but not in "Log message"
### Issue Priority
Priority: 3
### Issue Component
Component: Actions | a1e5923d176b27c34b9d91566b2e0dec47c2cfac | a4271b083668728a1ab8dd109e5e6ced67eac9db | https://github.com/apache/hop/compare/a1e5923d176b27c34b9d91566b2e0dec47c2cfac...a4271b083668728a1ab8dd109e5e6ced67eac9db | diff --git a/plugins/actions/writetolog/src/main/java/org/apache/hop/workflow/actions/writetolog/ActionWriteToLogDialog.java b/plugins/actions/writetolog/src/main/java/org/apache/hop/workflow/actions/writetolog/ActionWriteToLogDialog.java
index c3c2a8504e..de536b6a1d 100644
--- a/plugins/actions/writetolog/src/main/java/org/apache/hop/workflow/actions/writetolog/ActionWriteToLogDialog.java
+++ b/plugins/actions/writetolog/src/main/java/org/apache/hop/workflow/actions/writetolog/ActionWriteToLogDialog.java
@@ -26,7 +26,6 @@ import org.apache.hop.i18n.BaseMessages;
import org.apache.hop.ui.core.PropsUi;
import org.apache.hop.ui.core.dialog.BaseDialog;
import org.apache.hop.ui.core.dialog.MessageBox;
-import org.apache.hop.ui.core.widget.ControlSpaceKeyAdapter;
import org.apache.hop.ui.core.widget.TextVar;
import org.apache.hop.ui.pipeline.transform.BaseTransformDialog;
import org.apache.hop.ui.workflow.action.ActionDialog;
@@ -167,7 +166,7 @@ public class ActionWriteToLogDialog extends ActionDialog implements IActionDialo
fdlLogMessage.top = new FormAttachment(wLogSubject, margin);
fdlLogMessage.right = new FormAttachment(middle, -margin);
wlLogMessage.setLayoutData(fdlLogMessage);
-
+
wLogMessage =
new TextVar(
variables, shell, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
@@ -180,7 +179,6 @@ public class ActionWriteToLogDialog extends ActionDialog implements IActionDialo
fdLogMessage.right = new FormAttachment(100, 0);
fdLogMessage.bottom = new FormAttachment(wOk, -margin);
wLogMessage.setLayoutData(fdLogMessage);
- wLogMessage.addKeyListener(new ControlSpaceKeyAdapter(variables, wLogMessage));
getData();
| ['plugins/actions/writetolog/src/main/java/org/apache/hop/workflow/actions/writetolog/ActionWriteToLogDialog.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 28,142,074 | 6,207,724 | 820,608 | 2,965 | 152 | 32 | 4 | 1 | 328 | 52 | 78 | 24 | 0 | 0 | 1970-01-01T00:27:53 | 713 | Java | {'Java': 33345733, 'CSS': 119561, 'Shell': 69068, 'Batchfile': 30359, 'JavaScript': 18221, 'Dockerfile': 7044, 'HTML': 7032, 'Smarty': 4587, 'Vim Snippet': 3904, 'XSLT': 1043} | Apache License 2.0 |
1,367 | bazelbuild/intellij/4062/4013 | bazelbuild | intellij | https://github.com/bazelbuild/intellij/issues/4013 | https://github.com/bazelbuild/intellij/pull/4062 | https://github.com/bazelbuild/intellij/pull/4062 | 1 | fix | Error debugging py_binary: "More than 1 executable was produced when building don't know which one to debug" | #### Description of the issue. Please be specific.
I have a bazel repo with simple python app and lib projects. I can run my app.py file using right-click run. When I try to debug, I get failure popup on the debug tab that says "More than 1 executable was produced when building don't know which one to debug"
Not clear what other executable it is referring to?
I wonder if its because it produces a exe and zip file for the py_binary, which is default behaviour for windows , no?
```
Target //projects/appA:main up-to-date:
bazel-bin/projects/appA/main.exe
bazel-bin/projects/appA/main.zip
```
#### Version information
IdeaUltimate: 2022.1.2
Platform: Windows 10 10.0
Bazel plugin: 2022.09.20.0.1-api-version-221
Bazel: 5.3.1
| a7fc9ecd32eb0ba15f54be66737ee94f2f0dbfdd | 9f992bd1c60a71ec5dab12e0d884e00c8e36e23c | https://github.com/bazelbuild/intellij/compare/a7fc9ecd32eb0ba15f54be66737ee94f2f0dbfdd...9f992bd1c60a71ec5dab12e0d884e00c8e36e23c | diff --git a/python/src/com/google/idea/blaze/python/run/BlazePyRunConfigurationRunner.java b/python/src/com/google/idea/blaze/python/run/BlazePyRunConfigurationRunner.java
index 7e512549e..7f0b26252 100644
--- a/python/src/com/google/idea/blaze/python/run/BlazePyRunConfigurationRunner.java
+++ b/python/src/com/google/idea/blaze/python/run/BlazePyRunConfigurationRunner.java
@@ -391,7 +391,12 @@ public class BlazePyRunConfigurationRunner implements BlazeCommandRunConfigurati
}
String name = PathUtil.getFileName(target.targetName().toString());
for (File file : outputs) {
- if (file.getName().equals(name)) {
+ String fileName = file.getName();
+ if (fileName.equals(name)) {
+ return file;
+ }
+ int exeIndex = fileName.lastIndexOf(".exe");
+ if (exeIndex > 0 && fileName.substring(0, exeIndex).equals(name)) {
return file;
}
}
diff --git a/python/tests/unittests/com/google/idea/blaze/python/run/BlazePyRunConfigurationRunnerTest.java b/python/tests/unittests/com/google/idea/blaze/python/run/BlazePyRunConfigurationRunnerTest.java
index e9cd46aab..4e4bf49d3 100644
--- a/python/tests/unittests/com/google/idea/blaze/python/run/BlazePyRunConfigurationRunnerTest.java
+++ b/python/tests/unittests/com/google/idea/blaze/python/run/BlazePyRunConfigurationRunnerTest.java
@@ -38,4 +38,15 @@ public class BlazePyRunConfigurationRunnerTest {
assertThat(BlazePyRunConfigurationRunner.findExecutable(target, outputFiles))
.isEqualTo(new File("blaze-bin/path/to/package/SomeTest"));
}
+
+ @Test
+ public void testMultipleOutputFilesOnWindows() {
+ Label target = Label.create("//path/to/package:SomeTest");
+ ImmutableList<File> outputFiles =
+ ImmutableList.of(
+ new File("blaze-bin/path/to/package/SomeTest.zip"),
+ new File("blaze-bin/path/to/package/SomeTest.exe"));
+ assertThat(BlazePyRunConfigurationRunner.findExecutable(target, outputFiles))
+ .isEqualTo(new File("blaze-bin/path/to/package/SomeTest.exe"));
+ }
} | ['python/tests/unittests/com/google/idea/blaze/python/run/BlazePyRunConfigurationRunnerTest.java', 'python/src/com/google/idea/blaze/python/run/BlazePyRunConfigurationRunner.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 5,840,640 | 1,214,894 | 157,834 | 1,507 | 276 | 62 | 7 | 1 | 759 | 111 | 202 | 21 | 0 | 1 | 1970-01-01T00:27:47 | 711 | Java | {'Java': 10102604, 'Starlark': 354766, 'Python': 21439, 'Shell': 6506, 'HTML': 970, 'Kotlin': 695, 'C': 558, 'Scala': 481, 'C++': 230} | Apache License 2.0 |
1,368 | bazelbuild/intellij/2686/2685 | bazelbuild | intellij | https://github.com/bazelbuild/intellij/issues/2685 | https://github.com/bazelbuild/intellij/pull/2686 | https://github.com/bazelbuild/intellij/pull/2686 | 1 | fixes | WebStorm 2020.3.3 with plugin 2021.05.12.1.5 is not functional | When I try to import every project from https://github.com/bazelbuild/rules_nodejs/tree/stable/examples IDE is trying to sync, but always comes to:
```
java.lang.RuntimeException: java.lang.ClassCastException: class com.intellij.webcore.moduleType.PlatformWebModuleType cannot be cast to class com.intellij.openapi.module.WebModuleType (com.intellij.webcore.moduleType.PlatformWebModuleType and com.intellij.openapi.module.WebModuleType are in unnamed module of loader com.intellij.util.lang.UrlClassLoader @9f70c54)
at com.intellij.openapi.application.impl.LaterInvocator.invokeAndWait(LaterInvocator.java:149)
at com.intellij.openapi.application.impl.ApplicationImpl.invokeAndWait(ApplicationImpl.java:476)
at com.intellij.openapi.application.impl.ApplicationImpl.invokeAndWait(ApplicationImpl.java:481)
at com.google.idea.common.util.Transactions.submitTransactionAndWait(Transactions.java:25)
at com.google.idea.common.util.Transactions.submitWriteActionTransactionAndWait(Transactions.java:41)
at com.google.idea.blaze.base.sync.ProjectUpdateSyncTask.lambda$updateProject$8(ProjectUpdateSyncTask.java:302)
at com.google.idea.blaze.base.scope.Scope.push(Scope.java:40)
at com.google.idea.blaze.base.sync.ProjectUpdateSyncTask.updateProject(ProjectUpdateSyncTask.java:293)
at com.google.idea.blaze.base.sync.ProjectUpdateSyncTask.run(ProjectUpdateSyncTask.java:246)
at com.google.idea.blaze.base.sync.ProjectUpdateSyncTask.runProjectUpdatePhase(ProjectUpdateSyncTask.java:120)
at com.google.idea.blaze.base.sync.SyncPhaseCoordinator.lambda$updateProjectAndFinishSync$7(SyncPhaseCoordinator.java:509)
at com.google.idea.blaze.base.sync.SyncScope.lambda$runWithTiming$1(SyncScope.java:61)
at com.google.idea.blaze.base.sync.SyncScope.lambda$push$2(SyncScope.java:74)
at com.google.idea.blaze.base.sync.SyncScope.push(SyncScope.java:89)
at com.google.idea.blaze.base.sync.SyncScope.push(SyncScope.java:71)
at com.google.idea.blaze.base.sync.SyncScope.runWithTiming(SyncScope.java:63)
at com.google.idea.blaze.base.sync.SyncPhaseCoordinator.updateProjectAndFinishSync(SyncPhaseCoordinator.java:501)
at com.google.idea.blaze.base.sync.SyncPhaseCoordinator.runSync(SyncPhaseCoordinator.java:405)
at com.google.idea.blaze.base.sync.SyncPhaseCoordinator.lambda$syncProject$0(SyncPhaseCoordinator.java:230)
at com.google.idea.blaze.base.scope.Scope.push(Scope.java:57)
at com.google.idea.blaze.base.scope.Scope.root(Scope.java:33)
at com.google.idea.blaze.base.sync.SyncPhaseCoordinator.lambda$syncProject$1(SyncPhaseCoordinator.java:220)
at com.google.idea.blaze.base.async.executor.ProgressiveTaskWithProgressIndicator.lambda$submitTask$0(ProgressiveTaskWithProgressIndicator.java:79)
at com.google.idea.blaze.base.async.executor.ProgressiveTaskWithProgressIndicator.lambda$submitTaskWithResult$4(ProgressiveTaskWithProgressIndicator.java:127)
at com.intellij.openapi.progress.ProgressManager.lambda$runProcess$0(ProgressManager.java:59)
at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:178)
at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:658)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:610)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:65)
at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:165)
at com.intellij.openapi.progress.ProgressManager.runProcess(ProgressManager.java:59)
at com.google.idea.blaze.base.async.executor.ProgressiveTaskWithProgressIndicator.lambda$submitTaskWithResult$5(ProgressiveTaskWithProgressIndicator.java:127)
at com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask.runInterruptibly(TrustedListenableFutureTask.java:125)
at com.google.common.util.concurrent.InterruptibleTask.run(InterruptibleTask.java:69)
at com.google.common.util.concurrent.TrustedListenableFutureTask.run(TrustedListenableFutureTask.java:78)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.ClassCastException: class com.intellij.webcore.moduleType.PlatformWebModuleType cannot be cast to class com.intellij.openapi.module.WebModuleType (com.intellij.webcore.moduleType.PlatformWebModuleType and com.intellij.openapi.module.WebModuleType are in unnamed module of loader com.intellij.util.lang.UrlClassLoader @9f70c54)
at com.intellij.openapi.module.WebModuleType.getInstance(WebModuleType.java:17)
at com.google.idea.blaze.javascript.BlazeJavascriptSyncPlugin.getWorkspaceModuleType(BlazeJavascriptSyncPlugin.java:59)
at com.google.idea.blaze.base.sync.ProjectUpdateSyncTask.updateProjectStructure(ProjectUpdateSyncTask.java:351)
at com.google.idea.blaze.base.sync.ProjectUpdateSyncTask.lambda$updateProject$6(ProjectUpdateSyncTask.java:307)
at com.intellij.openapi.roots.impl.ProjectRootManagerImpl.mergeRootsChangesDuring(ProjectRootManagerImpl.java:402)
at com.google.idea.blaze.base.sync.ProjectUpdateSyncTask.lambda$updateProject$7(ProjectUpdateSyncTask.java:305)
at com.intellij.openapi.application.impl.ApplicationImpl.runWriteAction(ApplicationImpl.java:1000)
at com.google.idea.common.util.Transactions.lambda$submitWriteActionTransactionAndWait$2(Transactions.java:41)
at com.intellij.openapi.application.TransactionGuardImpl.runWithWritingAllowed(TransactionGuardImpl.java:216)
at com.intellij.openapi.application.TransactionGuardImpl.access$200(TransactionGuardImpl.java:24)
at com.intellij.openapi.application.TransactionGuardImpl$2.run(TransactionGuardImpl.java:199)
at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:822)
at com.intellij.openapi.application.impl.ApplicationImpl.lambda$invokeAndWait$8(ApplicationImpl.java:476)
at com.intellij.openapi.application.impl.LaterInvocator$1.run(LaterInvocator.java:126)
at com.intellij.openapi.application.impl.FlushQueue.doRun(FlushQueue.java:85)
at com.intellij.openapi.application.impl.FlushQueue.runNextEvent(FlushQueue.java:134)
at com.intellij.openapi.application.impl.FlushQueue.flushNow(FlushQueue.java:47)
at com.intellij.openapi.application.impl.FlushQueue$FlushNow.run(FlushQueue.java:190)
at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:776)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:727)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:746)
at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:976)
at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:843)
at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$8(IdeEventQueue.java:454)
at com.intellij.openapi.progress.impl.CoreProgressManager.computePrioritized(CoreProgressManager.java:773)
at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$9(IdeEventQueue.java:453)
at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:822)
at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:501)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
``` | 65f388edfeeab2eca559cb6ec598a49e78922ec5 | 344e7d078fd6052d85cfc20850f9a22711338adb | https://github.com/bazelbuild/intellij/compare/65f388edfeeab2eca559cb6ec598a49e78922ec5...344e7d078fd6052d85cfc20850f9a22711338adb | diff --git a/javascript/src/com/google/idea/blaze/javascript/BlazeJavascriptSyncPlugin.java b/javascript/src/com/google/idea/blaze/javascript/BlazeJavascriptSyncPlugin.java
index 24ccdab84..edabcd8d6 100644
--- a/javascript/src/com/google/idea/blaze/javascript/BlazeJavascriptSyncPlugin.java
+++ b/javascript/src/com/google/idea/blaze/javascript/BlazeJavascriptSyncPlugin.java
@@ -36,7 +36,7 @@ import com.google.idea.blaze.base.sync.projectview.WorkspaceLanguageSettings;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;
-import com.intellij.openapi.module.WebModuleType;
+import com.intellij.openapi.module.WebModuleTypeBase;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.roots.libraries.Library;
@@ -56,7 +56,7 @@ public class BlazeJavascriptSyncPlugin implements BlazeSyncPlugin {
@Override
public ModuleType<?> getWorkspaceModuleType(WorkspaceType workspaceType) {
if (workspaceType == WorkspaceType.JAVASCRIPT) {
- return WebModuleType.getInstance();
+ return WebModuleTypeBase.getInstance();
}
return null;
} | ['javascript/src/com/google/idea/blaze/javascript/BlazeJavascriptSyncPlugin.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 5,433,966 | 1,131,500 | 146,988 | 1,370 | 195 | 34 | 4 | 1 | 8,323 | 216 | 1,728 | 82 | 1 | 1 | 1970-01-01T00:27:03 | 711 | Java | {'Java': 10102604, 'Starlark': 354766, 'Python': 21439, 'Shell': 6506, 'HTML': 970, 'Kotlin': 695, 'C': 558, 'Scala': 481, 'C++': 230} | Apache License 2.0 |
1,358 | odpi/egeria/6518/6517 | odpi | egeria | https://github.com/odpi/egeria/issues/6517 | https://github.com/odpi/egeria/pull/6518 | https://github.com/odpi/egeria/pull/6518 | 1 | fix | [BUG] REX pretraversals are failing. | ### Is there an existing issue for this?
- [X] I have searched the existing issues
### Current Behavior
REX pretraversals are failing.
### Expected Behavior
REX pretraversals should work
### Steps To Reproduce
create a n entity with a relationship an attempt to explore from it from the REX UI.
### Environment
```markdown
- Egeria:
- OS:
- Java:
- Browser (for UI issues):
- Additional connectors and integration:
```
### Any Further Information?
The Traversal logic work on longs whereas the pre traversal logic is incorrectly working with Longs (the object) and it checks for non null to determine if there is an asOfTime. The value is 0 for this case so it fails if the back end repository does no support asOfTime on the query | fd72cc9ab629c85f0a07d8c30897764403746aac | 94b764448858ac8acc4b4fb0047a6de3a5cd4f91 | https://github.com/odpi/egeria/compare/fd72cc9ab629c85f0a07d8c30897764403746aac...94b764448858ac8acc4b4fb0047a6de3a5cd4f91 | diff --git a/open-metadata-implementation/view-services/rex-view/rex-view-server/src/main/java/org/odpi/openmetadata/viewservices/rex/handlers/RexViewHandler.java b/open-metadata-implementation/view-services/rex-view/rex-view-server/src/main/java/org/odpi/openmetadata/viewservices/rex/handlers/RexViewHandler.java
index 39e4d6ba87..a618422571 100644
--- a/open-metadata-implementation/view-services/rex-view/rex-view-server/src/main/java/org/odpi/openmetadata/viewservices/rex/handlers/RexViewHandler.java
+++ b/open-metadata-implementation/view-services/rex-view/rex-view-server/src/main/java/org/odpi/openmetadata/viewservices/rex/handlers/RexViewHandler.java
@@ -979,7 +979,7 @@ public class RexViewHandler
boolean enterpriseOption,
String entityGUID,
int depth,
- Long asOfTime,
+ long asOfTime,
String methodName)
throws
RexViewServiceException
@@ -1021,7 +1021,7 @@ public class RexViewHandler
if (depth > 0)
{
Date asOfTimeDate = null;
- if (asOfTime !=null) {
+ if (asOfTime != 0) {
asOfTimeDate = new Date(asOfTime);
}
instGraph = repositoryServicesClient.getEntityNeighborhood(userId, | ['open-metadata-implementation/view-services/rex-view/rex-view-server/src/main/java/org/odpi/openmetadata/viewservices/rex/handlers/RexViewHandler.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 54,422,740 | 8,922,516 | 1,217,175 | 4,742 | 211 | 35 | 4 | 1 | 750 | 128 | 173 | 30 | 0 | 1 | 1970-01-01T00:27:31 | 701 | Java | {'Java': 73907703, 'Jupyter Notebook': 2338674, 'Groovy': 67997, 'SCSS': 11740, 'Shell': 7274, 'HTML': 6701, 'Dockerfile': 5404, 'Ruby': 49} | Apache License 2.0 |
1,357 | odpi/egeria/6521/6517 | odpi | egeria | https://github.com/odpi/egeria/issues/6517 | https://github.com/odpi/egeria/pull/6521 | https://github.com/odpi/egeria/pull/6521 | 1 | fix | [BUG] REX pretraversals are failing. | ### Is there an existing issue for this?
- [X] I have searched the existing issues
### Current Behavior
REX pretraversals are failing.
### Expected Behavior
REX pretraversals should work
### Steps To Reproduce
create a n entity with a relationship an attempt to explore from it from the REX UI.
### Environment
```markdown
- Egeria:
- OS:
- Java:
- Browser (for UI issues):
- Additional connectors and integration:
```
### Any Further Information?
The Traversal logic work on longs whereas the pre traversal logic is incorrectly working with Longs (the object) and it checks for non null to determine if there is an asOfTime. The value is 0 for this case so it fails if the back end repository does no support asOfTime on the query | b2ed0a013181c864d3447cbc913360e46929b712 | f58e21d4009c990b470e216bd39201393129779f | https://github.com/odpi/egeria/compare/b2ed0a013181c864d3447cbc913360e46929b712...f58e21d4009c990b470e216bd39201393129779f | diff --git a/open-metadata-implementation/view-services/rex-view/rex-view-server/src/main/java/org/odpi/openmetadata/viewservices/rex/handlers/RexViewHandler.java b/open-metadata-implementation/view-services/rex-view/rex-view-server/src/main/java/org/odpi/openmetadata/viewservices/rex/handlers/RexViewHandler.java
index 39e4d6ba87..a618422571 100644
--- a/open-metadata-implementation/view-services/rex-view/rex-view-server/src/main/java/org/odpi/openmetadata/viewservices/rex/handlers/RexViewHandler.java
+++ b/open-metadata-implementation/view-services/rex-view/rex-view-server/src/main/java/org/odpi/openmetadata/viewservices/rex/handlers/RexViewHandler.java
@@ -979,7 +979,7 @@ public class RexViewHandler
boolean enterpriseOption,
String entityGUID,
int depth,
- Long asOfTime,
+ long asOfTime,
String methodName)
throws
RexViewServiceException
@@ -1021,7 +1021,7 @@ public class RexViewHandler
if (depth > 0)
{
Date asOfTimeDate = null;
- if (asOfTime !=null) {
+ if (asOfTime != 0) {
asOfTimeDate = new Date(asOfTime);
}
instGraph = repositoryServicesClient.getEntityNeighborhood(userId, | ['open-metadata-implementation/view-services/rex-view/rex-view-server/src/main/java/org/odpi/openmetadata/viewservices/rex/handlers/RexViewHandler.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 54,458,277 | 8,927,703 | 1,217,723 | 4,744 | 211 | 35 | 4 | 1 | 750 | 128 | 173 | 30 | 0 | 1 | 1970-01-01T00:27:31 | 701 | Java | {'Java': 73907703, 'Jupyter Notebook': 2338674, 'Groovy': 67997, 'SCSS': 11740, 'Shell': 7274, 'HTML': 6701, 'Dockerfile': 5404, 'Ruby': 49} | Apache License 2.0 |
1,359 | odpi/egeria/6362/6358 | odpi | egeria | https://github.com/odpi/egeria/issues/6358 | https://github.com/odpi/egeria/pull/6362 | https://github.com/odpi/egeria/pull/6362 | 1 | fixes | [BUG] Code fix for Egerai UI issue326 | ### Is there an existing issue for this?
- [X] I have searched the existing issues
### Current Behavior
See EgeriaUI issue326 [https://github.com/odpi/egeria-react-ui/issues/326](https://github.com/odpi/egeria-react-ui/issues/326)
### Expected Behavior
Expected that the isA Relation is successfully created .
### Steps To Reproduce
Testing Egeria 3.5 chart
Egeria 3.5
React UI 3.4
Logged in as garygeeke
Created a glossary 'a'
Created a category 'b'
Created two terms in above 'c', 'd'
All good to this point
I then tried to create a 'isA' relationship 'r' between c and d using the visual explorer
In the UI I got to the final screen, clicked create, and the page refreshed but no error/info was shown
In the log of the view server I see a Bad Request:
Full log at https://gist.github.com/e9bd7053cdcb056c85b24b53dbfcfa4e
### Environment
```markdown
- Egeria:
- OS:
- Java:
- Browser (for UI issues):
- Additional connectors and integration:
```
### Any Further Information?
The REST call error outs for a NULL point exception returning a Http code 400 | 24c5ee30ba617fdf29e6a25be1b457be2130e969 | fba8f268416f67073bf638861f4e51360db15bbb | https://github.com/odpi/egeria/compare/24c5ee30ba617fdf29e6a25be1b457be2130e969...fba8f268416f67073bf638861f4e51360db15bbb | diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/IsARelationshipMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/IsARelationshipMapper.java
index f894ab2ddb..e47e905972 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/IsARelationshipMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/IsARelationshipMapper.java
@@ -44,9 +44,7 @@ public class IsARelationshipMapper extends RelationshipMapper<IsA> {
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, iSARelationship.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (iSARelationship.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(iSARelationship.getStatus().getOrdinal());
- instanceProperties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, iSARelationship.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/utilities/SubjectAreaUtils.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/utilities/SubjectAreaUtils.java
index 09d9ce79f7..57953c5ddc 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/utilities/SubjectAreaUtils.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/utilities/SubjectAreaUtils.java
@@ -6,6 +6,7 @@ package org.odpi.openmetadata.accessservices.subjectarea.utilities;
import org.odpi.openmetadata.accessservices.subjectarea.ffdc.SubjectAreaErrorCode;
import org.odpi.openmetadata.accessservices.subjectarea.ffdc.exceptions.InvalidParameterException;
import org.odpi.openmetadata.accessservices.subjectarea.properties.enums.Status;
+import org.odpi.openmetadata.accessservices.subjectarea.properties.enums.TermRelationshipStatus;
import org.odpi.openmetadata.accessservices.subjectarea.properties.objects.category.Category;
import org.odpi.openmetadata.accessservices.subjectarea.properties.objects.common.SystemAttributes;
import org.odpi.openmetadata.accessservices.subjectarea.properties.objects.glossary.Glossary;
@@ -18,6 +19,7 @@ import org.odpi.openmetadata.accessservices.subjectarea.properties.objects.nodes
import org.odpi.openmetadata.accessservices.subjectarea.properties.relationships.CategoryAnchor;
import org.odpi.openmetadata.accessservices.subjectarea.properties.relationships.TermAnchor;
import org.odpi.openmetadata.accessservices.subjectarea.responses.SubjectAreaOMASAPIResponse;
+import org.odpi.openmetadata.commonservices.generichandlers.OpenMetadataAPIMapper;
import org.odpi.openmetadata.frameworks.auditlog.messagesets.ExceptionMessageDefinition;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.*;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.typedefs.PrimitiveDefCategory;
@@ -305,4 +307,18 @@ public class SubjectAreaUtils {
response.addAllResults(icons);
return response;
}
+
+ /**
+ * Set status values into instance properties.
+ *
+ * @param instanceProperties supplied instanceproperties
+ * @param status Status value
+ * @param propertyName property name
+ */
+ public static void setStatusPropertyInInstanceProperties(InstanceProperties instanceProperties, TermRelationshipStatus status, String propertyName) {
+ EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
+ enumPropertyValue.setOrdinal(status.getOrdinal());
+ enumPropertyValue.setSymbolicName(status.getName());
+ instanceProperties.setProperty(propertyName, enumPropertyValue);
+ }
}
\\ No newline at end of file | ['open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/utilities/SubjectAreaUtils.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/IsARelationshipMapper.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 54,551,804 | 8,943,451 | 1,220,146 | 4,765 | 1,280 | 212 | 20 | 2 | 1,129 | 164 | 295 | 48 | 2 | 1 | 1970-01-01T00:27:28 | 701 | Java | {'Java': 73907703, 'Jupyter Notebook': 2338674, 'Groovy': 67997, 'SCSS': 11740, 'Shell': 7274, 'HTML': 6701, 'Dockerfile': 5404, 'Ruby': 49} | Apache License 2.0 |
1,354 | odpi/egeria/6428/6427 | odpi | egeria | https://github.com/odpi/egeria/issues/6427 | https://github.com/odpi/egeria/pull/6428 | https://github.com/odpi/egeria/pull/6428#issuecomment-1102740847 | 1 | fixes | [BUG] Enum symbolic names are not populated for the Status property | ### Is there an existing issue for this?
- [X] I have searched the existing issues
### Current Behavior
While creating a relationship, using Egeria UI, the relationship creation process sets the property of the Status using a ENUM. The current code does not set the symbolic name of the ENUM.
### Expected Behavior
Status property ENUM should have the symbolic name assigned while creating a relationship.
### Steps To Reproduce
Logged in as garygeeke
Created a glossary 'a'
Created a category 'b'
Created two terms in above 'c', 'd'
Create any relationship 'r' between c and d using the visual explorer
### Environment
```markdown
- Egeria:
- OS:
- Java:
- Browser (for UI issues):
- Additional connectors and integration:
```
### Any Further Information?
_No response_ | 492592d7a05ea35890489637fa198d0d57ef3cbd | a5575f01857f63e610fb6fa58a2c64f37aeafc83 | https://github.com/odpi/egeria/compare/492592d7a05ea35890489637fa198d0d57ef3cbd...a5575f01857f63e610fb6fa58a2c64f37aeafc83 | diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/AntonymMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/AntonymMapper.java
index 5c8cb8ccfd..16f6ff4eed 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/AntonymMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/AntonymMapper.java
@@ -44,9 +44,7 @@ public class AntonymMapper extends RelationshipMapper<Antonym> {
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, antonym.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (antonym.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(antonym.getStatus().getOrdinal());
- instanceProperties.setProperty("status", enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, antonym.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/IsATypeOfMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/IsATypeOfMapper.java
index 5015f4cfd4..7203f748be 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/IsATypeOfMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/IsATypeOfMapper.java
@@ -40,9 +40,7 @@ public class IsATypeOfMapper extends RelationshipMapper<IsATypeOf> {
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, isATypeOf.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (isATypeOf.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(isATypeOf.getStatus().getOrdinal());
- instanceProperties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, isATypeOf.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/PreferredTermMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/PreferredTermMapper.java
index 9c82daeba1..722ef5dc6d 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/PreferredTermMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/PreferredTermMapper.java
@@ -44,9 +44,7 @@ public class PreferredTermMapper extends RelationshipMapper<PreferredTerm> {
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, preferredTerm.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (preferredTerm.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(preferredTerm.getStatus().getOrdinal());
- instanceProperties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, preferredTerm.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/RelatedTermMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/RelatedTermMapper.java
index 4cf639f125..5c9fc7dada 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/RelatedTermMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/RelatedTermMapper.java
@@ -43,9 +43,7 @@ public class RelatedTermMapper extends RelationshipMapper<RelatedTerm> {
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, relatedTerm.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (relatedTerm.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(relatedTerm.getStatus().getOrdinal());
- instanceProperties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, relatedTerm.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/ReplacementTermMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/ReplacementTermMapper.java
index 429eccfb92..0c7d50f21f 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/ReplacementTermMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/ReplacementTermMapper.java
@@ -43,9 +43,7 @@ public class ReplacementTermMapper extends RelationshipMapper<ReplacementTerm> {
SubjectAreaUtils.setStringPropertyInInstanceProperties(properties, replacementTerm.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (replacementTerm.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(replacementTerm.getStatus().getOrdinal());
- properties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(properties, replacementTerm.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/SynonymMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/SynonymMapper.java
index c481dcbee1..37d778ca2e 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/SynonymMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/SynonymMapper.java
@@ -43,9 +43,7 @@ public class SynonymMapper extends RelationshipMapper<Synonym> {
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, synonym.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (synonym.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(synonym.getStatus().getOrdinal());
- instanceProperties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, synonym.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermCategorizationMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermCategorizationMapper.java
index 35060cc475..4f44389f2a 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermCategorizationMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermCategorizationMapper.java
@@ -34,9 +34,7 @@ public class TermCategorizationMapper extends RelationshipMapper<Categorization>
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, termCategorization.getDescription(), "description");
}
if (termCategorization.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(termCategorization.getStatus().getOrdinal());
- instanceProperties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, termCategorization.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermHasARelationshipMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermHasARelationshipMapper.java
index f246842e97..9a02e490c4 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermHasARelationshipMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermHasARelationshipMapper.java
@@ -40,9 +40,7 @@ public class TermHasARelationshipMapper extends RelationshipMapper<HasA> {
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, termHasARelationship.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (termHasARelationship.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(termHasARelationship.getStatus().getOrdinal());
- instanceProperties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, termHasARelationship.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermIsATypeOfRelationshipDeprecatedMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermIsATypeOfRelationshipDeprecatedMapper.java
index dcef554921..ab1369b452 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermIsATypeOfRelationshipDeprecatedMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermIsATypeOfRelationshipDeprecatedMapper.java
@@ -44,9 +44,7 @@ public class TermIsATypeOfRelationshipDeprecatedMapper extends RelationshipMappe
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, isATypeOfDeprecated.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (isATypeOfDeprecated.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(isATypeOfDeprecated.getStatus().getOrdinal());
- instanceProperties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, isATypeOfDeprecated.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermTypedByRelationshipMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermTypedByRelationshipMapper.java
index 2e050328f8..b1b84d953a 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermTypedByRelationshipMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermTypedByRelationshipMapper.java
@@ -40,9 +40,7 @@ public class TermTypedByRelationshipMapper extends RelationshipMapper<TypedBy> {
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, termTYPEDBYRelationship.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (termTYPEDBYRelationship.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(termTYPEDBYRelationship.getStatus().getOrdinal());
- instanceProperties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, termTYPEDBYRelationship.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TranslationMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TranslationMapper.java
index b8086ff9ce..1374b54e78 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TranslationMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TranslationMapper.java
@@ -42,9 +42,7 @@ public class TranslationMapper extends RelationshipMapper<Translation> {
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, translation.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (translation.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(translation.getStatus().getOrdinal());
- instanceProperties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, translation.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/UsedInContextMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/UsedInContextMapper.java
index 1354b1be34..9cba4ed8a3 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/UsedInContextMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/UsedInContextMapper.java
@@ -43,9 +43,7 @@ public class UsedInContextMapper extends RelationshipMapper<UsedInContext> {
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, usedInContext.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (usedInContext.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(usedInContext.getStatus().getOrdinal());
- instanceProperties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, usedInContext.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
diff --git a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/ValidValueMapper.java b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/ValidValueMapper.java
index 69a3688c5c..35174de297 100644
--- a/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/ValidValueMapper.java
+++ b/open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/ValidValueMapper.java
@@ -43,9 +43,7 @@ public class ValidValueMapper extends RelationshipMapper<ValidValue> {
SubjectAreaUtils.setStringPropertyInInstanceProperties(instanceProperties, validValue.getSource(), OpenMetadataAPIMapper.SOURCE_PROPERTY_NAME);
}
if (validValue.getStatus() != null) {
- EnumPropertyValue enumPropertyValue = new EnumPropertyValue();
- enumPropertyValue.setOrdinal(validValue.getStatus().getOrdinal());
- instanceProperties.setProperty(OpenMetadataAPIMapper.STATUS_PROPERTY_NAME, enumPropertyValue);
+ SubjectAreaUtils.setStatusPropertyInInstanceProperties(instanceProperties, validValue.getStatus(), OpenMetadataAPIMapper.STATUS_PROPERTY_NAME);
}
}
| ['open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermCategorizationMapper.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermHasARelationshipMapper.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermTypedByRelationshipMapper.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/RelatedTermMapper.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/SynonymMapper.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/PreferredTermMapper.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/UsedInContextMapper.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TranslationMapper.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/ReplacementTermMapper.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/ValidValueMapper.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/IsATypeOfMapper.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/TermIsATypeOfRelationshipDeprecatedMapper.java', 'open-metadata-implementation/access-services/subject-area/subject-area-server/src/main/java/org/odpi/openmetadata/accessservices/subjectarea/server/mappers/relationships/AntonymMapper.java'] | {'.java': 13} | 13 | 13 | 0 | 0 | 13 | 54,465,231 | 8,929,106 | 1,217,879 | 4,747 | 5,502 | 857 | 52 | 13 | 803 | 128 | 178 | 40 | 0 | 1 | 1970-01-01T00:27:30 | 701 | Java | {'Java': 73907703, 'Jupyter Notebook': 2338674, 'Groovy': 67997, 'SCSS': 11740, 'Shell': 7274, 'HTML': 6701, 'Dockerfile': 5404, 'Ruby': 49} | Apache License 2.0 |
1,355 | odpi/egeria/7498/7423 | odpi | egeria | https://github.com/odpi/egeria/issues/7423 | https://github.com/odpi/egeria/pull/7498 | https://github.com/odpi/egeria/pull/7498 | 1 | fixes | [BUG] deleteGovernanceZone error | ### Existing/related issue?
_No response_
### Current Behavior
(https://github.com/odpi/egeria/blob/main/open-metadata-implementation/access-services/governance-program/governance-program-client/src/main/java/org/odpi/openmetadata/accessservices/governanceprogram/client/GovernanceZoneManager.java)
line: 210 spell error
`final String urlTemplate = serverPlatformURLRoot + "/servers/{0}/open-metadata/access-services/governance-program/users/{1}/governance-zones/{2}/delete}";`
the last symbol '}' is redundant
### Expected Behavior
the correct as follow
`final String urlTemplate = serverPlatformURLRoot + "/servers/{0}/open-metadata/access-services/governance-program/users/{1}/governance-zones/{2}/delete";`
### Steps To Reproduce
_No response_
### Environment
```markdown
- Egeria:3.12
- OS:centos7
- Java:11
- Browser (for UI issues):chrome
- Additional connectors and integration:
```
### Any Further Information?
_No response_ | 57895896e4379008afe5ffded9edbe3896323e81 | fb7d2705b22513a9558f104a803ab24c54f7a974 | https://github.com/odpi/egeria/compare/57895896e4379008afe5ffded9edbe3896323e81...fb7d2705b22513a9558f104a803ab24c54f7a974 | diff --git a/open-metadata-implementation/access-services/governance-program/governance-program-client/src/main/java/org/odpi/openmetadata/accessservices/governanceprogram/client/GovernanceZoneManager.java b/open-metadata-implementation/access-services/governance-program/governance-program-client/src/main/java/org/odpi/openmetadata/accessservices/governanceprogram/client/GovernanceZoneManager.java
index ac3263634e..6e9be1b6fb 100644
--- a/open-metadata-implementation/access-services/governance-program/governance-program-client/src/main/java/org/odpi/openmetadata/accessservices/governanceprogram/client/GovernanceZoneManager.java
+++ b/open-metadata-implementation/access-services/governance-program/governance-program-client/src/main/java/org/odpi/openmetadata/accessservices/governanceprogram/client/GovernanceZoneManager.java
@@ -207,7 +207,7 @@ public class GovernanceZoneManager extends GovernanceProgramBaseClient implement
final String methodName = "deleteGovernanceZone";
final String guidParameter = "zoneGUID";
- final String urlTemplate = serverPlatformURLRoot + "/servers/{0}/open-metadata/access-services/governance-program/users/{1}/governance-zones/{2}/delete}";
+ final String urlTemplate = serverPlatformURLRoot + "/servers/{0}/open-metadata/access-services/governance-program/users/{1}/governance-zones/{2}/delete";
super.removeReferenceable(userId, zoneGUID, guidParameter, urlTemplate, methodName);
} | ['open-metadata-implementation/access-services/governance-program/governance-program-client/src/main/java/org/odpi/openmetadata/accessservices/governanceprogram/client/GovernanceZoneManager.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 61,576,085 | 9,947,466 | 1,347,840 | 5,120 | 326 | 76 | 2 | 1 | 954 | 72 | 228 | 34 | 1 | 1 | 1970-01-01T00:27:58 | 701 | Java | {'Java': 73907703, 'Jupyter Notebook': 2338674, 'Groovy': 67997, 'SCSS': 11740, 'Shell': 7274, 'HTML': 6701, 'Dockerfile': 5404, 'Ruby': 49} | Apache License 2.0 |
1,356 | odpi/egeria/6712/6549 | odpi | egeria | https://github.com/odpi/egeria/issues/6549 | https://github.com/odpi/egeria/pull/6712 | https://github.com/odpi/egeria/pull/6712 | 1 | fix | [BUG] Problem registering governance engine / Asset consumer exceptions | ### Is there an existing issue for this?
- [X] I have searched the existing issues
### Current Behavior
Noticed this when checking the notebooks for release.
This notebook is explicitly marked as not to be run. However it looks to be an issue worth checking, possibly after some refactoring
```
POST https://lab-core:9443/servers/cocoMDS2/open-metadata/access-services/governance-engine/users/erinoverview/governance-services/new/GovernanceActionService
{
"class": "NewGovernanceServiceRequestBody",
"qualifiedName": "ftp-governance-action-service",
"displayName": "FTP Governance Action Service",
"description": "Simulates FTP from an external party.",
"connection": {
"class": "Connection",
"type": {
"class": "ElementType",
"elementTypeId": "114e9f8f-5ff3-4c32-bd37-a7eb42712253",
"elementTypeName": "Connection",
"elementTypeVersion": 1,
"elementTypeDescription": "A set of properties to identify and configure a connector instance.",
"elementOrigin": "CONFIGURATION"
},
"qualifiedName": "ftp-governance-action-service-implementation",
"displayName": "FTP Governance Action Service Implementation Connection",
"description": "Connection for governance service ftp-governance-action-service",
"connectorType": {
"class": "ConnectorType",
"type": {
"class": "ElementType",
"elementTypeId": "954421eb-33a6-462d-a8ca-b5709a1bd0d4",
"elementTypeName": "ConnectorType",
"elementTypeVersion": 1,
"elementTypeDescription": "A set of properties describing a type of connector.",
"elementOrigin": "LOCAL_COHORT"
},
"guid": "1111f73d-e343-abcd-82cb-3918fed81da6",
"qualifiedName": "ftp-governance-action-service-GovernanceServiceProvider",
"displayName": "FTP Governance Action Service Governance Service Provider Implementation",
"description": "Simulates FTP from an external party.",
"connectorProviderClassName": "org.odpi.openmetadata.adapters.connectors.governanceactions.provisioning.MoveCopyFileGovernanceActionProvider"
},
"configurationProperties": {
"noLineage": ""
}
}
}
Returns:
{
"class": "GUIDResponse",
"relatedHTTPCode": 200,
"guid": "d594dc4d-59f6-44c8-8121-0dafdc5be544"
}
The guid for the ftp-governance-action-service governance service is: d594dc4d-59f6-44c8-8121-0dafdc5be544
POST https://lab-datalake:9443/servers/cocoMDS1/open-metadata/access-services/governance-engine/users/peterprofile/governance-engines/f45b9bb7-81d7-4304-a74f-b8162a3438e9/governance-services
{
"class": "GovernanceServiceRegistrationRequestBody",
"governanceServiceGUID": "d594dc4d-59f6-44c8-8121-0dafdc5be544",
"requestType": "copy-file"
}
Returns:
{
"class": "VoidResponse",
"relatedHTTPCode": 500,
"exceptionClassName": "org.odpi.openmetadata.frameworks.connectors.ffdc.PropertyServerException",
"actionDescription": "registerGovernanceServiceWithEngine",
"exceptionErrorMessage": "OMAG-REPOSITORY-HANDLER-500-001 An unexpected error org.odpi.openmetadata.repositoryservices.ffdc.exception.RepositoryErrorException was returned to reclassifyEntity(LatestChange) by the metadata server during registerGovernanceServiceWithEngine request for open metadata access service Governance Engine OMAS on server cocoMDS1; message was OMRS-REPOSITORY-400-056 The OMRS repository connector operation updateEntityClassification (EntityProxy) from the OMRS Enterprise Repository Services can not locate the home repository connector for instance LatestChange located in metadata collection 94645157-2a9d-4d32-9170-e6f2747a0ceb",
"exceptionErrorMessageId": "OMAG-REPOSITORY-HANDLER-500-001",
"exceptionErrorMessageParameters": [
"OMRS-REPOSITORY-400-056 The OMRS repository connector operation updateEntityClassification (EntityProxy) from the OMRS Enterprise Repository Services can not locate the home repository connector for instance LatestChange located in metadata collection 94645157-2a9d-4d32-9170-e6f2747a0ceb",
"registerGovernanceServiceWithEngine",
"Governance Engine OMAS",
"cocoMDS1",
"org.odpi.openmetadata.repositoryservices.ffdc.exception.RepositoryErrorException",
"reclassifyEntity(LatestChange)"
],
"exceptionSystemAction": "The system is unable to process the request because of an internal error.",
"exceptionUserAction": "Verify the sanity of the server. This is probably a logic error. If you can not work out what happened, ask the Egeria community for help."
}
OMAG-REPOSITORY-HANDLER-500-001 An unexpected error org.odpi.openmetadata.repositoryservices.ffdc.exception.RepositoryErrorException was returned to reclassifyEntity(LatestChange) by the metadata server during registerGovernanceServiceWithEngine request for open metadata access service Governance Engine OMAS on server cocoMDS1; message was OMRS-REPOSITORY-400-056 The OMRS repository connector operation updateEntityClassification (EntityProxy) from the OMRS Enterprise Repository Services can not locate the home repository connector for instance LatestChange located in metadata collection 94645157-2a9d-4d32-9170-e6f2747a0ceb
* The system is unable to process the request because of an internal error.
* Verify the sanity of the server. This is probably a logic error. If you can not work out what happened, ask the Egeria community for help.
Service registered as: copy-file
```
### Expected Behavior
governance engine registration passes
### Steps To Reproduce
Run the incomplete/unsupported notebook 'automated curation' in a coco pharma tutorial environment
### Environment
```markdown
- Egeria:3.8
```
### Any Further Information?
_No response_ | fc52eb09a771a29fcbd90b4cf5dc150f6b7799f6 | f3128ceee67de9ea12157e00d0e019d6c650e216 | https://github.com/odpi/egeria/compare/fc52eb09a771a29fcbd90b4cf5dc150f6b7799f6...f3128ceee67de9ea12157e00d0e019d6c650e216 | diff --git a/open-metadata-implementation/adapters/open-connectors/event-bus-connectors/open-metadata-topic-connectors/kafka-open-metadata-topic-connector/src/main/java/org/odpi/openmetadata/adapters/eventbus/topic/kafka/KafkaOpenMetadataEventConsumer.java b/open-metadata-implementation/adapters/open-connectors/event-bus-connectors/open-metadata-topic-connectors/kafka-open-metadata-topic-connector/src/main/java/org/odpi/openmetadata/adapters/eventbus/topic/kafka/KafkaOpenMetadataEventConsumer.java
index 4c68da4943..50232bb6bd 100644
--- a/open-metadata-implementation/adapters/open-connectors/event-bus-connectors/open-metadata-topic-connectors/kafka-open-metadata-topic-connector/src/main/java/org/odpi/openmetadata/adapters/eventbus/topic/kafka/KafkaOpenMetadataEventConsumer.java
+++ b/open-metadata-implementation/adapters/open-connectors/event-bus-connectors/open-metadata-topic-connectors/kafka-open-metadata-topic-connector/src/main/java/org/odpi/openmetadata/adapters/eventbus/topic/kafka/KafkaOpenMetadataEventConsumer.java
@@ -3,30 +3,21 @@
package org.odpi.openmetadata.adapters.eventbus.topic.kafka;
import java.time.Duration;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Queue;
+import java.util.*;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
-import org.apache.kafka.clients.consumer.CommitFailedException;
-import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
-import org.apache.kafka.clients.consumer.ConsumerRecord;
-import org.apache.kafka.clients.consumer.ConsumerRecords;
-import org.apache.kafka.clients.consumer.KafkaConsumer;
-import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.WakeupException;
import org.odpi.openmetadata.frameworks.auditlog.AuditLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static java.lang.Thread.sleep;
/**
@@ -52,7 +43,10 @@ public class KafkaOpenMetadataEventConsumer implements Runnable
private long nextMessageProcessingStatusCheckTime = System.currentTimeMillis();
private long maxNextPollTimestampToAvoidConsumerTimeout = 0;
private final long maxMsBetweenPolls;
-
+
+ // Keep track of when an initial rebalance is done
+ private boolean initialPartitionAssignment = true;
+
//If we get close enough to the consumer timeout timestamp, force a poll so that
//we do not exceed the timeout. This parameter controls how close we can get
@@ -68,6 +62,7 @@ public class KafkaOpenMetadataEventConsumer implements Runnable
private final AtomicBoolean running = new AtomicBoolean(true);
private final boolean isAutoCommitEnabled;
+ private final long startTime = System.currentTimeMillis();
/**
* Constructor for the event consumer.
@@ -112,6 +107,7 @@ public class KafkaOpenMetadataEventConsumer implements Runnable
this.messageProcessingStatusCheckIntervalMs = config.getLongProperty(KafkaOpenMetadataEventConsumerProperty.COMMIT_CHECK_INTERVAL_MS);
long messageTimeoutMins = config.getLongProperty(KafkaOpenMetadataEventConsumerProperty.CONSUMER_EVENT_PROCESSING_TIMEOUT_MINS);
this.messageProcessingTimeoutMs = messageTimeoutMins < 0 ? messageTimeoutMins : TimeUnit.MILLISECONDS.convert(messageTimeoutMins, TimeUnit.MINUTES);
+
}
@@ -135,8 +131,7 @@ public class KafkaOpenMetadataEventConsumer implements Runnable
public void run()
{
final String actionDescription = "run";
- KafkaOpenMetadataTopicConnectorAuditCode auditCode;
-
+
while (isRunning())
{
try
@@ -452,7 +447,7 @@ public class KafkaOpenMetadataEventConsumer implements Runnable
private void awaitNextPollingTime() {
try
{
- Thread.sleep(1000);
+ sleep(1000);
}
catch (InterruptedException e)
{
@@ -468,7 +463,7 @@ public class KafkaOpenMetadataEventConsumer implements Runnable
try
{
- Thread.sleep(recoverySleepTimeSec * 1000L);
+ sleep(recoverySleepTimeSec * 1000L);
}
catch (InterruptedException e1)
{
@@ -514,17 +509,68 @@ public class KafkaOpenMetadataEventConsumer implements Runnable
}
- private class HandleRebalance implements ConsumerRebalanceListener
- {
+ private class HandleRebalance implements ConsumerRebalanceListener {
AuditLog auditLog = null;
+
public HandleRebalance(AuditLog auditLog) {
this.auditLog = auditLog;
}
- public void onPartitionsAssigned(Collection<TopicPartition> partitions)
- {
+ @Override
+ public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
+
+ // Check if we need to rewind to handle initial startup case -- but only on first assignment
+ try {
+ if (initialPartitionAssignment) {
+ log.info("Received initial PartitionsAssigned event");
+
+ long partitionCount = partitions.size();
+
+ if (partitionCount != 1) {
+ log.info("Received PartitionsAssigned event with {} partitions. This is not supported.",partitionCount);
+ } else {
+ // there is only one partition, so we can just grab the first one - and we'll try this once only
+ initialPartitionAssignment = false;
+ long maxOffsetWanted = 0; // same as 'beginning'
+
+ TopicPartition partition = partitions.iterator().next();
+
+ // query offset by timestamp (when we started connector) - NULL if there are no messages later than this offset
+ long reqStartTime=KafkaOpenMetadataEventConsumer.this.startTime;
+ log.info("Querying for offset by timestamp: {}",reqStartTime);
+ OffsetAndTimestamp otByStartTime = consumer.offsetsForTimes(Collections.singletonMap(partition,
+ reqStartTime)).get(partition);
+
+ // If null, then we don't have any earlier messages - ie there is no offset found
+ if (otByStartTime != null) {
+ // where we want to scoll to - the messages sent since we thought we started
+ maxOffsetWanted = otByStartTime.offset();
+ log.info("Earliest offset found for {} is {}",reqStartTime,otByStartTime.timestamp());
+
+ // get the current offset
+ long currentOffset = consumer.position(partition);
+
+ // if the current offset is later than the start time we want, rewind to the start time
+ if (currentOffset > maxOffsetWanted) {
+
+ log.info("Seeking to {} for partition {} and topic {} as current offset {} is too late", maxOffsetWanted, partition.partition(),
+ partition.topic(), currentOffset);
+ consumer.seek(partition, maxOffsetWanted);
+ } else
+ log.info("Not Seeking to {} for partition {} and topic {} as current offset {} is older", maxOffsetWanted, partition.partition(),
+ partition.topic(), currentOffset);
+ }
+ else
+ log.info("No missed events found for partition {} and topic {}", partition.partition(), partition.topic());
+ }
+ }
+ } catch (Exception e) {
+ // We leave the offset as-is if anything goes wrong. Eventually other messages will cause the effective state to be updated
+ log.info("Error correcting seek position, continuing with defaults", e);
+ }
}
+ @Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions)
{
final String methodName = "onPartitionsRevoked.commitSync";
| ['open-metadata-implementation/adapters/open-connectors/event-bus-connectors/open-metadata-topic-connectors/kafka-open-metadata-topic-connector/src/main/java/org/odpi/openmetadata/adapters/eventbus/topic/kafka/KafkaOpenMetadataEventConsumer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 54,463,284 | 8,931,539 | 1,218,045 | 4,758 | 4,770 | 854 | 88 | 1 | 6,033 | 490 | 1,388 | 114 | 2 | 2 | 1970-01-01T00:27:37 | 701 | Java | {'Java': 73907703, 'Jupyter Notebook': 2338674, 'Groovy': 67997, 'SCSS': 11740, 'Shell': 7274, 'HTML': 6701, 'Dockerfile': 5404, 'Ruby': 49} | Apache License 2.0 |
926 | javacord/javacord/17/16 | javacord | javacord | https://github.com/Javacord/Javacord/issues/16 | https://github.com/Javacord/Javacord/pull/17 | https://github.com/Javacord/Javacord/pull/17 | 1 | fix | 'Timestamp' attribute on messages ignores the timezone. | Currently the timestamp attribute on messages completely ignores the timezone, which causes major issues when comparing the time. As no TZ is supplied, Java assumes it wants to use the system time, which means unless the system is set to use UTC, the time will be wrong.
This can be remedied in one of two ways:
- Just set the calendar instance to UTC
- Or better, implement proper timestamp handling that includes the timezone.
| ab17ff6257733f96a3bbe35ae2952166dfac3423 | ed3965c9eba5bdb1ed5956309c2edc747f427ba7 | https://github.com/javacord/javacord/compare/ab17ff6257733f96a3bbe35ae2952166dfac3423...ed3965c9eba5bdb1ed5956309c2edc747f427ba7 | diff --git a/src/main/java/de/btobastian/javacord/entities/message/impl/ImplMessage.java b/src/main/java/de/btobastian/javacord/entities/message/impl/ImplMessage.java
index 07c667ff..184dc29a 100644
--- a/src/main/java/de/btobastian/javacord/entities/message/impl/ImplMessage.java
+++ b/src/main/java/de/btobastian/javacord/entities/message/impl/ImplMessage.java
@@ -18,6 +18,7 @@
*/
package de.btobastian.javacord.entities.message.impl;
+import com.google.common.base.Joiner;
import com.google.common.util.concurrent.FutureCallback;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
@@ -59,9 +60,30 @@ public class ImplMessage implements Message {
*/
private static final Logger logger = LoggerUtil.getLogger(ImplMessage.class);
- private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
- private static final SimpleDateFormat FORMAT_ALTERNATIVE = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
- private static final SimpleDateFormat FORMAT_ALTERNATIVE_TWO = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
+ private static final ThreadLocal<SimpleDateFormat> TIMEZONE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
+ @Override
+ protected SimpleDateFormat initialValue() {
+ return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
+ }
+ };
+ private static final ThreadLocal<SimpleDateFormat> FORMAT = new ThreadLocal<SimpleDateFormat>() {
+ @Override
+ protected SimpleDateFormat initialValue() {
+ return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
+ }
+ };
+ private static final ThreadLocal<SimpleDateFormat> FORMAT_ALTERNATIVE = new ThreadLocal<SimpleDateFormat>() {
+ @Override
+ protected SimpleDateFormat initialValue() {
+ return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
+ }
+ };
+ private static final ThreadLocal<SimpleDateFormat> FORMAT_ALTERNATIVE_TWO = new ThreadLocal<SimpleDateFormat>() {
+ @Override
+ protected SimpleDateFormat initialValue() {
+ return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
+ }
+ };
private final ImplDiscordAPI api;
@@ -93,15 +115,19 @@ public class ImplMessage implements Message {
if (data.has("timestamp")) {
String time = data.getString("timestamp");
Calendar calendar = Calendar.getInstance();
- synchronized (FORMAT) { // SimpleDateFormat#parse() isn't thread safe...
- try {
- calendar.setTime(FORMAT.parse(time.substring(0, time.length() - 9)));
+ try {
+ //remove the nano seconds, rejoining on +. If the formatting changes then the string will remain the same
+ String nanoSecondsRemoved = Joiner.on("+").join(time.split("\\\\d{3}\\\\+"));
+ calendar.setTime(TIMEZONE_FORMAT.get().parse(nanoSecondsRemoved));
+ } catch (ParseException timeZoneIgnored) {
+ try { //Continuing with previous code before Issue 15 fix
+ calendar.setTime(FORMAT.get().parse(time.substring(0, time.length() - 9)));
} catch (ParseException ignored) {
try {
- calendar.setTime(FORMAT_ALTERNATIVE.parse(time.substring(0, time.length() - 9)));
+ calendar.setTime(FORMAT_ALTERNATIVE.get().parse(time.substring(0, time.length() - 9)));
} catch (ParseException ignored2) {
try {
- calendar.setTime(FORMAT_ALTERNATIVE_TWO.parse(time.substring(0, time.length() - 9)));
+ calendar.setTime(FORMAT_ALTERNATIVE_TWO.get().parse(time.substring(0, time.length() - 9)));
} catch (ParseException e) {
logger.warn("Could not parse timestamp {}. Please contact the developer!", time, e);
} | ['src/main/java/de/btobastian/javacord/entities/message/impl/ImplMessage.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 502,730 | 102,266 | 14,074 | 106 | 2,654 | 513 | 42 | 1 | 430 | 75 | 86 | 6 | 0 | 0 | 1970-01-01T00:24:33 | 689 | Java | {'Java': 3278798, 'Groovy': 96336, 'Kotlin': 18569} | Apache License 2.0 |
925 | javacord/javacord/20/19 | javacord | javacord | https://github.com/Javacord/Javacord/issues/19 | https://github.com/Javacord/Javacord/pull/20 | https://github.com/Javacord/Javacord/pull/20 | 1 | fix | Game of User does not update if not playing anything after. | When a user plays a game and leaves it, getGame() still gives the last played game, instead of null.
| 4fcd6ae8890f3e6c9620f88bbedfa79f3b22cc0a | 4f036dbd0062d1195f7d8fe545e3415d2e467ec0 | https://github.com/javacord/javacord/compare/4fcd6ae8890f3e6c9620f88bbedfa79f3b22cc0a...4f036dbd0062d1195f7d8fe545e3415d2e467ec0 | diff --git a/src/main/java/de/btobastian/javacord/utils/handler/user/PresenceUpdateHandler.java b/src/main/java/de/btobastian/javacord/utils/handler/user/PresenceUpdateHandler.java
index 4f9d7745..14622b19 100644
--- a/src/main/java/de/btobastian/javacord/utils/handler/user/PresenceUpdateHandler.java
+++ b/src/main/java/de/btobastian/javacord/utils/handler/user/PresenceUpdateHandler.java
@@ -122,22 +122,27 @@ public class PresenceUpdateHandler extends PacketHandler {
}
// check game
- if (packet.has("game") && !packet.isNull("game")) {
- if (packet.getJSONObject("game").has("name")) {
- String game = packet.getJSONObject("game").get("name").toString();
- String oldGame = user.getGame();
- if ((game == null && oldGame != null)
- || (game != null && oldGame == null)
- || (game != null && !game.equals(oldGame))) {
- ((ImplUser) user).setGame(game);
- List<UserChangeGameListener> listeners = api.getListeners(UserChangeGameListener.class);
- synchronized (listeners) {
- for (UserChangeGameListener listener : listeners) {
- try {
- listener.onUserChangeGame(api, user, oldGame);
- } catch (Throwable t) {
- logger.warn("Uncaught exception in UserChangeGameListener!", t);
- }
+ if (packet.has("game")) {
+ String game;
+ if (!packet.isNull("game")
+ && packet.getJSONObject("game").has("name")
+ && !packet.getJSONObject("game").isNull("name")) {
+ game = packet.getJSONObject("game").get("name").toString();
+ } else {
+ game = null;
+ }
+ String oldGame = user.getGame();
+ if ((game == null && oldGame != null)
+ || (game != null && oldGame == null)
+ || (game != null && !game.equals(oldGame))) {
+ ((ImplUser) user).setGame(game);
+ List<UserChangeGameListener> listeners = api.getListeners(UserChangeGameListener.class);
+ synchronized (listeners) {
+ for (UserChangeGameListener listener : listeners) {
+ try {
+ listener.onUserChangeGame(api, user, oldGame);
+ } catch (Throwable t) {
+ logger.warn("Uncaught exception in UserChangeGameListener!", t);
}
}
} | ['src/main/java/de/btobastian/javacord/utils/handler/user/PresenceUpdateHandler.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 503,940 | 102,505 | 14,101 | 106 | 2,156 | 382 | 37 | 1 | 101 | 19 | 24 | 2 | 0 | 0 | 1970-01-01T00:24:33 | 689 | Java | {'Java': 3278798, 'Groovy': 96336, 'Kotlin': 18569} | Apache License 2.0 |
924 | javacord/javacord/366/361 | javacord | javacord | https://github.com/Javacord/Javacord/issues/361 | https://github.com/Javacord/Javacord/pull/366 | https://github.com/Javacord/Javacord/pull/366 | 1 | fixed | The 50/1 global REST ratelimit is not handled properly | At the moment, hitting the global 50/1 ratelimit (e.g. by trying to send 100 DMs to 100 different users at the same time) is not handled properly by Javacord. | 646310ec573e69b464e500043a23228acced57c4 | ec9f6f719f4a7936d956e7d048060ee33d055554 | https://github.com/javacord/javacord/compare/646310ec573e69b464e500043a23228acced57c4...ec9f6f719f4a7936d956e7d048060ee33d055554 | diff --git a/javacord-core/src/main/java/org/javacord/core/AccountUpdaterDelegateImpl.java b/javacord-core/src/main/java/org/javacord/core/AccountUpdaterDelegateImpl.java
index 1f5fe90a..606e9af7 100644
--- a/javacord-core/src/main/java/org/javacord/core/AccountUpdaterDelegateImpl.java
+++ b/javacord-core/src/main/java/org/javacord/core/AccountUpdaterDelegateImpl.java
@@ -113,12 +113,10 @@ public class AccountUpdaterDelegateImpl implements AccountUpdaterDelegate {
+ Base64.getEncoder().encodeToString(bytes);
body.put("avatar", base64Avatar);
}).thenCompose(aVoid -> new RestRequest<Void>(api, RestMethod.PATCH, RestEndpoint.CURRENT_USER)
- .setRatelimitRetries(0)
.setBody(body)
.execute(result -> null));
}
return new RestRequest<Void>(api, RestMethod.PATCH, RestEndpoint.CURRENT_USER)
- .setRatelimitRetries(0)
.setBody(body)
.execute(result -> null);
} else {
diff --git a/javacord-core/src/main/java/org/javacord/core/DiscordApiImpl.java b/javacord-core/src/main/java/org/javacord/core/DiscordApiImpl.java
index ace50cd4..6974db4f 100644
--- a/javacord-core/src/main/java/org/javacord/core/DiscordApiImpl.java
+++ b/javacord-core/src/main/java/org/javacord/core/DiscordApiImpl.java
@@ -1059,7 +1059,6 @@ public class DiscordApiImpl implements DiscordApi, InternalGloballyAttachableLis
}
httpClient.dispatcher().executorService().shutdown();
httpClient.connectionPool().evictAll();
- ratelimitManager.cleanup();
}
disconnectCalled = true;
}
diff --git a/javacord-core/src/main/java/org/javacord/core/entity/channel/InternalTextChannel.java b/javacord-core/src/main/java/org/javacord/core/entity/channel/InternalTextChannel.java
index 7a95ff3a..7168582a 100644
--- a/javacord-core/src/main/java/org/javacord/core/entity/channel/InternalTextChannel.java
+++ b/javacord-core/src/main/java/org/javacord/core/entity/channel/InternalTextChannel.java
@@ -32,7 +32,6 @@ public interface InternalTextChannel extends TextChannel, InternalTextChannelAtt
@Override
default CompletableFuture<Void> type() {
return new RestRequest<Void>(getApi(), RestMethod.POST, RestEndpoint.CHANNEL_TYPING)
- .setRatelimitRetries(0)
.setUrlParameters(getIdAsString())
.execute(result -> null);
}
diff --git a/javacord-core/src/main/java/org/javacord/core/entity/message/UncachedMessageUtilImpl.java b/javacord-core/src/main/java/org/javacord/core/entity/message/UncachedMessageUtilImpl.java
index 1ed0e33b..f87bcf75 100644
--- a/javacord-core/src/main/java/org/javacord/core/entity/message/UncachedMessageUtilImpl.java
+++ b/javacord-core/src/main/java/org/javacord/core/entity/message/UncachedMessageUtilImpl.java
@@ -61,7 +61,6 @@ public class UncachedMessageUtilImpl implements UncachedMessageUtil, InternalUnc
public CompletableFuture<Void> delete(long channelId, long messageId, String reason) {
return new RestRequest<Void>(api, RestMethod.DELETE, RestEndpoint.MESSAGE_DELETE)
.setUrlParameters(Long.toUnsignedString(channelId), Long.toUnsignedString(messageId))
- .setRatelimitRetries(250)
.setAuditLogReason(reason)
.execute(result -> null);
}
@@ -249,7 +248,6 @@ public class UncachedMessageUtilImpl implements UncachedMessageUtil, InternalUnc
return new RestRequest<Void>(api, RestMethod.PUT, RestEndpoint.REACTION)
.setUrlParameters(
Long.toUnsignedString(channelId), Long.toUnsignedString(messageId), unicodeEmoji, "@me")
- .setRatelimitRetries(500)
.execute(result -> null);
}
@@ -274,7 +272,6 @@ public class UncachedMessageUtilImpl implements UncachedMessageUtil, InternalUnc
);
return new RestRequest<Void>(api, RestMethod.PUT, RestEndpoint.REACTION)
.setUrlParameters(Long.toUnsignedString(channelId), Long.toUnsignedString(messageId), value, "@me")
- .setRatelimitRetries(500)
.execute(result -> null);
}
@@ -357,8 +354,7 @@ public class UncachedMessageUtilImpl implements UncachedMessageUtil, InternalUnc
new RestRequest<List<User>>(api, RestMethod.GET, RestEndpoint.REACTION)
.setUrlParameters(
Long.toUnsignedString(channelId), Long.toUnsignedString(messageId), value)
- .addQueryParameter("limit", "100")
- .setRatelimitRetries(250);
+ .addQueryParameter("limit", "100");
if (!users.isEmpty()) {
request.addQueryParameter("after", users.get(users.size() - 1).getIdAsString());
}
@@ -401,7 +397,6 @@ public class UncachedMessageUtilImpl implements UncachedMessageUtil, InternalUnc
Long.toUnsignedString(messageId),
value,
user.isYourself() ? "@me" : user.getIdAsString())
- .setRatelimitRetries(250)
.execute(result -> null);
}
diff --git a/javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitBucket.java b/javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitBucket.java
index 0be1cc07..915ec879 100644
--- a/javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitBucket.java
+++ b/javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitBucket.java
@@ -3,20 +3,26 @@ package org.javacord.core.util.ratelimit;
import org.javacord.api.DiscordApi;
import org.javacord.core.DiscordApiImpl;
import org.javacord.core.util.rest.RestEndpoint;
+import org.javacord.core.util.rest.RestRequest;
-import java.util.Optional;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
public class RatelimitBucket {
+ // The key is the token, as global ratelimits are shared across the same account.
+ private static final Map<String, Long> globalRatelimitResetTimestamp = new ConcurrentHashMap<>();
+
private final DiscordApiImpl api;
+ private final ConcurrentLinkedQueue<RestRequest<?>> requestQueue = new ConcurrentLinkedQueue<>();
+
private final RestEndpoint endpoint;
private final String majorUrlParameter;
- private volatile long rateLimitResetTimestamp = 0;
- private volatile int rateLimitRemaining = 1;
-
- private volatile boolean hasActiveScheduler = false;
+ private volatile long ratelimitResetTimestamp = 0;
+ private volatile int ratelimitRemaining = 1;
/**
* Creates a RatelimitBucket for the given endpoint / parameter combination.
@@ -45,58 +51,58 @@ public class RatelimitBucket {
}
/**
- * Gets the rest endpoint of the bucket.
+ * Sets a global ratelimit.
*
- * @return The endpoint of the bucket. If it's a global limit, the endpoint will be not be present.
+ * @param api A discord api instance.
+ * @param resetTimestamp The reset timestamp of the global ratelimit.
*/
- public Optional<RestEndpoint> getEndpoint() {
- return Optional.ofNullable(endpoint);
+ public static void setGlobalRatelimitResetTimestamp(DiscordApi api, long resetTimestamp) {
+ globalRatelimitResetTimestamp.put(api.getToken(), resetTimestamp);
}
/**
- * Checks if this bucket has an active scheduler.
+ * Adds the given request to the bucket's queue.
*
- * @return Whether this bucket has an active scheduler or not.
+ * @param request The request to add.
*/
- public synchronized boolean hasActiveScheduler() {
- return hasActiveScheduler;
+ public void addRequestToQueue(RestRequest<?> request) {
+ requestQueue.add(request);
}
/**
- * Sets if this bucket has an active scheduler.
+ * Polls a request from the bucket's queue.
*
- * @param hasActiveScheduler Whether this bucket has an active scheduler or not.
+ * @return The polled request.
*/
- public synchronized void setHasActiveScheduler(boolean hasActiveScheduler) {
- this.hasActiveScheduler = hasActiveScheduler;
+ public RestRequest<?> pollRequestFromQueue() {
+ return requestQueue.poll();
}
/**
- * Checks if there is still "space" in this bucket, which means that you can still send requests without being
- * ratelimited.
+ * Peeks a request from the bucket's queue.
*
- * @return Whether you can send requests without being ratelimited or not.
+ * @return The peeked request.
*/
- public boolean hasSpace() {
- return rateLimitRemaining > 0 || getTimeTillSpaceGetsAvailable() <= 0;
+ public RestRequest<?> peekRequestFromQueue() {
+ return requestQueue.peek();
}
/**
* Sets the remaining requests till ratelimit.
*
- * @param rateLimitRemaining The remaining requests till ratelimit.
+ * @param ratelimitRemaining The remaining requests till ratelimit.
*/
- public void setRateLimitRemaining(int rateLimitRemaining) {
- this.rateLimitRemaining = rateLimitRemaining;
+ public void setRatelimitRemaining(int ratelimitRemaining) {
+ this.ratelimitRemaining = ratelimitRemaining;
}
/**
* Sets the ratelimit reset timestamp.
*
- * @param rateLimitResetTimestamp The rateLimit reset timestamp.
+ * @param ratelimitResetTimestamp The ratelimit reset timestamp.
*/
- public void setRateLimitResetTimestamp(long rateLimitResetTimestamp) {
- this.rateLimitResetTimestamp = rateLimitResetTimestamp;
+ public void setRatelimitResetTimestamp(long ratelimitResetTimestamp) {
+ this.ratelimitResetTimestamp = ratelimitResetTimestamp;
}
/**
@@ -105,11 +111,13 @@ public class RatelimitBucket {
* @return The time in seconds how long you have to wait till there's space in the bucket again.
*/
public int getTimeTillSpaceGetsAvailable() {
- if (rateLimitRemaining > 0) {
+ long globalRatelimitResetTimestamp =
+ RatelimitBucket.globalRatelimitResetTimestamp.getOrDefault(api.getToken(), 0L);
+ long timestamp = System.currentTimeMillis() + (api.getTimeOffset() == null ? 0 : api.getTimeOffset());
+ if (ratelimitRemaining > 0 && (globalRatelimitResetTimestamp - timestamp) <= 0) {
return 0;
}
- long timestamp = System.currentTimeMillis() + (api.getTimeOffset() == null ? 0 : api.getTimeOffset());
- return (int) (rateLimitResetTimestamp - timestamp);
+ return (int) (Math.max(ratelimitResetTimestamp, globalRatelimitResetTimestamp) - timestamp);
}
/**
diff --git a/javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitManager.java b/javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitManager.java
index fa582713..66dc2555 100644
--- a/javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitManager.java
+++ b/javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitManager.java
@@ -2,12 +2,8 @@ package org.javacord.core.util.ratelimit;
import okhttp3.Response;
import org.apache.logging.log4j.Logger;
-import org.javacord.api.DiscordApi;
import org.javacord.api.exception.DiscordException;
-import org.javacord.api.exception.RatelimitException;
import org.javacord.core.DiscordApiImpl;
-import org.javacord.core.util.Cleanupable;
-import org.javacord.core.util.concurrent.ThreadFactory;
import org.javacord.core.util.logging.LoggerUtil;
import org.javacord.core.util.rest.RestRequest;
import org.javacord.core.util.rest.RestRequestResponseInformationImpl;
@@ -15,208 +11,196 @@ import org.javacord.core.util.rest.RestRequestResult;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
-import java.util.HashMap;
+import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
import java.util.function.Function;
/**
* This class manages ratelimits and keeps track of them.
*/
-public class RatelimitManager implements Cleanupable {
+public class RatelimitManager {
/**
* The logger of this class.
*/
private static final Logger logger = LoggerUtil.getLogger(RatelimitManager.class);
- private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(
- 1, new ThreadFactory("Javacord - RatelimitBucket Delay Scheduler - %d", true));
-
- private final Set<RatelimitBucket> buckets = ConcurrentHashMap.newKeySet();
- private final HashMap<RatelimitBucket, ConcurrentLinkedQueue<RestRequest<?>>> queues = new HashMap<>();
-
+ /**
+ * The discord api instance for this ratelimit manager.
+ */
private final DiscordApiImpl api;
/**
- * Creates a new ratelimit manager for the given api.
+ * A set with all buckets.
+ */
+ private final Set<RatelimitBucket> buckets = new HashSet<>();
+
+ /**
+ * Creates a new ratelimit manager.
*
- * @param api The api instance of the bot.
+ * @param api The discord api instance for this ratelimit manager.
*/
- public RatelimitManager(DiscordApi api) {
- this.api = (DiscordApiImpl) api;
+ public RatelimitManager(DiscordApiImpl api) {
+ this.api = api;
}
/**
- * Adds a request to the queue based on the ratelimit bucket.
+ * Queues the given request.
* This method is automatically called when using {@link RestRequest#execute(Function)}!
*
* @param request The request to queue.
*/
public void queueRequest(RestRequest<?> request) {
- // Get the bucket for the current request type.
- RatelimitBucket bucket = buckets
- .parallelStream()
- .filter(b -> b.equals(request.getEndpoint(), request.getMajorUrlParameter().orElse(null)))
- .findAny()
- .orElseGet(() ->
- new RatelimitBucket(api, request.getEndpoint(), request.getMajorUrlParameter().orElse(null)));
-
- // Add bucket to list with buckets
- buckets.add(bucket);
-
- // Get the queue for the current bucket or create a new one if there's no one already
- ConcurrentLinkedQueue<RestRequest<?>> queue =
- queues.computeIfAbsent(bucket, k -> new ConcurrentLinkedQueue<>());
-
- // Add the request to the queue and check if there's already a scheduler working on the queue
- boolean startScheduler = false;
- synchronized (bucket) {
- synchronized (queue) {
- if (bucket.hasActiveScheduler()) {
- queue.add(request);
- } else {
- bucket.setHasActiveScheduler(true);
- queue.add(request);
- startScheduler = true;
- }
- }
+ final RatelimitBucket bucket;
+ final boolean alreadyInQueue;
+ synchronized (buckets) {
+ // Search for a bucket that fits to this request
+ bucket = buckets.stream()
+ .filter(b -> b.equals(request.getEndpoint(), request.getMajorUrlParameter().orElse(null)))
+ .findAny()
+ .orElseGet(() -> new RatelimitBucket(
+ api, request.getEndpoint(), request.getMajorUrlParameter().orElse(null)));
+
+ // Must be executed BEFORE adding the request to the queue
+ alreadyInQueue = bucket.peekRequestFromQueue() != null;
+
+ // Add the bucket to the set of buckets (does nothing if it's already in the set)
+ buckets.add(bucket);
+
+ // Add the request to the bucket's queue
+ bucket.addRequestToQueue(request);
}
- if (!startScheduler) {
+ // If the bucket is already in the queue, there's nothing more to do
+ if (alreadyInQueue) {
return;
}
- int delay = bucket.getTimeTillSpaceGetsAvailable();
- if (delay > 0) {
- synchronized (bucket) {
- synchronized (queue) {
- if (request.incrementRetryCounter()) {
- request.getResult().completeExceptionally(
- new RatelimitException(request.getOrigin(),
- "You have been ratelimited and ran out of retires!",
- request.asRestRequestInformation())
- );
- queue.remove(request);
- bucket.setHasActiveScheduler(false);
- return;
+
+ // Start working of the queue
+ api.getThreadPool().getExecutorService().submit(() -> {
+ RestRequest<?> currentRequest = bucket.peekRequestFromQueue();
+ RestRequestResult result = null;
+ long responseTimestamp = System.currentTimeMillis();
+ while (currentRequest != null) {
+ try {
+ int sleepTime = bucket.getTimeTillSpaceGetsAvailable();
+ if (sleepTime > 0) {
+ logger.debug("Delaying requests to {} for {}ms to prevent hitting ratelimits",
+ bucket, sleepTime);
}
- }
- }
- logger.debug("Delaying requests to {} for {}ms to prevent hitting ratelimits", bucket, delay);
- }
- // Start a scheduler to work off the queue
- scheduler.schedule(() -> api.getThreadPool().getExecutorService().submit(() -> {
- try {
- while (!queue.isEmpty()) {
- if (!bucket.hasSpace()) {
- synchronized (queue) {
- // Remove if we retried to often
- queue.removeIf(req -> {
- if (req.incrementRetryCounter()) {
- req.getResult().completeExceptionally(
- new RatelimitException(req.getOrigin(),
- "You have been ratelimited and ran out of retires!",
- request.asRestRequestInformation())
- );
- return true;
- }
- return false;
- });
- if (queue.isEmpty()) {
- break;
- }
- }
+
+ // Sleep until space is available
+ while (sleepTime > 0) {
try {
- int sleepTime = bucket.getTimeTillSpaceGetsAvailable();
- if (sleepTime > 0) {
- logger.debug("Delaying requests to {} for {}ms to prevent hitting ratelimits",
- bucket, sleepTime);
- Thread.sleep(sleepTime);
- }
+ Thread.sleep(sleepTime);
} catch (InterruptedException e) {
logger.warn("We got interrupted while waiting for a rate limit!", e);
}
+ // Update in case something changed (e.g. because we hit a global ratelimit)
+ sleepTime = bucket.getTimeTillSpaceGetsAvailable();
}
- RestRequest<?> restRequest = queue.peek();
- boolean remove = true;
- RestRequestResult rateLimitHeadersSource = null;
- CompletableFuture<RestRequestResult> restRequestResult = restRequest.getResult();
- try {
- RestRequestResult result = restRequest.executeBlocking();
- rateLimitHeadersSource = result;
-
- long currentTime = System.currentTimeMillis();
- if (api.getTimeOffset() == null) {
- calculateOffset(currentTime, result);
- }
+ // Execute the request
+ result = currentRequest.executeBlocking();
- if (result.getResponse().code() == 429) {
- remove = false;
- rateLimitHeadersSource = null;
- logger.debug("Received a 429 response from Discord! Recalculating time offset...");
- api.setTimeOffset(null);
-
- int retryAfter =
- result.getJsonBody().isNull() ? 0 : result.getJsonBody().get("retry_after").asInt();
- bucket.setRateLimitRemaining(0);
- bucket.setRateLimitResetTimestamp(currentTime + retryAfter);
- } else {
- restRequestResult.complete(result);
- }
+ // Calculate the time offset, if it wasn't done before
+ responseTimestamp = System.currentTimeMillis();
+ } catch (Throwable t) {
+ responseTimestamp = System.currentTimeMillis();
+ if (currentRequest.getResult().isDone()) {
+ logger.warn("Received exception for a request that is already done. "
+ + "This should not be able to happen!", t);
+ }
+ // Try to get the response from the exception if it exists
+ if (t instanceof DiscordException) {
+ result = ((DiscordException) t).getResponse()
+ .map(RestRequestResponseInformationImpl.class::cast)
+ .map(RestRequestResponseInformationImpl::getRestRequestResult)
+ .orElse(null);
+ }
+ // Complete the request
+ currentRequest.getResult().completeExceptionally(t);
+ } finally {
+ try {
+ // Calculate offset
+ calculateOffset(responseTimestamp, result);
+ // Handle the response
+ handleResponse(currentRequest, result, bucket, responseTimestamp);
} catch (Throwable t) {
- if (t instanceof DiscordException) {
- rateLimitHeadersSource = ((DiscordException) t).getResponse()
- .map(response -> ((RestRequestResponseInformationImpl) response))
- .map(RestRequestResponseInformationImpl::getRestRequestResult)
- .orElse(null);
- }
- restRequestResult.completeExceptionally(t);
- } finally {
- try {
- if (rateLimitHeadersSource != null) {
- Response response = rateLimitHeadersSource.getResponse();
- String remaining = response.header("X-RateLimit-Remaining", "1");
- long reset = restRequest
- .getEndpoint()
- .getHardcodedRatelimit()
- .map(ratelimit -> System.currentTimeMillis() + api.getTimeOffset() + ratelimit)
- .orElseGet(
- () -> Long.parseLong(response.header("X-RateLimit-Reset", "0")) * 1000
- );
- String global = response.header("X-RateLimit-Global");
-
- if (global != null && global.equals("true")) {
- // Mark the endpoint as global
- bucket.getEndpoint().ifPresent(endpoint -> endpoint.setGlobal(true));
- }
- bucket.setRateLimitRemaining(Integer.parseInt(remaining));
- bucket.setRateLimitResetTimestamp(reset);
- }
- } catch (Throwable t) {
- if (restRequestResult.isDone()) {
- throw t;
- }
- restRequestResult.completeExceptionally(t);
- }
+ logger.warn("Encountered unexpected exception.", t);
}
- if (remove) {
- queue.remove(restRequest);
+
+ // The request didn't finish, so let's try again
+ if (!currentRequest.getResult().isDone()) {
+ continue;
+ }
+
+ // Poll a new quest
+ synchronized (buckets) {
+ bucket.pollRequestFromQueue();
+ currentRequest = bucket.peekRequestFromQueue();
+ if (currentRequest == null) {
+ buckets.remove(bucket);
+ }
}
- }
- } catch (Throwable t) {
- logger.error("Exception in RatelimitManager! Please contact the developer!", t);
- } finally {
- synchronized (bucket) {
- bucket.setHasActiveScheduler(false);
}
}
- }), delay, TimeUnit.MILLISECONDS);
+ });
+ }
+
+ /**
+ * Updates the ratelimit information and sets the result if the request was successful.
+ *
+ * @param request The request.
+ * @param result The result of the request.
+ * @param bucket The bucket the request belongs to.
+ * @param responseTimestamp The timestamp directly after the response finished.
+ */
+ private void handleResponse(
+ RestRequest<?> request, RestRequestResult result, RatelimitBucket bucket, long responseTimestamp) {
+ if (result == null) {
+ return;
+ }
+ Response response = result.getResponse();
+ boolean global = response.header("X-RateLimit-Global", "false").equalsIgnoreCase("true");
+ int remaining = Integer.valueOf(response.header("X-RateLimit-Remaining", "1"));
+ long reset = request
+ .getEndpoint()
+ .getHardcodedRatelimit()
+ .map(ratelimit -> responseTimestamp + api.getTimeOffset() + ratelimit)
+ .orElseGet(() -> Long.parseLong(response.header("X-RateLimit-Reset", "0")) * 1000);
+
+ // Check if we received a 429 response
+ if (result.getResponse().code() == 429) {
+ int retryAfter =
+ result.getJsonBody().isNull() ? 0 : result.getJsonBody().get("retry_after").asInt();
+
+ if (global) {
+ // We hit a global ratelimit. Time to panic!
+ logger.warn("Hit a global ratelimit! This means you were sending a very large "
+ + "amount within a very short time frame.");
+ RatelimitBucket.setGlobalRatelimitResetTimestamp(api, responseTimestamp + retryAfter);
+ } else {
+ logger.debug("Received a 429 response from Discord! Recalculating time offset...");
+ // Setting the offset to null causes a recalculate for the next request
+ api.setTimeOffset(null);
+
+ // Update the bucket information
+ bucket.setRatelimitRemaining(0);
+ bucket.setRatelimitResetTimestamp(responseTimestamp + retryAfter);
+ }
+ } else {
+ // Check if we didn't already complete it exceptionally.
+ CompletableFuture<RestRequestResult> requestResult = request.getResult();
+ if (!requestResult.isDone()) {
+ requestResult.complete(result);
+ }
+
+ // Update bucket information
+ bucket.setRatelimitRemaining(remaining);
+ bucket.setRatelimitResetTimestamp(reset);
+ }
}
/**
@@ -226,19 +210,23 @@ public class RatelimitManager implements Cleanupable {
* @param result The result of the rest request.
*/
private void calculateOffset(long currentTime, RestRequestResult result) {
- // Discord sends the date in their header in the format RFC_1123_DATE_TIME
- // We use this header to calculate a possible offset between our local time and the discord time
- String date = result.getResponse().header("Date");
- if (date != null) {
- long discordTimestamp = OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME)
- .toInstant().toEpochMilli();
- api.setTimeOffset((discordTimestamp - currentTime));
- logger.debug("Calculated an offset of {} to the Discord time.", api::getTimeOffset);
+ // Double-checked locking for better performance
+ if (api.getTimeOffset() != null) {
+ return;
+ }
+ synchronized (api) {
+ if (api.getTimeOffset() == null) {
+ // Discord sends the date in their header in the format RFC_1123_DATE_TIME
+ // We use this header to calculate a possible offset between our local time and the discord time
+ String date = result.getResponse().header("Date");
+ if (date != null) {
+ long discordTimestamp = OffsetDateTime.parse(date, DateTimeFormatter.RFC_1123_DATE_TIME)
+ .toInstant().toEpochMilli();
+ api.setTimeOffset((discordTimestamp - currentTime));
+ logger.debug("Calculated an offset of {} to the Discord time.", api::getTimeOffset);
+ }
+ }
}
}
- @Override
- public void cleanup() {
- scheduler.shutdown();
- }
}
diff --git a/javacord-core/src/main/java/org/javacord/core/util/rest/RestRequest.java b/javacord-core/src/main/java/org/javacord/core/util/rest/RestRequest.java
index 8b9ef667..0f9a5622 100644
--- a/javacord-core/src/main/java/org/javacord/core/util/rest/RestRequest.java
+++ b/javacord-core/src/main/java/org/javacord/core/util/rest/RestRequest.java
@@ -21,7 +21,6 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
/**
@@ -39,14 +38,11 @@ public class RestRequest<T> {
private final RestEndpoint endpoint;
private volatile boolean includeAuthorizationHeader = true;
- private volatile int ratelimitRetries = 50;
private volatile String[] urlParameters = new String[0];
private final Map<String, String> queryParameters = new HashMap<>();
private final Map<String, String> headers = new HashMap<>();
private volatile String body = null;
- private final AtomicInteger retryCounter = new AtomicInteger();
-
private final CompletableFuture<RestRequestResult> result = new CompletableFuture<>();
/**
@@ -213,20 +209,6 @@ public class RestRequest<T> {
return this;
}
- /**
- * Sets the amount of ratelimit retries we should use with this request.
- *
- * @param retries The amount of ratelimit retries.
- * @return The current instance in order to chain call methods.
- */
- public RestRequest<T> setRatelimitRetries(int retries) {
- if (retries < 0) {
- throw new IllegalArgumentException("Retries cannot be less than 0!");
- }
- this.ratelimitRetries = retries;
- return this;
- }
-
/**
* Sets a custom major parameter.
*
@@ -270,15 +252,6 @@ public class RestRequest<T> {
return this;
}
- /**
- * Increments the amounts of ratelimit retries.
- *
- * @return <code>true</code> if the maximum ratelimit retries were exceeded.
- */
- public boolean incrementRetryCounter() {
- return retryCounter.incrementAndGet() > ratelimitRetries;
- }
-
/**
* Executes the request. This will automatically retry if we hit a ratelimit.
* | ['javacord-core/src/main/java/org/javacord/core/entity/channel/InternalTextChannel.java', 'javacord-core/src/main/java/org/javacord/core/DiscordApiImpl.java', 'javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitManager.java', 'javacord-core/src/main/java/org/javacord/core/util/ratelimit/RatelimitBucket.java', 'javacord-core/src/main/java/org/javacord/core/util/rest/RestRequest.java', 'javacord-core/src/main/java/org/javacord/core/entity/message/UncachedMessageUtilImpl.java', 'javacord-core/src/main/java/org/javacord/core/AccountUpdaterDelegateImpl.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 1,609,067 | 334,267 | 48,975 | 549 | 23,423 | 4,148 | 446 | 7 | 158 | 29 | 46 | 1 | 0 | 0 | 1970-01-01T00:25:33 | 689 | Java | {'Java': 3278798, 'Groovy': 96336, 'Kotlin': 18569} | Apache License 2.0 |
923 | javacord/javacord/394/260 | javacord | javacord | https://github.com/Javacord/Javacord/issues/260 | https://github.com/Javacord/Javacord/pull/394 | https://github.com/Javacord/Javacord/pull/394 | 1 | fixes | Message cache can be outdated | In some cases there might be messages in the cache which are no longer up to date:
- Message gets send in a channel with read-access
- Bot loses read-access for this channel
- Message gets edited
- Bot gains read-access again
=> The message content is out of date, but still in the cache
This can cause some issues with methods like `MessageEditEvent#getOldContent()`.
**Possible solution:**
- Remove a message from the cache when the bot loses read-access | 61802fa365a75a474ac97363d753a41585450cca | 83f246ce7f0f398538f2d7dbf66a70b0a5466e6b | https://github.com/javacord/javacord/compare/61802fa365a75a474ac97363d753a41585450cca...83f246ce7f0f398538f2d7dbf66a70b0a5466e6b | diff --git a/javacord-core/src/main/java/org/javacord/core/DiscordApiImpl.java b/javacord-core/src/main/java/org/javacord/core/DiscordApiImpl.java
index 374da79a..70f5d20e 100644
--- a/javacord-core/src/main/java/org/javacord/core/DiscordApiImpl.java
+++ b/javacord-core/src/main/java/org/javacord/core/DiscordApiImpl.java
@@ -78,7 +78,9 @@ import java.util.WeakHashMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
import java.util.function.Function;
+import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
@@ -1330,6 +1332,38 @@ public class DiscordApiImpl implements DiscordApi, DispatchQueueSelector {
}
}
+ /**
+ * Get messages from the cache that satisfy a given condition.
+ *
+ * @param filter The filter for messages to be included.
+ * @return A set of cached messages satisfying the condition.
+ */
+ public MessageSet getCachedMessagesWhere(Predicate<Message> filter) {
+ synchronized (messages) {
+ return messages.values().stream()
+ .map(Reference::get)
+ .filter(Objects::nonNull)
+ .filter(filter)
+ .collect(Collectors.toCollection(MessageSetImpl::new));
+ }
+ }
+
+ /**
+ * Execute a task for every message in cache that satisfied a given condition.
+ *
+ * @param filter The condition on which to execute the code.
+ * @param action The action to be applied to the messages.
+ */
+ public void forEachCachedMessageWhere(Predicate<Message> filter, Consumer<Message> action) {
+ synchronized (messages) {
+ messages.values().stream()
+ .map(Reference::get)
+ .filter(Objects::nonNull)
+ .filter(filter)
+ .forEach(action);
+ }
+ }
+
@Override
public Optional<Message> getCachedMessageById(long id) {
return Optional.ofNullable(messages.get(id)).map(Reference::get);
diff --git a/javacord-core/src/main/java/org/javacord/core/util/handler/ResumedHandler.java b/javacord-core/src/main/java/org/javacord/core/util/handler/ResumedHandler.java
index 02b6603b..110bf4ce 100644
--- a/javacord-core/src/main/java/org/javacord/core/util/handler/ResumedHandler.java
+++ b/javacord-core/src/main/java/org/javacord/core/util/handler/ResumedHandler.java
@@ -23,4 +23,4 @@ public class ResumedHandler extends PacketHandler {
// NOP
}
-}
\\ No newline at end of file
+}
diff --git a/javacord-core/src/main/java/org/javacord/core/util/handler/channel/ChannelDeleteHandler.java b/javacord-core/src/main/java/org/javacord/core/util/handler/channel/ChannelDeleteHandler.java
index ac241439..6f85c83e 100644
--- a/javacord-core/src/main/java/org/javacord/core/util/handler/channel/ChannelDeleteHandler.java
+++ b/javacord-core/src/main/java/org/javacord/core/util/handler/channel/ChannelDeleteHandler.java
@@ -108,6 +108,10 @@ public class ChannelDeleteHandler extends PacketHandler {
.ifPresent(server -> server.getTextChannelById(channelId).ifPresent(channel -> {
dispatchServerChannelDeleteEvent(channel);
((ServerImpl) server).removeChannelFromCache(channel.getId());
+ api.forEachCachedMessageWhere(
+ msg -> msg.getChannel().getId() == channelId,
+ msg -> api.removeMessageFromCache(msg.getId())
+ );
}));
api.removeObjectListeners(ServerTextChannel.class, channelId);
api.removeObjectListeners(ServerChannel.class, channelId);
@@ -150,7 +154,10 @@ public class ChannelDeleteHandler extends PacketHandler {
api.removeObjectListeners(VoiceChannel.class, channelId);
api.removeObjectListeners(TextChannel.class, channelId);
api.removeObjectListeners(Channel.class, channelId);
-
+ api.forEachCachedMessageWhere(
+ msg -> msg.getChannel().getId() == privateChannel.getId(),
+ msg -> api.removeMessageFromCache(msg.getId())
+ );
recipient.setChannel(null);
});
}
@@ -172,6 +179,10 @@ public class ChannelDeleteHandler extends PacketHandler {
api.removeObjectListeners(VoiceChannel.class, channelId);
api.removeObjectListeners(TextChannel.class, channelId);
api.removeObjectListeners(Channel.class, channelId);
+ api.forEachCachedMessageWhere(
+ msg -> msg.getChannel().getId() == groupChannel.getId(),
+ msg -> api.removeMessageFromCache(msg.getId())
+ );
});
}
diff --git a/javacord-core/src/main/java/org/javacord/core/util/handler/channel/ChannelUpdateHandler.java b/javacord-core/src/main/java/org/javacord/core/util/handler/channel/ChannelUpdateHandler.java
index b6ae10bb..f077ea24 100644
--- a/javacord-core/src/main/java/org/javacord/core/util/handler/channel/ChannelUpdateHandler.java
+++ b/javacord-core/src/main/java/org/javacord/core/util/handler/channel/ChannelUpdateHandler.java
@@ -47,6 +47,7 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
/**
* Handles the channel update packet.
@@ -128,6 +129,7 @@ public class ChannelUpdateHandler extends PacketHandler {
}
}
+ final AtomicBoolean areYouAffected = new AtomicBoolean(false);
ChannelCategory oldCategory = channel.asCategorizable().flatMap(Categorizable::getCategory).orElse(null);
ChannelCategory newCategory = jsonChannel.hasNonNull("parent_id")
? channel.getServer().getChannelCategoryById(jsonChannel.get("parent_id").asLong(-1)).orElse(null)
@@ -142,7 +144,6 @@ public class ChannelUpdateHandler extends PacketHandler {
((ServerVoiceChannelImpl) channel).setParentId(newCategory == null ? -1 : newCategory.getId());
}
channel.setPosition(newRawPosition);
-
int newPosition = channel.getPosition();
ServerChannelChangePositionEvent event = new ServerChannelChangePositionEventImpl(
@@ -188,6 +189,9 @@ public class ChannelUpdateHandler extends PacketHandler {
if (server.isReady()) {
dispatchServerChannelChangeOverwrittenPermissionsEvent(
channel, newOverwrittenPermissions, oldOverwrittenPermissions, entity);
+ areYouAffected.compareAndSet(false, entity instanceof User && ((User) entity).isYourself());
+ areYouAffected.compareAndSet(false, entity instanceof Role
+ && ((Role) entity).getUsers().stream().anyMatch(User::isYourself));
}
}
}
@@ -209,6 +213,7 @@ public class ChannelUpdateHandler extends PacketHandler {
if (server.isReady()) {
dispatchServerChannelChangeOverwrittenPermissionsEvent(
channel, PermissionsImpl.EMPTY_PERMISSIONS, oldPermissions, user);
+ areYouAffected.compareAndSet(false, user.isYourself());
}
});
}
@@ -225,9 +230,17 @@ public class ChannelUpdateHandler extends PacketHandler {
if (server.isReady()) {
dispatchServerChannelChangeOverwrittenPermissionsEvent(
channel, PermissionsImpl.EMPTY_PERMISSIONS, oldPermissions, role);
+ areYouAffected.compareAndSet(false, role.getUsers().stream().anyMatch(User::isYourself));
}
});
}
+
+ if (areYouAffected.get() && !channel.canYouSee()) {
+ api.forEachCachedMessageWhere(
+ msg -> msg.getChannel().getId() == channelId,
+ msg -> api.removeMessageFromCache(msg.getId())
+ );
+ }
}
/**
diff --git a/javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildDeleteHandler.java b/javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildDeleteHandler.java
index 7aa0b4d1..95f50a11 100644
--- a/javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildDeleteHandler.java
+++ b/javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildDeleteHandler.java
@@ -34,6 +34,10 @@ public class GuildDeleteHandler extends PacketHandler {
api.getEventDispatcher().dispatchServerBecomesUnavailableEvent(
(DispatchQueueSelector) server, server, event);
+ api.forEachCachedMessageWhere(
+ msg -> msg.getServer().map(s -> s.getId() == serverId).orElse(false),
+ msg -> api.removeMessageFromCache(msg.getId())
+ );
});
api.removeServerFromCache(serverId);
return;
@@ -44,6 +48,10 @@ public class GuildDeleteHandler extends PacketHandler {
api.getEventDispatcher().dispatchServerLeaveEvent((DispatchQueueSelector) server, server, event);
});
api.removeObjectListeners(Server.class, serverId);
+ api.forEachCachedMessageWhere(
+ msg -> msg.getServer().map(s -> s.getId() == serverId).orElse(false),
+ msg -> api.removeMessageFromCache(msg.getId())
+ );
api.removeServerFromCache(serverId);
}
diff --git a/javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildMemberRemoveHandler.java b/javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildMemberRemoveHandler.java
index e126bc4c..64138c72 100644
--- a/javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildMemberRemoveHandler.java
+++ b/javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildMemberRemoveHandler.java
@@ -34,7 +34,8 @@ public class GuildMemberRemoveHandler extends PacketHandler {
ServerMemberLeaveEvent event = new ServerMemberLeaveEventImpl(server, user);
api.getEventDispatcher().dispatchServerMemberLeaveEvent(server, server, user, event);
+
});
}
-}
\\ No newline at end of file
+}
diff --git a/javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildMemberUpdateHandler.java b/javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildMemberUpdateHandler.java
index 94128c3a..ee952570 100644
--- a/javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildMemberUpdateHandler.java
+++ b/javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildMemberUpdateHandler.java
@@ -2,6 +2,7 @@ package org.javacord.core.util.handler.guild;
import com.fasterxml.jackson.databind.JsonNode;
import org.javacord.api.DiscordApi;
+import org.javacord.api.entity.channel.ServerTextChannel;
import org.javacord.api.entity.permission.Role;
import org.javacord.api.entity.user.User;
import org.javacord.api.event.server.role.UserRoleAddEvent;
@@ -19,6 +20,9 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
+import java.util.Set;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
/**
* Handles the guild member update packet.
@@ -95,6 +99,18 @@ public class GuildMemberUpdateHandler extends PacketHandler {
(DispatchQueueSelector) role.getServer(), role, role.getServer(), user, event);
}
}
+
+ if (user.isYourself()) {
+ Set<Long> unreadableChannels = server.getTextChannels().stream()
+ .filter(((Predicate<ServerTextChannel>)ServerTextChannel::canYouSee).negate())
+ .map(ServerTextChannel::getId)
+ .collect(Collectors.toSet());
+ api.forEachCachedMessageWhere(
+ msg -> unreadableChannels.contains(msg.getChannel().getId()),
+ msg -> api.removeMessageFromCache(msg.getId())
+ );
+ }
+
});
}
diff --git a/javacord-core/src/main/java/org/javacord/core/util/handler/guild/role/GuildRoleUpdateHandler.java b/javacord-core/src/main/java/org/javacord/core/util/handler/guild/role/GuildRoleUpdateHandler.java
index 6767d318..0d7696fa 100644
--- a/javacord-core/src/main/java/org/javacord/core/util/handler/guild/role/GuildRoleUpdateHandler.java
+++ b/javacord-core/src/main/java/org/javacord/core/util/handler/guild/role/GuildRoleUpdateHandler.java
@@ -2,7 +2,9 @@ package org.javacord.core.util.handler.guild.role;
import com.fasterxml.jackson.databind.JsonNode;
import org.javacord.api.DiscordApi;
+import org.javacord.api.entity.channel.ServerTextChannel;
import org.javacord.api.entity.permission.Permissions;
+import org.javacord.api.entity.user.User;
import org.javacord.api.event.server.role.RoleChangeColorEvent;
import org.javacord.api.event.server.role.RoleChangeHoistEvent;
import org.javacord.api.event.server.role.RoleChangeMentionableEvent;
@@ -21,6 +23,9 @@ import org.javacord.core.util.event.DispatchQueueSelector;
import org.javacord.core.util.gateway.PacketHandler;
import java.awt.Color;
+import java.util.Set;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
/**
* Handles the guild role create packet.
@@ -97,6 +102,17 @@ public class GuildRoleUpdateHandler extends PacketHandler {
api.getEventDispatcher().dispatchRoleChangePermissionsEvent(
(DispatchQueueSelector) role.getServer(), role, role.getServer(), event);
+ // If bot is affected remove messages from cache that are no longer visible
+ if (role.getUsers().stream().anyMatch(User::isYourself)) {
+ Set<Long> unreadableChannels = role.getServer().getTextChannels().stream()
+ .filter(((Predicate<ServerTextChannel>)ServerTextChannel::canYouSee).negate())
+ .map(ServerTextChannel::getId)
+ .collect(Collectors.toSet());
+ api.forEachCachedMessageWhere(
+ msg -> unreadableChannels.contains(msg.getChannel().getId()),
+ msg -> api.removeMessageFromCache(msg.getId())
+ );
+ }
}
int oldPosition = role.getPosition(); | ['javacord-core/src/main/java/org/javacord/core/DiscordApiImpl.java', 'javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildMemberUpdateHandler.java', 'javacord-core/src/main/java/org/javacord/core/util/handler/channel/ChannelUpdateHandler.java', 'javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildMemberRemoveHandler.java', 'javacord-core/src/main/java/org/javacord/core/util/handler/channel/ChannelDeleteHandler.java', 'javacord-core/src/main/java/org/javacord/core/util/handler/guild/role/GuildRoleUpdateHandler.java', 'javacord-core/src/main/java/org/javacord/core/util/handler/guild/GuildDeleteHandler.java', 'javacord-core/src/main/java/org/javacord/core/util/handler/ResumedHandler.java'] | {'.java': 8} | 8 | 8 | 0 | 0 | 8 | 1,720,206 | 356,802 | 52,007 | 568 | 5,040 | 867 | 107 | 8 | 470 | 78 | 100 | 12 | 0 | 0 | 1970-01-01T00:25:40 | 689 | Java | {'Java': 3278798, 'Groovy': 96336, 'Kotlin': 18569} | Apache License 2.0 |
922 | javacord/javacord/456/398 | javacord | javacord | https://github.com/Javacord/Javacord/issues/398 | https://github.com/Javacord/Javacord/pull/456 | https://github.com/Javacord/Javacord/pull/456 | 1 | fixes | Javacord does not wait for all servers being loaded | Sometimes Javacord does not wait for all server being loaded on startup.
I don't know what's causing it, but I can imagine that it's caused by a slow websocket connection in combination with a very large server (Discord API has > 43.000 and Discord Bots > 37.000 members).
I feel like that there's something wrong in our handling, as we already wait a pretty long time.
```java
DiscordApi api = new DiscordApiBuilder()
.setToken("nope")
.login()
.join();
System.out.println("Logged in");
```
```
2018-10-24 21:14:38,934 <DEBUG> <main> <[]> <{}> <org.javacord.core.DiscordApiBuilderDelegateImpl> Creating shard 1 of 1
2018-10-24 21:14:39,526 <DEBUG> <Javacord - Central ExecutorService - 2> <[]> <{shard=0}> <org.javacord.core.util.rest.RestRequest> Trying to send GET request to https://discordapp.com/api/v6/gateway
2018-10-24 21:14:39,872 <DEBUG> <Javacord - Central ExecutorService - 2> <[]> <{shard=0}> <org.javacord.core.util.rest.RestRequest> Sent GET request to https://discordapp.com/api/v6/gateway and received status code 200 with body {"url": "wss://gateway.discord.gg"}
2018-10-24 21:14:39,884 <DEBUG> <Javacord - Central ExecutorService - 2> <[]> <{shard=0}> <org.javacord.core.util.ratelimit.RatelimitManager> Calculated an offset of -872 to the Discord time.
2018-10-24 21:14:40,322 <DEBUG> <ReadingThread> <[]> <{shard=0}> <org.javacord.core.util.gateway.DiscordWebSocketAdapter> Received HELLO packet
2018-10-24 21:14:40,325 <DEBUG> <Javacord - Central Scheduler - 1> <[]> <{shard=0}> <org.javacord.core.util.gateway.DiscordWebSocketAdapter> Sent heartbeat (interval: 41250)
2018-10-24 21:14:40,325 <DEBUG> <ReadingThread> <[]> <{shard=0}> <org.javacord.core.util.gateway.DiscordWebSocketAdapter> Sending identify packet
2018-10-24 21:14:40,460 <DEBUG> <ReadingThread> <[]> <{shard=0}> <org.javacord.core.util.gateway.DiscordWebSocketAdapter> Heartbeat ACK received
2018-10-24 21:14:40,525 <DEBUG> <ReadingThread> <[]> <{shard=0}> <org.javacord.core.util.gateway.DiscordWebSocketAdapter> Received READY packet
2018-10-24 21:14:40,740 <DEBUG> <Javacord - Handlers Processor> <[]> <{shard=0}> <org.javacord.core.util.gateway.DiscordWebSocketAdapter> Queued Server (id: 151037561152733184, name: Javacord) for request guild members packet
2018-10-24 21:14:40,742 <DEBUG> <Javacord - Request Server Members Queue Consumer> <[]> <{shard=0}> <org.javacord.core.util.gateway.DiscordWebSocketAdapter> Sending request guild members packet {"op":8,"d":{"query":"","limit":0,"guild_id":"151037561152733184"}}
2018-10-24 21:14:44,539 <DEBUG> <Javacord - Central ExecutorService - 1> <[]> <{shard=0}> <org.javacord.core.util.rest.RestRequest> Trying to send GET request to https://discordapp.com/api/v6/oauth2/applications/@me
2018-10-24 21:14:44,686 <DEBUG> <Javacord - Central ExecutorService - 1> <[]> <{shard=0}> <org.javacord.core.util.rest.RestRequest> Sent GET request to https://discordapp.com/api/v6/oauth2/applications/@me and received status code 200 with body {"description": "", "name": "Bastians Bot", "owner": {"username": "Bastian", "discriminator": "0001", "id": "157862224206102529", "avatar": "a_796bef60840438a232f53f24ba29165c"}, "bot_public": true, "bot_require_code_grant": false, "id": "157889000391180288", "icon": "a20d7ce51ae6bb0e3ef78195468e0d46"}
2018-10-24 21:14:44,687 <DEBUG> <Javacord - Central ExecutorService - 1> <[]> <{shard=0}> <org.javacord.core.util.ratelimit.RatelimitManager> Calculated an offset of -686 to the Discord time.
Logged in
2018-10-24 21:14:44,732 <DEBUG> <Javacord - Handlers Processor> <[]> <{shard=0}> <org.javacord.core.util.gateway.DiscordWebSocketAdapter> Queued Server (id: 110373943822540800, name: Discord Bots) for request guild members packet
2018-10-24 21:14:44,732 <DEBUG> <Javacord - Request Server Members Queue Consumer> <[]> <{shard=0}> <org.javacord.core.util.gateway.DiscordWebSocketAdapter> Sending request guild members packet {"op":8,"d":{"query":"","limit":0,"guild_id":"110373943822540800"}}
2018-10-24 21:14:49,169 <DEBUG> <Javacord - Handlers Processor> <[]> <{shard=0}> <org.javacord.core.util.gateway.DiscordWebSocketAdapter> Queued Server (id: 81384788765712384, name: Discord API) for request guild members packet
2018-10-24 21:14:49,169 <DEBUG> <Javacord - Request Server Members Queue Consumer> <[]> <{shard=0}> <org.javacord.core.util.gateway.DiscordWebSocketAdapter> Sending request guild members packet {"op":8,"d":{"query":"","limit":0,"guild_id":"81384788765712384"}}
``` | 15f07ce3d58233176fd318476a87d2bc6d79dedc | a1beb9aff53a51a171fb2a9959a2fa6d0a71859c | https://github.com/javacord/javacord/compare/15f07ce3d58233176fd318476a87d2bc6d79dedc...a1beb9aff53a51a171fb2a9959a2fa6d0a71859c | diff --git a/javacord-core/src/main/java/org/javacord/core/util/gateway/DiscordWebSocketAdapter.java b/javacord-core/src/main/java/org/javacord/core/util/gateway/DiscordWebSocketAdapter.java
index 4654b9eb..9a1cb57a 100644
--- a/javacord-core/src/main/java/org/javacord/core/util/gateway/DiscordWebSocketAdapter.java
+++ b/javacord-core/src/main/java/org/javacord/core/util/gateway/DiscordWebSocketAdapter.java
@@ -529,9 +529,9 @@ public class DiscordWebSocketAdapter extends WebSocketAdapter {
allUsersLoaded = api.getAllServers().stream()
.noneMatch(server -> server.getMemberCount() != server.getMembers().size());
}
- if (sameUnavailableServerCounter > 20
+ if (sameUnavailableServerCounter > 1000
&& lastGuildMembersChunkReceived + 5000 < System.currentTimeMillis()) {
- // It has been more than two seconds since no more servers became available and more
+ // It has been more than 1 minute since no more servers became available and more
// than five seconds since the last guild member chunk event was received. We
// can assume that this will not change anytime soon, most likely because Discord
// itself has some issues. Let's break the loop! | ['javacord-core/src/main/java/org/javacord/core/util/gateway/DiscordWebSocketAdapter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,716,490 | 356,108 | 51,940 | 568 | 368 | 60 | 4 | 1 | 4,526 | 424 | 1,449 | 34 | 4 | 2 | 1970-01-01T00:25:53 | 689 | Java | {'Java': 3278798, 'Groovy': 96336, 'Kotlin': 18569} | Apache License 2.0 |
921 | javacord/javacord/510/505 | javacord | javacord | https://github.com/Javacord/Javacord/issues/505 | https://github.com/Javacord/Javacord/pull/510 | https://github.com/Javacord/Javacord/pull/510 | 1 | closes | Regions | Discord changed the avaible server-regions. Please update them.
There is e.g. only one europe region now instead of east and west. | bad5dfb76f6593b1a4c2a1205603479903ab29ea | 50c22eeee13600a663a4bb1463754f425509e31b | https://github.com/javacord/javacord/compare/bad5dfb76f6593b1a4c2a1205603479903ab29ea...50c22eeee13600a663a4bb1463754f425509e31b | diff --git a/javacord-api/src/main/java/org/javacord/api/entity/Region.java b/javacord-api/src/main/java/org/javacord/api/entity/Region.java
index ddf5cce9..f59a25ee 100644
--- a/javacord-api/src/main/java/org/javacord/api/entity/Region.java
+++ b/javacord-api/src/main/java/org/javacord/api/entity/Region.java
@@ -8,6 +8,7 @@ public enum Region implements Nameable {
// "Normal" regions
AMSTERDAM("amsterdam", "Amsterdam", false),
BRAZIL("brazil", "Brazil", false),
+ EUROPE("europe", "Europe", false),
EU_WEST("eu-west", "EU West", false),
EU_CENTRAL("eu-central", "EU Central", false),
FRANKFURT("frankfurt", "Frankfurt", false),
@@ -15,6 +16,7 @@ public enum Region implements Nameable {
JAPAN("japan", "Japan", false),
LONDON("london", "London", false),
RUSSIA("russia", "Russia", false),
+ INDIA("india", "India", false),
SINGAPORE("singapore", "Singapore", false),
SYDNEY("sydney", "Sydney", false),
US_EAST("us-east", "US East", false), | ['javacord-api/src/main/java/org/javacord/api/entity/Region.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,749,537 | 362,398 | 52,628 | 568 | 76 | 24 | 2 | 1 | 134 | 21 | 31 | 3 | 0 | 0 | 1970-01-01T00:26:14 | 689 | Java | {'Java': 3278798, 'Groovy': 96336, 'Kotlin': 18569} | Apache License 2.0 |
920 | javacord/javacord/550/526 | javacord | javacord | https://github.com/Javacord/Javacord/issues/526 | https://github.com/Javacord/Javacord/pull/550 | https://github.com/Javacord/Javacord/pull/550 | 1 | fixes | http status codes being ignored | JavaCord will attempt to parse Discord's repsonse on certain actions (e.g. sendMessage()) without checking the http response code. This results in HTML being parsed as JSON, and an exception being thrown. Attached is a stacktrace of when the API returned an HTTP 502, but JavaCord tried parsing the response as JSON anyway.
https://hastebin.com/zodofazefi.php
| 6c78cc91ee8872288c089196e146ebfde063e870 | c5b1e711ae7bf5677ebe9d3394e07f9403eb5d5a | https://github.com/javacord/javacord/compare/6c78cc91ee8872288c089196e146ebfde063e870...c5b1e711ae7bf5677ebe9d3394e07f9403eb5d5a | diff --git a/javacord-core/src/main/java/org/javacord/core/util/rest/RestRequestResult.java b/javacord-core/src/main/java/org/javacord/core/util/rest/RestRequestResult.java
index 515aa667..a983cef7 100644
--- a/javacord-core/src/main/java/org/javacord/core/util/rest/RestRequestResult.java
+++ b/javacord-core/src/main/java/org/javacord/core/util/rest/RestRequestResult.java
@@ -1,10 +1,13 @@
package org.javacord.core.util.rest;
+import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.NullNode;
import okhttp3.Response;
import okhttp3.ResponseBody;
+import org.apache.logging.log4j.Logger;
+import org.javacord.core.util.logging.LoggerUtil;
import java.io.IOException;
import java.util.Optional;
@@ -14,6 +17,11 @@ import java.util.Optional;
*/
public class RestRequestResult {
+ /**
+ * The logger of this class.
+ */
+ private static final Logger logger = LoggerUtil.getLogger(RestRequestResult.class);
+
private final RestRequest<?> request;
private final Response response;
private final ResponseBody body;
@@ -37,7 +45,14 @@ public class RestRequestResult {
} else {
stringBody = body.string();
ObjectMapper mapper = request.getApi().getObjectMapper();
- JsonNode jsonBody = mapper.readTree(stringBody);
+ JsonNode jsonBody;
+ try {
+ jsonBody = mapper.readTree(stringBody);
+ } catch (JsonParseException e) {
+ // This can happen if Discord sends garbage (see https://github.com/Javacord/Javacord/issues/526)
+ logger.debug("Failed to parse json response", e);
+ jsonBody = null;
+ }
this.jsonBody = jsonBody == null ? NullNode.getInstance() : jsonBody;
}
}
@@ -80,7 +95,7 @@ public class RestRequestResult {
/**
* Gets the json body of the response.
- * Returns a {@link NullNode} if the response had no body.
+ * Returns a {@link NullNode} if the response had no body or the body is not in a valid json format.
*
* @return The json body of the response.
*/ | ['javacord-core/src/main/java/org/javacord/core/util/rest/RestRequestResult.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,787,134 | 370,471 | 53,822 | 576 | 906 | 186 | 19 | 1 | 364 | 53 | 84 | 4 | 1 | 0 | 1970-01-01T00:26:28 | 689 | Java | {'Java': 3278798, 'Groovy': 96336, 'Kotlin': 18569} | Apache License 2.0 |
919 | javacord/javacord/23/22 | javacord | javacord | https://github.com/Javacord/Javacord/issues/22 | https://github.com/Javacord/Javacord/pull/23 | https://github.com/Javacord/Javacord/issues/22#issuecomment-249503828 | 1 | fixed | Can't login to 'real' account | I'm attempting to log into a real account using the API. But it's throwing an error and an exception saying this:
> java.lang.IllegalArgumentException: 400 Bad request! Maybe wrong email or password?
> at de.btobastian.javacord.ImplDiscordAPI.requestTokenBlocking(ImplDiscordAPI.java:1014)
> at de.btobastian.javacord.ImplDiscordAPI.connectBlocking(ImplDiscordAPI.java:160)
> at de.btobastian.javacord.ImplDiscordAPI$2.call(ImplDiscordAPI.java:147)
> at de.btobastian.javacord.ImplDiscordAPI$2.call(ImplDiscordAPI.java:144)
I made sure the email and password are right. I even went to the discord program, logged out. Copied the email I put. Put it in the email box, copied the password from the program and hit login on discord, and it logged me in. So I do not know what the problem is :/ . I Do not have 2-FA enabled. I only require an email and password to login.
| 3e31b863d4cb36093f110bb1e8dcd23837998174 | fef7d09e491121c1d90fd8db4dce42d2655392e5 | https://github.com/javacord/javacord/compare/3e31b863d4cb36093f110bb1e8dcd23837998174...fef7d09e491121c1d90fd8db4dce42d2655392e5 | diff --git a/src/main/java/de/btobastian/javacord/ImplDiscordAPI.java b/src/main/java/de/btobastian/javacord/ImplDiscordAPI.java
index df7d9a13..6d87dcdd 100644
--- a/src/main/java/de/btobastian/javacord/ImplDiscordAPI.java
+++ b/src/main/java/de/btobastian/javacord/ImplDiscordAPI.java
@@ -72,6 +72,11 @@ import java.util.concurrent.Future;
* The implementation of {@link DiscordAPI}.
*/
public class ImplDiscordAPI implements DiscordAPI {
+
+ // If you have a better way to retrieve this other than manually, please do implement
+ private static final String JAVA_VERSION = Runtime.class.getPackage().getImplementationVersion();
+ private static final String VERSION = "2.0.11";
+ private static final String UNIREST_VERSION = "1.4.8";
/**
* The logger of this class.
@@ -1006,8 +1011,9 @@ public class ImplDiscordAPI implements DiscordAPI {
try {
logger.debug("Trying to request token (email: {}, password: {})", email, password.replaceAll(".", "*"));
HttpResponse<JsonNode> response = Unirest.post("https://discordapp.com/api/auth/login")
- .field("email", email)
- .field("password", password)
+ .header("User-Agent", "DiscordBot (https://github.com/BtoBastian/Javacord " + VERSION + ") Java/" + JAVA_VERSION + " Unirest/" + UNIREST_VERSION)
+ .header("Content-Type", "application/json")
+ .body("{\\"email\\":\\"" + email +"\\", \\"password\\":\\"" + password + "\\"}")
.asJson();
JSONObject jsonResponse = response.getBody().getObject();
if (response.getStatus() == 400) { | ['src/main/java/de/btobastian/javacord/ImplDiscordAPI.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 504,229 | 102,557 | 14,106 | 106 | 723 | 160 | 10 | 1 | 878 | 114 | 239 | 10 | 0 | 0 | 1970-01-01T00:24:34 | 689 | Java | {'Java': 3278798, 'Groovy': 96336, 'Kotlin': 18569} | Apache License 2.0 |
113 | stripe/stripe-java/1582/1581 | stripe | stripe-java | https://github.com/stripe/stripe-java/issues/1581 | https://github.com/stripe/stripe-java/pull/1582 | https://github.com/stripe/stripe-java/pull/1582 | 1 | fixes | Customer.retrievePaymentMethod() is broken | ### Describe the bug
unable to retrieve a customer's payment method using: `Customer.retrievePaymentMethod()`
the `Customer.retrievePaymentMethod()` method is broken: when the URL parameters are inserted by `String.format()` it inserts the customer id for both the customer and the payment method instead of inserting the correct payment method id
### To Reproduce
```java
...
Customer customer = ...
customer.retrievePaymentMethod(customer.getId(), ..., ...)
...
```
### Expected behavior
the method should take in the payment method id, not the customer id, in order for the `String.format()` to work correctly
### Code snippets
https://github.com/stripe/stripe-java/blob/master/src/main/java/com/stripe/model/Customer.java#L561-L588
Look at the String.format lines of code, they are not inserting the id's correctly:
```java
/** Retrieves a PaymentMethod object for a given Customer. */
public PaymentMethod retrievePaymentMethod(
String customer, Map<String, Object> params, RequestOptions options) throws StripeException {
String url =
ApiResource.fullUrl(
Stripe.getApiBase(),
options,
String.format(
"/v1/customers/%s/payment_methods/%s",
ApiResource.urlEncodeId(customer), ApiResource.urlEncodeId(this.getId())));
return ApiResource.request(
ApiResource.RequestMethod.GET, url, params, PaymentMethod.class, options);
}
/** Retrieves a PaymentMethod object for a given Customer. */
public PaymentMethod retrievePaymentMethod(
String customer, CustomerRetrievePaymentMethodParams params, RequestOptions options)
throws StripeException {
String url =
ApiResource.fullUrl(
Stripe.getApiBase(),
options,
String.format(
"/v1/customers/%s/payment_methods/%s",
ApiResource.urlEncodeId(customer), ApiResource.urlEncodeId(this.getId())));
return ApiResource.request(
ApiResource.RequestMethod.GET, url, params, PaymentMethod.class, options);
}
```
```
### OS
macOS
### Java version
Java 17
### stripe-java version
v22.23.0
### API version
2022-11-15
### Additional context
_No response_ | 98d98801e7103fdeda9eb7ffe1f9fdc6871378ca | f93a85c5da3ef715d93f6ce8140089fbd5b890a8 | https://github.com/stripe/stripe-java/compare/98d98801e7103fdeda9eb7ffe1f9fdc6871378ca...f93a85c5da3ef715d93f6ce8140089fbd5b890a8 | diff --git a/src/main/java/com/stripe/model/Customer.java b/src/main/java/com/stripe/model/Customer.java
index a47875a770..7e84fc9043 100644
--- a/src/main/java/com/stripe/model/Customer.java
+++ b/src/main/java/com/stripe/model/Customer.java
@@ -560,21 +560,22 @@ public class Customer extends ApiResource implements HasId, MetadataStore<Custom
/** Retrieves a PaymentMethod object for a given Customer. */
public PaymentMethod retrievePaymentMethod(
- String customer, Map<String, Object> params, RequestOptions options) throws StripeException {
+ String paymentMethod, Map<String, Object> params, RequestOptions options)
+ throws StripeException {
String url =
ApiResource.fullUrl(
Stripe.getApiBase(),
options,
String.format(
"/v1/customers/%s/payment_methods/%s",
- ApiResource.urlEncodeId(customer), ApiResource.urlEncodeId(this.getId())));
+ ApiResource.urlEncodeId(this.getId()), ApiResource.urlEncodeId(paymentMethod)));
return ApiResource.request(
ApiResource.RequestMethod.GET, url, params, PaymentMethod.class, options);
}
/** Retrieves a PaymentMethod object for a given Customer. */
public PaymentMethod retrievePaymentMethod(
- String customer, CustomerRetrievePaymentMethodParams params, RequestOptions options)
+ String paymentMethod, CustomerRetrievePaymentMethodParams params, RequestOptions options)
throws StripeException {
String url =
ApiResource.fullUrl(
@@ -582,7 +583,7 @@ public class Customer extends ApiResource implements HasId, MetadataStore<Custom
options,
String.format(
"/v1/customers/%s/payment_methods/%s",
- ApiResource.urlEncodeId(customer), ApiResource.urlEncodeId(this.getId())));
+ ApiResource.urlEncodeId(this.getId()), ApiResource.urlEncodeId(paymentMethod)));
return ApiResource.request(
ApiResource.RequestMethod.GET, url, params, PaymentMethod.class, options);
} | ['src/main/java/com/stripe/model/Customer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 12,504,938 | 2,662,671 | 346,715 | 674 | 784 | 135 | 9 | 1 | 2,296 | 208 | 456 | 77 | 1 | 2 | 1970-01-01T00:28:06 | 686 | Java | {'Java': 13238026, 'Makefile': 1002} | MIT License |
741 | jhipster/jhipster-registry/546/543 | jhipster | jhipster-registry | https://github.com/jhipster/jhipster-registry/issues/543 | https://github.com/jhipster/jhipster-registry/pull/546 | https://github.com/jhipster/jhipster-registry/pull/546 | 1 | fix | Registry docker image requires JWT base64-secret in oauth2 profile | <!--
- Please follow the issue template below for bug reports and feature requests.
- If you have a support request rather than a bug, please use [Stack Overflow](http://stackoverflow.com/questions/tagged/jhipster) with the JHipster tag.
- For bug reports it is mandatory to run the command `jhipster info` in your project's root folder, and paste the result here.
- Tickets opened without any of these pieces of information will be **closed** without any explanation.
-->
##### **Overview of the issue**
JWT base64-secret should not be mandatory in oauth2 profile
<!-- Explain the bug or feature request, if an error is being thrown a stack trace helps -->
##### **Motivation for or Use Case**
<!-- Explain why this is a bug or a new feature for you -->
##### **Reproduce the error**
- Generate the JHipster application with OIDC authentication and select integration with JHipster Registry
- Start the Keycloak container
- Start `jhipster-registry` container -- `docker-compose -f src/main/docker/jhipster-registry up`
- You shall see startup errors due to the null `base64-secret` configuration required by TokenProvider.
- Specify some dummy long base64-secret under `src/main/docker/central-server-config/localhost-config/application.yml` and start JHipster Registry again. This time you should see the registry starts up correctly.
<!-- For bug reports, an unambiguous set of steps to reproduce the error -->
##### **Related issues**
<!-- Has a similar issue been reported before? Please search both closed & open issues -->
##### **Suggest a Fix**
<!-- For bug reports, if you can't fix the bug yourself, perhaps you can point to what might be
causing the problem (line of code or commit) -->
##### **JHipster Registry Version(s)**
<!--
Which version of JHipster Registry are you using, is it a regression?
-->
##### **Browsers and Operating System**
<!-- What OS are you on? is this a problem with all browsers or only IE8? -->
- [ ] Checking this box is mandatory (this is just to show you read everything)
| d4de3449db4f8308a1f527e10138ee708957e5de | 6bce26936769c30123097156c778ed89c6169b49 | https://github.com/jhipster/jhipster-registry/compare/d4de3449db4f8308a1f527e10138ee708957e5de...6bce26936769c30123097156c778ed89c6169b49 | diff --git a/src/main/java/tech/jhipster/registry/security/jwt/TokenProvider.java b/src/main/java/tech/jhipster/registry/security/jwt/TokenProvider.java
index e8a382c..059d642 100644
--- a/src/main/java/tech/jhipster/registry/security/jwt/TokenProvider.java
+++ b/src/main/java/tech/jhipster/registry/security/jwt/TokenProvider.java
@@ -20,7 +20,6 @@ import org.springframework.util.ObjectUtils;
import tech.jhipster.config.JHipsterProperties;
import tech.jhipster.registry.management.SecurityMetersService;
-@Component
public class TokenProvider {
private final Logger log = LoggerFactory.getLogger(TokenProvider.class);
diff --git a/src/main/java/tech/jhipster/registry/security/oauth2/JwtGrantedAuthorityConverter.java b/src/main/java/tech/jhipster/registry/security/oauth2/JwtGrantedAuthorityConverter.java
index 08a91ac..9ae9db6 100644
--- a/src/main/java/tech/jhipster/registry/security/oauth2/JwtGrantedAuthorityConverter.java
+++ b/src/main/java/tech/jhipster/registry/security/oauth2/JwtGrantedAuthorityConverter.java
@@ -7,7 +7,6 @@ import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Component;
import tech.jhipster.registry.security.SecurityUtils;
-@Component
public class JwtGrantedAuthorityConverter implements Converter<Jwt, Collection<GrantedAuthority>> {
public JwtGrantedAuthorityConverter() {
diff --git a/src/main/java/tech/jhipster/registry/web/rest/UserJWTController.java b/src/main/java/tech/jhipster/registry/web/rest/UserJWTController.java
index 39f414a..5506b9c 100644
--- a/src/main/java/tech/jhipster/registry/web/rest/UserJWTController.java
+++ b/src/main/java/tech/jhipster/registry/web/rest/UserJWTController.java
@@ -2,6 +2,7 @@ package tech.jhipster.registry.web.rest;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.Valid;
+import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -10,6 +11,7 @@ import org.springframework.security.config.annotation.authentication.builders.Au
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
+import tech.jhipster.registry.config.Constants;
import tech.jhipster.registry.security.jwt.JWTFilter;
import tech.jhipster.registry.security.jwt.TokenProvider;
import tech.jhipster.registry.web.rest.vm.LoginVM;
@@ -19,6 +21,7 @@ import tech.jhipster.registry.web.rest.vm.LoginVM;
*/
@RestController
@RequestMapping("/api")
+@Profile("!" + Constants.PROFILE_OAUTH2)
public class UserJWTController {
private final TokenProvider tokenProvider; | ['src/main/java/tech/jhipster/registry/security/jwt/TokenProvider.java', 'src/main/java/tech/jhipster/registry/web/rest/UserJWTController.java', 'src/main/java/tech/jhipster/registry/security/oauth2/JwtGrantedAuthorityConverter.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 105,496 | 19,536 | 2,872 | 49 | 168 | 31 | 5 | 3 | 2,077 | 316 | 445 | 45 | 1 | 0 | 1970-01-01T00:27:42 | 676 | TypeScript | {'TypeScript': 198550, 'Java': 192822, 'CSS': 140710, 'HTML': 42192, 'SCSS': 9677, 'JavaScript': 5850, 'Shell': 2208, 'Dockerfile': 1434, 'Batchfile': 1088, 'HCL': 201} | Apache License 2.0 |
1,352 | spring-cloud/spring-cloud-commons/225/224 | spring-cloud | spring-cloud-commons | https://github.com/spring-cloud/spring-cloud-commons/issues/224 | https://github.com/spring-cloud/spring-cloud-commons/pull/225 | https://github.com/spring-cloud/spring-cloud-commons/pull/225 | 1 | fixes | RetryTemplate does not work properly when calling multiple serviceNames | Hi guys.
We encountered following issue when using consul and `RetryLoadBalancerInterceptor`
Service-A calls service-1 and service-2.
Service-1 and service-2 are provided in different servers with different paths.
service-1 : http://host-1:8888/path1/service1
service-2: http://host-2:9999/path2/service2
But we found that some requests access following URLs which caused 404 errors.
http://host-2:9999/path1/service1
http://host-1:8888/path2/service2
We researched the source code and found that in `RetryLoadBalancerInterceptor` since the retryTemplate is singleton, the retryPolicy inside retryTemplate maybe modified by another thread before the request is executed.
<pre><code>retryTemplate.setRetryPolicy(
!lbProperties.isEnabled() || retryPolicy == null ? new NeverRetryPolicy()
: new InterceptorRetryPolicy(request, retryPolicy, loadBalancer,
serviceName));
</code></pre>
Please see the code in `RetryTemplate` at about line 277 (master branch)
`while (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) `
And `InterceptorRetryPolicy` `canRetry` method,
<pre><code> LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext)context;
if(lbContext.getRetryCount() == 0 && lbContext.getServiceInstance() == null) {
//We haven't even tried to make the request yet so return true so we do
lbContext.setServiceInstance(serviceInstanceChooser.choose(serviceName));
return true;
}
</code></pre>
Since the serviceInstance which contains the real service host and port info maybe modified in canRetry method, it may change the request URL to a host of another serviceName (If another thread modified the retryPolicy with other serviceName. In class `ServiceRequestWrapper` is where the request URL is actually changed by using `ServiceInstance`).
So we disabled the retryPolicy by config
`spring.cloud.loadbalancer.retry.enabled=false`
so that in `RetryLoadBalancerInterceptor.intercept` we will always use `NeverRetryPolicy` object, and we have not encountered 404 since then. (We encountered 404 every hour before modifying the configuration).
Would you please confirm if my investigation on our issue is correct or not?
Thank you.
| 40930de25dd33878fb2773d087db3476d86abc70 | 5d5a5edc3c2a10b0890c5617802cad94e5cd6836 | https://github.com/spring-cloud/spring-cloud-commons/compare/40930de25dd33878fb2773d087db3476d86abc70...5d5a5edc3c2a10b0890c5617802cad94e5cd6836 | diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfiguration.java
index 02257ac0..9f4cb42d 100644
--- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfiguration.java
+++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfiguration.java
@@ -126,8 +126,8 @@ public class LoadBalancerAutoConfiguration {
public RetryLoadBalancerInterceptor ribbonInterceptor(
LoadBalancerClient loadBalancerClient, LoadBalancerRetryProperties properties,
LoadBalancedRetryPolicyFactory lbRetryPolicyFactory,
- LoadBalancerRequestFactory requestFactory, RetryTemplate retryTemplate) {
- return new RetryLoadBalancerInterceptor(loadBalancerClient, retryTemplate, properties,
+ LoadBalancerRequestFactory requestFactory) {
+ return new RetryLoadBalancerInterceptor(loadBalancerClient, properties,
lbRetryPolicyFactory, requestFactory);
}
diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java
index d632b471..cabf8d45 100644
--- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java
+++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java
@@ -42,7 +42,7 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto
private LoadBalancerRetryProperties lbProperties;
private LoadBalancerRequestFactory requestFactory;
-
+ @Deprecated
public RetryLoadBalancerInterceptor(LoadBalancerClient loadBalancer, RetryTemplate retryTemplate,
LoadBalancerRetryProperties lbProperties,
LoadBalancedRetryPolicyFactory lbRetryPolicyFactory,
@@ -53,7 +53,18 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto
this.lbProperties = lbProperties;
this.requestFactory = requestFactory;
}
-
+
+ public RetryLoadBalancerInterceptor(LoadBalancerClient loadBalancer,
+ LoadBalancerRetryProperties lbProperties,
+ LoadBalancedRetryPolicyFactory lbRetryPolicyFactory,
+ LoadBalancerRequestFactory requestFactory) {
+ this.loadBalancer = loadBalancer;
+ this.lbRetryPolicyFactory = lbRetryPolicyFactory;
+ this.lbProperties = lbProperties;
+ this.requestFactory = requestFactory;
+ }
+
+ @Deprecated
public RetryLoadBalancerInterceptor(LoadBalancerClient loadBalancer, RetryTemplate retryTemplate,
LoadBalancerRetryProperties lbProperties,
LoadBalancedRetryPolicyFactory lbRetryPolicyFactory) {
@@ -70,11 +81,13 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto
Assert.state(serviceName != null, "Request URI does not contain a valid hostname: " + originalUri);
final LoadBalancedRetryPolicy retryPolicy = lbRetryPolicyFactory.create(serviceName,
loadBalancer);
- retryTemplate.setRetryPolicy(
+ RetryTemplate template = this.retryTemplate == null ? new RetryTemplate() : this.retryTemplate;
+ template.setThrowLastExceptionOnExhausted(true);
+ template.setRetryPolicy(
!lbProperties.isEnabled() || retryPolicy == null ? new NeverRetryPolicy()
: new InterceptorRetryPolicy(request, retryPolicy, loadBalancer,
serviceName));
- return retryTemplate
+ return template
.execute(new RetryCallback<ClientHttpResponse, IOException>() {
@Override
public ClientHttpResponse doWithRetry(RetryContext context)
diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTest.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTest.java
index aaeaa768..307ee8d6 100644
--- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTest.java
+++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTest.java
@@ -33,14 +33,12 @@ import static org.mockito.Mockito.when;
public class RetryLoadBalancerInterceptorTest {
private LoadBalancerClient client;
- private RetryTemplate retryTemplate;
private LoadBalancerRetryProperties lbProperties;
private LoadBalancerRequestFactory lbRequestFactory;
@Before
public void setUp() throws Exception {
client = mock(LoadBalancerClient.class);
- retryTemplate = spy(new RetryTemplate());
lbProperties = new LoadBalancerRetryProperties();
lbRequestFactory = mock(LoadBalancerRequestFactory.class);
@@ -49,7 +47,6 @@ public class RetryLoadBalancerInterceptorTest {
@After
public void tearDown() throws Exception {
client = null;
- retryTemplate = null;
lbProperties = null;
}
@@ -64,11 +61,10 @@ public class RetryLoadBalancerInterceptorTest {
when(client.choose(eq("foo"))).thenReturn(serviceInstance);
when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenThrow(new IOException());
lbProperties.setEnabled(false);
- RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, retryTemplate, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
+ RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
byte[] body = new byte[]{};
ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
interceptor.intercept(request, body, execution);
- verify(retryTemplate, times(1)).setRetryPolicy(any(NeverRetryPolicy.class));
verify(lbRequestFactory).createRequest(request, body, execution);
}
@@ -85,7 +81,7 @@ public class RetryLoadBalancerInterceptorTest {
when(client.choose(eq("foo_underscore"))).thenReturn(serviceInstance);
when(client.execute(eq("foo_underscore"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenReturn(clientHttpResponse);
lbProperties.setEnabled(true);
- RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, retryTemplate, lbProperties, lbRetryPolicyFactory);
+ RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
byte[] body = new byte[]{};
ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
ClientHttpResponse rsp = interceptor.intercept(request, body, execution);
@@ -102,11 +98,10 @@ public class RetryLoadBalancerInterceptorTest {
when(client.choose(eq("foo"))).thenReturn(serviceInstance);
when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenReturn(clientHttpResponse);
lbProperties.setEnabled(true);
- RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, retryTemplate, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
+ RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
byte[] body = new byte[]{};
ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
interceptor.intercept(request, body, execution);
- verify(retryTemplate, times(1)).setRetryPolicy(any(NeverRetryPolicy.class));
verify(lbRequestFactory).createRequest(request, body, execution);
}
@@ -123,12 +118,11 @@ public class RetryLoadBalancerInterceptorTest {
when(client.choose(eq("foo"))).thenReturn(serviceInstance);
when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenReturn(clientHttpResponse);
lbProperties.setEnabled(true);
- RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, retryTemplate, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
+ RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
byte[] body = new byte[]{};
ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
ClientHttpResponse rsp = interceptor.intercept(request, body, execution);
assertThat(rsp, is(clientHttpResponse));
- verify(retryTemplate, times(1)).setRetryPolicy(eq(interceptorRetryPolicy));
verify(lbRequestFactory).createRequest(request, body, execution);
}
@@ -149,13 +143,12 @@ public class RetryLoadBalancerInterceptorTest {
when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).
thenReturn(clientHttpResponseNotFound).thenReturn(clientHttpResponseOk);
lbProperties.setEnabled(true);
- RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, retryTemplate, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
+ RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
byte[] body = new byte[]{};
ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
ClientHttpResponse rsp = interceptor.intercept(request, body, execution);
verify(client, times(2)).execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class));
assertThat(rsp, is(clientHttpResponseOk));
- verify(retryTemplate, times(1)).setRetryPolicy(eq(interceptorRetryPolicy));
verify(lbRequestFactory, times(2)).createRequest(request, body, execution);
}
@@ -172,13 +165,12 @@ public class RetryLoadBalancerInterceptorTest {
when(client.choose(eq("foo"))).thenReturn(serviceInstance);
when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenThrow(new IOException()).thenReturn(clientHttpResponse);
lbProperties.setEnabled(true);
- RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, retryTemplate, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
+ RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
byte[] body = new byte[]{};
ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
ClientHttpResponse rsp = interceptor.intercept(request, body, execution);
verify(client, times(2)).execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class));
assertThat(rsp, is(clientHttpResponse));
- verify(retryTemplate, times(1)).setRetryPolicy(any(InterceptorRetryPolicy.class));
verify(lbRequestFactory, times(2)).createRequest(request, body, execution);
}
@@ -196,7 +188,7 @@ public class RetryLoadBalancerInterceptorTest {
when(client.choose(eq("foo"))).thenReturn(serviceInstance);
when(client.execute(eq("foo"), eq(serviceInstance), any(LoadBalancerRequest.class))).thenThrow(new IOException()).thenReturn(clientHttpResponse);
lbProperties.setEnabled(true);
- RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, retryTemplate, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
+ RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(client, lbProperties, lbRetryPolicyFactory, lbRequestFactory);
byte[] body = new byte[]{};
ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
ClientHttpResponse rsp = interceptor.intercept(request, body, execution); | ['spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java', 'spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTest.java', 'spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancerAutoConfiguration.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 279,886 | 57,134 | 8,840 | 111 | 1,002 | 203 | 25 | 2 | 2,280 | 250 | 502 | 50 | 4 | 0 | 1970-01-01T00:24:59 | 658 | Java | {'Java': 1641470} | Apache License 2.0 |
1,349 | spring-cloud/spring-cloud-commons/1208/1207 | spring-cloud | spring-cloud-commons | https://github.com/spring-cloud/spring-cloud-commons/issues/1207 | https://github.com/spring-cloud/spring-cloud-commons/pull/1208 | https://github.com/spring-cloud/spring-cloud-commons/pull/1208 | 1 | fixes | Caching is not enabled by default for certain user-enabled load-balancer configurations | It should only be disabled by default for health-checks-based load-balancing that has its own caching mechanism. | 6677d16736de42c25525381694758c48ebf9ae8b | 730c7852cfea06ae1a49c5bc0268b7b4d82f12ab | https://github.com/spring-cloud/spring-cloud-commons/compare/6677d16736de42c25525381694758c48ebf9ae8b...730c7852cfea06ae1a49c5bc0268b7b4d82f12ab | diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfiguration.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfiguration.java
index d52a2d73..7c2cc898 100644
--- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfiguration.java
+++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfiguration.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2012-2020 the original author or authors.
+ * Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -120,7 +120,7 @@ public class LoadBalancerClientConfiguration {
public ServiceInstanceListSupplier requestBasedStickySessionDiscoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder().withDiscoveryClient().withRequestBasedStickySession()
- .build(context);
+ .withCaching().build(context);
}
@Bean
@@ -130,7 +130,7 @@ public class LoadBalancerClientConfiguration {
public ServiceInstanceListSupplier sameInstancePreferenceServiceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder().withDiscoveryClient().withSameInstancePreference()
- .build(context);
+ .withCaching().build(context);
}
}
@@ -176,7 +176,7 @@ public class LoadBalancerClientConfiguration {
public ServiceInstanceListSupplier requestBasedStickySessionDiscoveryClientServiceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder().withBlockingDiscoveryClient().withRequestBasedStickySession()
- .build(context);
+ .withCaching().build(context);
}
@Bean
@@ -186,7 +186,7 @@ public class LoadBalancerClientConfiguration {
public ServiceInstanceListSupplier sameInstancePreferenceServiceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder().withBlockingDiscoveryClient().withSameInstancePreference()
- .build(context);
+ .withCaching().build(context);
}
}
diff --git a/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfigurationTests.java b/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfigurationTests.java
index 5a356cb5..9ac93283 100644
--- a/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfigurationTests.java
+++ b/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfigurationTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2012-2020 the original author or authors.
+ * Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -119,10 +119,13 @@ class LoadBalancerClientConfigurationTests {
.withPropertyValues("spring.cloud.loadbalancer.configurations=request-based-sticky-session")
.run(context -> {
ServiceInstanceListSupplier supplier = context.getBean(ServiceInstanceListSupplier.class);
- then(supplier).isInstanceOf(RequestBasedStickySessionServiceInstanceListSupplier.class);
+ then(supplier).isInstanceOf(CachingServiceInstanceListSupplier.class);
ServiceInstanceListSupplier delegate = ((DelegatingServiceInstanceListSupplier) supplier)
.getDelegate();
- then(delegate).isInstanceOf(DiscoveryClientServiceInstanceListSupplier.class);
+ then(delegate).isInstanceOf(RequestBasedStickySessionServiceInstanceListSupplier.class);
+ ServiceInstanceListSupplier secondDelegate = ((DelegatingServiceInstanceListSupplier) delegate)
+ .getDelegate();
+ then(secondDelegate).isInstanceOf(DiscoveryClientServiceInstanceListSupplier.class);
});
}
| ['spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfiguration.java', 'spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientConfigurationTests.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 788,735 | 163,701 | 23,938 | 269 | 351 | 84 | 10 | 1 | 112 | 16 | 22 | 1 | 0 | 0 | 1970-01-01T00:27:56 | 658 | Java | {'Java': 1641470} | Apache License 2.0 |
1,353 | spring-cloud/spring-cloud-commons/144/143 | spring-cloud | spring-cloud-commons | https://github.com/spring-cloud/spring-cloud-commons/issues/143 | https://github.com/spring-cloud/spring-cloud-commons/pull/144 | https://github.com/spring-cloud/spring-cloud-commons/pull/144 | 1 | fixes | InfoEndpoint ID Is Not Set | When not using a boot version less than 1.4.x, the `InfoEndpoint` id is not set properly. See spring-cloud/spring-cloud-netflix#1449. | 216f7446366d3faab150e53ac3af92f8250e49dd | 607b6a9b0cb8030537ed6be64f634c29a4d383c3 | https://github.com/spring-cloud/spring-cloud-commons/compare/216f7446366d3faab150e53ac3af92f8250e49dd...607b6a9b0cb8030537ed6be64f634c29a4d383c3 | diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshEndpointAutoConfiguration.java b/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshEndpointAutoConfiguration.java
index bac20fea..a09858d1 100644
--- a/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshEndpointAutoConfiguration.java
+++ b/spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshEndpointAutoConfiguration.java
@@ -58,11 +58,16 @@ import org.springframework.integration.monitor.IntegrationMBeanExporter;
@AutoConfigureAfter(EndpointAutoConfiguration.class)
public class RefreshEndpointAutoConfiguration {
- @ConditionalOnBean(EndpointAutoConfiguration.class)
+ //TODO Remove this class and InfoEndpointRebinderConfiguration once we no longer
+ //need to support Boot 1.3.x
@ConditionalOnMissingClass("org.springframework.boot.actuate.info.InfoContributor")
- @Bean
- InfoEndpointRebinderConfiguration infoEndpointRebinderConfiguration() {
- return new InfoEndpointRebinderConfiguration();
+ protected static class InfoEndpointAutoConfiguration {
+
+ @ConditionalOnBean(EndpointAutoConfiguration.class)
+ @Bean
+ InfoEndpointRebinderConfiguration infoEndpointRebinderConfiguration() {
+ return new InfoEndpointRebinderConfiguration();
+ }
}
@ConditionalOnMissingBean
@@ -168,7 +173,7 @@ public class RefreshEndpointAutoConfiguration {
}
private InfoEndpoint infoEndpoint(InfoEndpoint endpoint) {
- return new InfoEndpoint(endpoint.invoke()) {
+ InfoEndpoint newEndpoint = new InfoEndpoint(endpoint.invoke()) {
@Override
public Map<String, Object> invoke() {
Map<String, Object> info = new LinkedHashMap<String, Object>(
@@ -177,6 +182,10 @@ public class RefreshEndpointAutoConfiguration {
return info;
}
};
+ newEndpoint.setId(endpoint.getId());
+ newEndpoint.setEnabled(endpoint.isEnabled());
+ newEndpoint.setSensitive(endpoint.isSensitive());
+ return newEndpoint;
}
} | ['spring-cloud-context/src/main/java/org/springframework/cloud/autoconfigure/RefreshEndpointAutoConfiguration.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 243,795 | 49,953 | 7,711 | 93 | 842 | 173 | 19 | 1 | 134 | 18 | 38 | 1 | 0 | 0 | 1970-01-01T00:24:39 | 658 | Java | {'Java': 1641470} | Apache License 2.0 |
491 | kotcrab/vis-ui/68/63 | kotcrab | vis-ui | https://github.com/kotcrab/vis-ui/issues/63 | https://github.com/kotcrab/vis-ui/pull/68 | https://github.com/kotcrab/vis-ui/pull/68#issuecomment-156676200 | 1 | close | Crash on opening plugins folder from settings dialog | Editor crashs at the time when the 'Open Plugin Folder' button has been clicked in Settings dialog.
I got this error message with stacktrace:
```
java.lang.IllegalArgumentException: The file: home/stquote/Downloads/VisUIEditor doesn't exist.
at java.awt.Desktop.checkFileValidation(Desktop.java:210)
at java.awt.Desktop.open(Desktop.java:270)
at com.kotcrab.vis.editor.util.FileUtils.browse(FileUtils.java:74)
at com.kotcrab.vis.editor.module.editor.PluginLoaderModule$PluginSettingsModule.lambda$buildTable$163(PluginLoaderModule.java:235)
at com.kotcrab.vis.editor.module.editor.PluginLoaderModule$PluginSettingsModule$$Lambda$55/1845515247.changed(Unknown Source)
at com.kotcrab.vis.editor.util.gdx.VisChangeListener.changed(VisChangeListener.java:35)
at com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.handle(ChangeListener.java:28)
at com.badlogic.gdx.scenes.scene2d.Actor.notify(Actor.java:181)
at com.badlogic.gdx.scenes.scene2d.Actor.fire(Actor.java:146)
at com.badlogic.gdx.scenes.scene2d.ui.Button.setChecked(Button.java:123)
at com.badlogic.gdx.scenes.scene2d.ui.Button$1.clicked(Button.java:91)
at com.badlogic.gdx.scenes.scene2d.utils.ClickListener.touchUp(ClickListener.java:89)
at com.badlogic.gdx.scenes.scene2d.InputListener.handle(InputListener.java:58)
at com.badlogic.gdx.scenes.scene2d.Stage.touchUp(Stage.java:348)
at com.badlogic.gdx.backends.lwjgl.LwjglInput.processEvents(LwjglInput.java:306)
at com.badlogic.gdx.backends.lwjgl.LwjglCanvas$3.run(LwjglCanvas.java:234)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
[22:51][Fatal] java.lang.RuntimeException: No OpenGL context found in the current thread.
at org.lwjgl.opengl.GLContext.getCapabilities(GLContext.java:124)
at org.lwjgl.opengl.GL11.glDeleteTextures(GL11.java:732)
at com.badlogic.gdx.backends.lwjgl.LwjglGL20.glDeleteTexture(LwjglGL20.java:248)
at com.badlogic.gdx.graphics.GLTexture.delete(GLTexture.java:170)
at com.badlogic.gdx.graphics.Texture.dispose(Texture.java:194)
at com.kotcrab.vis.ui.widget.color.ColorPicker.dispose(ColorPicker.java:468)
at com.kotcrab.vis.editor.module.editor.ColorPickerModule.dispose(ColorPickerModule.java:35)
at com.kotcrab.vis.editor.module.ModuleContainer.dispose(ModuleContainer.java:191)
at com.kotcrab.vis.editor.Editor.dispose(Editor.java:250)
at com.badlogic.gdx.backends.lwjgl.LwjglCanvas$4.run(LwjglCanvas.java:309)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
```
In my case I have a path to plugins folder ''/home/lalala/vis/viseditor/Editor/target/plugins/", but in `PluginLoaderModule` class at [this line](https://github.com/kotcrab/VisEditor/blob/master/Editor/src/com/kotcrab/vis/editor/module/editor/PluginLoaderModule.java#L235) used `PLUGINS_FOLDER_PATH` constant with "home/lalala/vis/viseditor/Editor/target/plugins/" value which which has not start with slash symbol.
It seems like a typo in [JarUtils.java](https://github.com/kotcrab/VisEditor/blob/master/Editor/src/com/kotcrab/vis/editor/util/JarUtils.java#L33) because `PluginLoaderModule` class uses this util method for initialize constant. I think substring method should have 0 in first argument. Like this: `path = path.substring(0, path.lastIndexOf('/'));`
I'm using Linux Mint, but I think this is not working in windows too.
So if I'm right, and all agree with me, I can make pull request for this :)
| dda750718ce9557064ec5821b09f21a0528eaeac | c231d4ec43519201d2d1bc00ac024b224b621304 | https://github.com/kotcrab/vis-ui/compare/dda750718ce9557064ec5821b09f21a0528eaeac...c231d4ec43519201d2d1bc00ac024b224b621304 | diff --git a/Editor/src/com/kotcrab/vis/editor/util/JarUtils.java b/Editor/src/com/kotcrab/vis/editor/util/JarUtils.java
index 57e5160b..bd576cfa 100644
--- a/Editor/src/com/kotcrab/vis/editor/util/JarUtils.java
+++ b/Editor/src/com/kotcrab/vis/editor/util/JarUtils.java
@@ -16,6 +16,7 @@
package com.kotcrab.vis.editor.util;
+import com.kotcrab.vis.ui.util.OsUtils;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
@@ -30,7 +31,12 @@ public class JarUtils {
try {
URL url = caller.getProtectionDomain().getCodeSource().getLocation();
String path = URLDecoder.decode(url.getFile(), "UTF-8");
- path = path.substring(1, path.lastIndexOf('/')); // remove jar name from path
+
+ // remove jar name from path
+ if (OsUtils.isWindows())
+ path = path.substring(1, path.lastIndexOf('/')); // cut first '/' for Windows
+ else
+ path = path.substring(0, path.lastIndexOf('/'));
if (path.endsWith("target/classes")) //launched from ide, remove classes from path
path = path.substring(0, path.length() - "/classes".length()); | ['Editor/src/com/kotcrab/vis/editor/util/JarUtils.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,438,297 | 584,843 | 77,764 | 697 | 332 | 83 | 8 | 1 | 5,351 | 249 | 1,252 | 71 | 2 | 1 | 1970-01-01T00:24:07 | 655 | Java | {'Java': 934953, 'GLSL': 2915} | Apache License 2.0 |
739 | adobe/s3mock/462/459 | adobe | s3mock | https://github.com/adobe/S3Mock/issues/459 | https://github.com/adobe/S3Mock/pull/462 | https://github.com/adobe/S3Mock/pull/462 | 2 | fixes | Copy command returns generic 404 instead of a NoSuchKey error | **Exception**
When trying to copy a non-existing S3 object to the same bucket but with a different key a generic 404 exception occurs.
```
Exception in thread "main" software.amazon.awssdk.services.s3.model.S3Exception: null (Service: S3, Status Code: 404, Request ID: null, Extended Request ID: null)
at software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler.handleErrorResponse(AwsXmlPredicatedResponseHandler.java:156)
at software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler.handleResponse(AwsXmlPredicatedResponseHandler.java:106)
at software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler.handle(AwsXmlPredicatedResponseHandler.java:84)
at software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler.handle(AwsXmlPredicatedResponseHandler.java:42)
```
**Reproducing the issue**
I use the following scratch file :
```java
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
class S3Test {
public static void main(String[] args) throws IOException {
final S3Client s3Client = S3Client.builder()
.endpointOverride(URI.create("http://localhost:9090"))
.build();
final String copySource = URLEncoder.encode("my-bucket/test-file.json", StandardCharsets.UTF_8.toString());
s3Client.copyObject(CopyObjectRequest.builder()
.copySource(copySource)
.destinationBucket("my-bucket")
.destinationKey("test-file-copy.json")
.build());
}
}
```
Please note I set this environment variable to initialize the bucket : *initialBuckets=my-bucket*
**Possible fix**
A quick fix I found was to change `FileStore`'s line 701 :
```java
// ...
public CopyObjectResult copyS3ObjectEncrypted(final String sourceBucketName,
final String sourceObjectName,
final String destinationBucketName,
final String destinationObjectName,
final String encryption,
final String kmsKeyId,
final Map<String, String> userMetadata) throws IOException {
final S3Object sourceObject = getS3Object(sourceBucketName, sourceObjectName);
if (sourceObject == null) {
//return null;
throw new S3Exception(NOT_FOUND.value(), "NoSuchKey", "The specified key does not exist.");
}
// ...
```
I can raise a Pull Request if needed 😊
| d6535223329d2cfd8bb601e8bde2c185823c1455 | e1cf8ca19cd216a3ae0761a5cbd143394f385b43 | https://github.com/adobe/s3mock/compare/d6535223329d2cfd8bb601e8bde2c185823c1455...e1cf8ca19cd216a3ae0761a5cbd143394f385b43 | diff --git a/integration-tests/src/test/java/com/adobe/testing/s3mock/its/AmazonClientUploadIT.java b/integration-tests/src/test/java/com/adobe/testing/s3mock/its/AmazonClientUploadIT.java
index 5e94ca91..69960bda 100644
--- a/integration-tests/src/test/java/com/adobe/testing/s3mock/its/AmazonClientUploadIT.java
+++ b/integration-tests/src/test/java/com/adobe/testing/s3mock/its/AmazonClientUploadIT.java
@@ -675,6 +675,26 @@ class AmazonClientUploadIT extends S3TestBase {
.hasMessageContaining("Status Code: 400; Error Code: KMS.NotFoundException");
}
+ /**
+ * Tests that a copy request for a non-existing object throws the correct error.
+ */
+ @Test
+ void shouldThrowNoSuchKeyOnCopyForNonExistingKey() {
+ final String sourceKey = "NON_EXISTENT_KEY";
+ final String destinationBucketName = "destinationbucket";
+ final String destinationKey = "copyOf" + sourceKey;
+
+ s3Client.createBucket(BUCKET_NAME);
+ s3Client.createBucket(destinationBucketName);
+
+ final CopyObjectRequest copyObjectRequest =
+ new CopyObjectRequest(BUCKET_NAME, sourceKey, destinationBucketName, destinationKey);
+
+ assertThatThrownBy(() -> s3Client.copyObject(copyObjectRequest))
+ .isInstanceOf(AmazonS3Exception.class)
+ .hasMessageContaining("Status Code: 404; Error Code: NoSuchKey");
+ }
+
/**
* Creates a bucket and checks if it exists using {@link AmazonS3Client#doesBucketExist(String)}.
*/
diff --git a/integration-tests/src/test/java/com/adobe/testing/s3mock/its/MultiPartUploadIT.java b/integration-tests/src/test/java/com/adobe/testing/s3mock/its/MultiPartUploadIT.java
index d648acab..ab183703 100644
--- a/integration-tests/src/test/java/com/adobe/testing/s3mock/its/MultiPartUploadIT.java
+++ b/integration-tests/src/test/java/com/adobe/testing/s3mock/its/MultiPartUploadIT.java
@@ -18,8 +18,10 @@ package com.adobe.testing.s3mock.its;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.amazonaws.services.s3.model.AbortMultipartUploadRequest;
+import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest;
import com.amazonaws.services.s3.model.CompleteMultipartUploadResult;
import com.amazonaws.services.s3.model.CopyPartRequest;
@@ -471,6 +473,40 @@ public class MultiPartUploadIT extends S3TestBase {
assertThat(partListing.getParts().get(0).getETag()).isEqualTo(copyPartResult.getETag());
}
+ /**
+ * Tries to copy part of an non-existing object to a new bucket.
+ */
+ @Test
+ void shouldThrowNoSuchKeyOnCopyObjectPartForNonExistingKey() {
+ final String sourceKey = "NON_EXISTENT_KEY";
+ final String destinationBucketName = "destinationbucket";
+ final String destinationKey = "copyOf/" + sourceKey;
+ s3Client.createBucket(BUCKET_NAME);
+ s3Client.createBucket(destinationBucketName);
+
+ final ObjectMetadata objectMetadata = new ObjectMetadata();
+ objectMetadata.addUserMetadata("key", "value");
+
+ final InitiateMultipartUploadResult initiateMultipartUploadResult = s3Client
+ .initiateMultipartUpload(
+ new InitiateMultipartUploadRequest(destinationBucketName, destinationKey,
+ objectMetadata));
+ final String uploadId = initiateMultipartUploadResult.getUploadId();
+
+ CopyPartRequest copyPartRequest = new CopyPartRequest();
+ copyPartRequest.setDestinationBucketName(destinationBucketName);
+ copyPartRequest.setUploadId(uploadId);
+ copyPartRequest.setDestinationKey(destinationKey);
+ copyPartRequest.setSourceBucketName(BUCKET_NAME);
+ copyPartRequest.setSourceKey(sourceKey);
+ copyPartRequest.setFirstByte(0L);
+ copyPartRequest.setLastByte(5L);
+
+ assertThatThrownBy(() -> s3Client.copyPart(copyPartRequest))
+ .isInstanceOf(AmazonS3Exception.class)
+ .hasMessageContaining("Status Code: 404; Error Code: NoSuchKey");
+ }
+
private PartETag uploadPart(String key, String uploadId, int partNumber, byte[] randomBytes) {
return s3Client
.uploadPart(createUploadPartRequest(key, uploadId)
diff --git a/server/src/main/java/com/adobe/testing/s3mock/FileStoreController.java b/server/src/main/java/com/adobe/testing/s3mock/FileStoreController.java
index 4708833b..4251e1ef 100644
--- a/server/src/main/java/com/adobe/testing/s3mock/FileStoreController.java
+++ b/server/src/main/java/com/adobe/testing/s3mock/FileStoreController.java
@@ -866,6 +866,7 @@ public class FileStoreController {
verifyBucketExistence(destinationBucket);
final String destinationFile = filenameFrom(destinationBucket, request);
+ verifyObjectExistence(copySource.getBucket(), copySource.getKey());
final String partEtag = fileStore.copyPart(copySource.getBucket(),
copySource.getKey(),
copyRange,
@@ -1018,6 +1019,7 @@ public class FileStoreController {
required = false) final String kmsKeyId,
final HttpServletRequest request) throws IOException {
verifyBucketExistence(destinationBucket);
+ verifyObjectExistence(objectRef.getBucket(), objectRef.getKey());
final String destinationFile = filenameFrom(destinationBucket, request);
final CopyObjectResult copyObjectResult; | ['integration-tests/src/test/java/com/adobe/testing/s3mock/its/AmazonClientUploadIT.java', 'integration-tests/src/test/java/com/adobe/testing/s3mock/its/MultiPartUploadIT.java', 'server/src/main/java/com/adobe/testing/s3mock/FileStoreController.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 224,313 | 50,123 | 6,816 | 52 | 143 | 28 | 2 | 1 | 2,847 | 199 | 578 | 68 | 1 | 3 | 1970-01-01T00:27:26 | 640 | Java | {'Java': 579394, 'Kotlin': 258712, 'Shell': 3792, 'Dockerfile': 3127} | Apache License 2.0 |
733 | adobe/s3mock/838/837 | adobe | s3mock | https://github.com/adobe/S3Mock/issues/837 | https://github.com/adobe/S3Mock/pull/838 | https://github.com/adobe/S3Mock/pull/838 | 1 | closes | Race condition for temp dir creation | Hi there,
we are running S3Mock embedded using the `S3MockExtension`. I know that this scenario is deprecated. ;-)
After adding a second unit test class using `S3MockExtension` we are regularly seeing root folder creation failures in CI where two threads generate the same tmp file name and only one of them succeeds with `mkdir` in `StoreConfiguration#rootFolder`.
I have prepared a PR that hopefully fixes this issue by using `Files#createTempDirectory`, which is thread-safe.
Regards,
Thilo
```
01:44:23.689 [ForkJoinPool-1-worker-1] INFO com.adobe.testing.s3mock.store.StoreConfiguration - Successfully created "/tmp/s3mockFileStore1664243063689" as root folder. Will retain files on exit: false
01:44:23.692 [ForkJoinPool-1-worker-8] WARN org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bucketStore' defined in class path resource [com/adobe/testing/s3mock/store/StoreConfiguration.class]: Unsatisfied dependency expressed through method 'bucketStore' parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bucketRootFolder' defined in class path resource [com/adobe/testing/s3mock/store/StoreConfiguration.class]: Unsatisfied dependency expressed through method 'bucketRootFolder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'rootFolder' defined in class path resource [com/adobe/testing/s3mock/store/StoreConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.io.File]: Factory method 'rootFolder' threw exception; nested exception is java.lang.IllegalStateException: Root folder could not be created. Path: /tmp/s3mockFileStore1664243063689
``` | 9068b26757eacdc64919e3e14abf566ee3fbfb3f | 4fc70dbf7c403810c439721420e7e8fb53f8f770 | https://github.com/adobe/s3mock/compare/9068b26757eacdc64919e3e14abf566ee3fbfb3f...4fc70dbf7c403810c439721420e7e8fb53f8f770 | diff --git a/server/src/main/java/com/adobe/testing/s3mock/store/StoreConfiguration.java b/server/src/main/java/com/adobe/testing/s3mock/store/StoreConfiguration.java
index 1a29f6fb..e11f0d32 100644
--- a/server/src/main/java/com/adobe/testing/s3mock/store/StoreConfiguration.java
+++ b/server/src/main/java/com/adobe/testing/s3mock/store/StoreConfiguration.java
@@ -18,9 +18,11 @@ package com.adobe.testing.s3mock.store;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
-import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -69,24 +71,37 @@ public class StoreConfiguration {
@Bean
File rootFolder(StoreProperties properties) {
final File root;
- if (properties.getRoot() == null || properties.getRoot().isEmpty()) {
- root = new File(FileUtils.getTempDirectory(), "s3mockFileStore" + new Date().getTime());
+ final boolean createTempDir = properties.getRoot() == null || properties.getRoot().isEmpty();
+
+ if (createTempDir) {
+ final Path baseTempDir = FileUtils.getTempDirectory().toPath();
+ try {
+ root = Files.createTempDirectory(baseTempDir, "s3mockFileStore").toFile();
+ } catch (IOException e) {
+ throw new IllegalStateException("Root folder could not be created. Base temp dir: "
+ + baseTempDir, e);
+ }
+
+ LOG.info("Successfully created \\"{}\\" as root folder. Will retain files on exit: {}",
+ root.getAbsolutePath(), properties.isRetainFilesOnExit());
} else {
root = new File(properties.getRoot());
+
+ if (root.exists()) {
+ LOG.info("Using existing folder \\"{}\\" as root folder. Will retain files on exit: {}",
+ root.getAbsolutePath(), properties.isRetainFilesOnExit());
+ } else if (!root.mkdir()) {
+ throw new IllegalStateException("Root folder could not be created. Path: "
+ + root.getAbsolutePath());
+ } else {
+ LOG.info("Successfully created \\"{}\\" as root folder. Will retain files on exit: {}",
+ root.getAbsolutePath(), properties.isRetainFilesOnExit());
+ }
}
+
if (!properties.isRetainFilesOnExit()) {
root.deleteOnExit();
}
- if (root.exists()) {
- LOG.info("Using existing folder \\"{}\\" as root folder. Will retain files on exit: {}",
- root.getAbsolutePath(), properties.isRetainFilesOnExit());
- } else if (!root.mkdir()) {
- throw new IllegalStateException("Root folder could not be created. Path: "
- + root.getAbsolutePath());
- } else {
- LOG.info("Successfully created \\"{}\\" as root folder. Will retain files on exit: {}",
- root.getAbsolutePath(), properties.isRetainFilesOnExit());
- }
return root;
} | ['server/src/main/java/com/adobe/testing/s3mock/store/StoreConfiguration.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 319,530 | 71,680 | 9,586 | 80 | 1,985 | 413 | 41 | 1 | 2,068 | 199 | 424 | 15 | 0 | 1 | 1970-01-01T00:27:44 | 640 | Java | {'Java': 579394, 'Kotlin': 258712, 'Shell': 3792, 'Dockerfile': 3127} | Apache License 2.0 |