...
 
Commits (5)
/**
* Copyright (C) 2016 Bonitasoft S.A.
* Bonitasoft, 32 rue Gustave Eiffel - 38000 Grenoble
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.common.repository.core;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Properties;
import org.eclipse.core.resources.IProject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class DatabaseHandlerTest {
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
@Test
public void should_create_bitronix_resource_properties() throws Exception {
final IProject project = mock(IProject.class, RETURNS_DEEP_STUBS);
final File rootFolder = tmpFolder.newFolder();
when(project.getLocation().toFile()).thenReturn(rootFolder);
final DatabaseHandler databaseHandler = spy(new DatabaseHandler(project));
final Properties dbProperties = new Properties();
dbProperties.put(DatabaseHandler.BONITA_DB_NAME_PROPERTY, "bonita_journal.db");
dbProperties.put(DatabaseHandler.BUSINESS_DATA_DB_NAME_PROPERTY, "business_data.db");
doReturn(dbProperties).when(databaseHandler).readDatabaseProperties();
final Path file = databaseHandler.createBitronixConfFile();
final Properties properties = new Properties();
try (InputStream is = java.nio.file.Files.newInputStream(file)) {
properties.load(is);
}
assertThat(properties).contains(
entry("resource.ds1.driverProperties.URL",
String.format(
"jdbc:h2:file:%s" + File.separator
+ "h2_database" + File.separator
+ "bonita_journal.db;MVCC=TRUE;DB_CLOSE_ON_EXIT=FALSE;IGNORECASE=TRUE;AUTO_SERVER=TRUE;",
rootFolder.getAbsolutePath())),
entry("resource.ds2.driverProperties.URL",
String.format(
"jdbc:h2:file:%s" + File.separator
+ "h2_database" + File.separator
+ "business_data.db;MVCC=TRUE;DB_CLOSE_ON_EXIT=FALSE;IGNORECASE=TRUE;AUTO_SERVER=TRUE;",
rootFolder.getAbsolutePath())),
entry("allowLocalTransactions", "true"),
entry("resource.ds1.uniqueName", "jdbc/bonitaDSXA"),
entry("resource.ds2.uniqueName", "jdbc/BusinessDataDSXA"));
}
}
......@@ -17,11 +17,7 @@ package org.bonitasoft.studio.common.repository.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Properties;
import org.bonitasoft.studio.common.ProjectUtil;
......@@ -89,30 +85,4 @@ public class DatabaseHandler {
return new File(project.getLocation().toFile(), H2_DATABASE_FOLDER_NAME);
}
public Path createBitronixConfFile() throws IOException {
final Properties databaseProperties = readDatabaseProperties();
final Path confFile = getDBLocation().toPath().resolve(Paths.get("conf", BITRONIX_RESOURCES_PROPERTIES));
if (!confFile.getParent().toFile().exists()) {
confFile.getParent().toFile().mkdirs();
}
final Properties bitronixResources = new Properties();
bitronixResources.put("allowLocalTransactions", Boolean.TRUE.toString());
final BitronixDatasourceConfiguration engineDS = new BitronixDatasourceConfiguration("jdbc/bonitaDSXA");
engineDS.setDatabaseFile(getDBLocation().getAbsolutePath() + File.separatorChar
+ databaseProperties.getProperty(BONITA_DB_NAME_PROPERTY));
bitronixResources.putAll(engineDS.toMap("ds1"));
final BitronixDatasourceConfiguration businessDataDS = new BitronixDatasourceConfiguration("jdbc/BusinessDataDSXA");
businessDataDS.setDatabaseFile(getDBLocation().getAbsolutePath() + File.separatorChar
+ databaseProperties.getProperty(BUSINESS_DATA_DB_NAME_PROPERTY));
businessDataDS.setMinPoolSize(0);
businessDataDS.setMaxPoolSize(5);
bitronixResources.putAll(businessDataDS.toMap("ds2"));
try (OutputStream newOutputStream = java.nio.file.Files.newOutputStream(confFile,
StandardOpenOption.CREATE)) {
bitronixResources.store(newOutputStream, null);
}
return confFile;
}
}
......@@ -98,4 +98,9 @@ creatingMappingOperation=Creating mapping operation for %s
saving=Saving...
taskBdmTips=You can first define <a>business variables</a> and/or <a>documents</a>, and then click on "Add from data...".\nIt will automatically map contract inputs to data, and create operations to update data with contract values.
poolBdmTips=You can first define <a>business variables</a> and/or <a>documents</a>, and then click on "Add from data...".\nIt will automatically map contract inputs to data, and initialize data with contract values.
creatingNewForm=Creating new form...
\ No newline at end of file
creatingNewForm=Creating new form...
createDataFromContractChoice=Create data from contract
editDataFromContractChoice=Edit an existing data using contract and context when generating a Form from the contract
lazyFieldInAMultipleParentRelationHasBeenDeselect=%s.%s has been unselected. Generating an edition form for this field is not supported (lazy reference in a multiple parent).
aChildHasBeenUnselected=A child relation has been unselected.
moreInfoFormGenerationLink=More information about <a>Contract and Form generation</a>.
\ No newline at end of file
......@@ -39,9 +39,11 @@ public class RelationFieldToContractInputMappingTest {
@Test
public void should_create_contract_input_from_a_composition_relation_field() throws Exception {
final RelationFieldToContractInputMapping fieldToContractInputMapping = new RelationFieldToContractInputMapping(aRelationField("address",
Type.COMPOSITION,
aBusinessObject("Address", aSimpleField("number", FieldType.INTEGER), aSimpleField("street", FieldType.STRING))));
final RelationFieldToContractInputMapping fieldToContractInputMapping = new RelationFieldToContractInputMapping(
aRelationField("address", Type.COMPOSITION,
aBusinessObject("Address",
aSimpleField("number", FieldType.INTEGER),
aSimpleField("street", FieldType.STRING))));
final ContractInput input = fieldToContractInputMapping.toContractInput(null);
......@@ -49,12 +51,18 @@ public class RelationFieldToContractInputMappingTest {
}
@Test
public void should_create_contract_input_with_children_from_a_RelationFieldToContractInputMapping_with_children() throws Exception {
public void should_create_contract_input_with_children_from_a_RelationFieldToContractInputMapping_with_children()
throws Exception {
final RelationField compositionField = aRelationField("address", Type.COMPOSITION,
aBusinessObject("Address", aSimpleField("number", FieldType.INTEGER), aSimpleField("street", FieldType.STRING)));
final RelationFieldToContractInputMapping fieldToContractInputMapping = new RelationFieldToContractInputMapping(compositionField);
fieldToContractInputMapping.addChild(new SimpleFieldToContractInputMapping((SimpleField) compositionField.getReference().getFields().get(0)));
fieldToContractInputMapping.addChild(new SimpleFieldToContractInputMapping((SimpleField) compositionField.getReference().getFields().get(1)));
aBusinessObject("Address",
aSimpleField("number", FieldType.INTEGER),
aSimpleField("street", FieldType.STRING)));
final RelationFieldToContractInputMapping fieldToContractInputMapping = new RelationFieldToContractInputMapping(
compositionField);
fieldToContractInputMapping.addChild(
new SimpleFieldToContractInputMapping((SimpleField) compositionField.getReference().getFields().get(0)));
fieldToContractInputMapping.addChild(
new SimpleFieldToContractInputMapping((SimpleField) compositionField.getReference().getFields().get(1)));
final ContractInput input = fieldToContractInputMapping.toContractInput(null);
......@@ -66,12 +74,17 @@ public class RelationFieldToContractInputMappingTest {
@Test
public void should_not_add_contract_input_for_not_generated_child_mapping() throws Exception {
final RelationField compositionField = aRelationField("address", Type.AGGREGATION,
aBusinessObject("Address", aSimpleField("number", FieldType.INTEGER), aSimpleField("street", FieldType.STRING)));
final RelationFieldToContractInputMapping fieldToContractInputMapping = new RelationFieldToContractInputMapping(compositionField);
final SimpleFieldToContractInputMapping child = new SimpleFieldToContractInputMapping((SimpleField) compositionField.getReference().getFields().get(0));
aBusinessObject("Address",
aSimpleField("number", FieldType.INTEGER),
aSimpleField("street", FieldType.STRING)));
final RelationFieldToContractInputMapping fieldToContractInputMapping = new RelationFieldToContractInputMapping(
compositionField);
final SimpleFieldToContractInputMapping child = new SimpleFieldToContractInputMapping(
(SimpleField) compositionField.getReference().getFields().get(0));
child.setGenerated(false);
fieldToContractInputMapping.addChild(child);
fieldToContractInputMapping.addChild(new SimpleFieldToContractInputMapping((SimpleField) compositionField.getReference().getFields().get(1)));
fieldToContractInputMapping.addChild(
new SimpleFieldToContractInputMapping((SimpleField) compositionField.getReference().getFields().get(1)));
final ContractInput input = fieldToContractInputMapping.toContractInput(null);
......@@ -82,17 +95,18 @@ public class RelationFieldToContractInputMappingTest {
@Test
public void should_create_script_initializing_an_address() throws Exception {
final BusinessObject addressBo = aBusinessObject("Address", aSimpleField("street", FieldType.TEXT));
final RelationFieldToContractInputMapping fieldToContractInputMapping = new RelationFieldToContractInputMapping(aRelationField("address",
Type.COMPOSITION,
addressBo));
fieldToContractInputMapping.addChild(new SimpleFieldToContractInputMapping((SimpleField) addressBo.getField("street")));
final RelationFieldToContractInputMapping fieldToContractInputMapping = new RelationFieldToContractInputMapping(
aRelationField("address", Type.COMPOSITION, addressBo));
fieldToContractInputMapping
.addChild(new SimpleFieldToContractInputMapping((SimpleField) addressBo.getField("street")));
fieldToContractInputMapping.toContractInput(aContractInput().withName("employee").withType(ContractInputType.COMPLEX)
.build());
final MappingOperationScriptBuilder scriptBuilder = fieldToContractInputMapping.getScriptBuilder(aBusinessData().withName("myEmployee").build());
final MappingOperationScriptBuilder scriptBuilder = fieldToContractInputMapping
.getScriptBuilder(aBusinessData().withName("myEmployee").build());
assertThat(scriptBuilder.toScript()).isEqualTo(
"def addressVar = myEmployee.address == null ? new Address() : myEmployee.address" + System.lineSeparator()
"def addressVar = myEmployee.address ?: new Address()" + System.lineSeparator()
+ "addressVar.street = employee.address.street" + System.lineSeparator()
+ "return addressVar");
}
......@@ -100,21 +114,18 @@ public class RelationFieldToContractInputMappingTest {
@Test
public void should_return_field_type() throws Exception {
final BusinessObject addressBo = aBusinessObject("Address", aSimpleField("street", FieldType.TEXT));
final RelationFieldToContractInputMapping fieldToContractInputMapping = new RelationFieldToContractInputMapping(aRelationField("address",
Type.COMPOSITION,
addressBo));
final RelationFieldToContractInputMapping fieldToContractInputMapping = new RelationFieldToContractInputMapping(
aRelationField("address", Type.COMPOSITION, addressBo));
assertThat(fieldToContractInputMapping.getFieldType()).isEqualTo("Address");
}
@Test
public void should_return_field_type_for_multiple_fields() throws Exception {
final BusinessObject addressBo = aBusinessObject("Address", aSimpleField("street", FieldType.TEXT));
final RelationField aRelationField = aRelationField("address",
Type.COMPOSITION,
addressBo);
final RelationField aRelationField = aRelationField("address", Type.COMPOSITION, addressBo);
aRelationField.setCollection(true);
final RelationFieldToContractInputMapping fieldToContractInputMapping = new RelationFieldToContractInputMapping(aRelationField);
final RelationFieldToContractInputMapping fieldToContractInputMapping = new RelationFieldToContractInputMapping(
aRelationField);
assertThat(fieldToContractInputMapping.getFieldType()).isEqualTo(List.class.getName());
}
......
......@@ -41,7 +41,8 @@ public class MappingOperationScriptBuilderTest {
@Test
public void should_not_need_data_dependency_for_a_simple_mapping() throws Exception {
final SimpleField firstNameField = aSimpleField().withName("firstName").ofType(FieldType.TEXT).build();
final MappingOperationScriptBuilder scriptBuilder = new MappingOperationScriptBuilder(aBusinessData().withName("employee").build(),
final MappingOperationScriptBuilder scriptBuilder = new MappingOperationScriptBuilder(
aBusinessData().withName("employee").build(),
new SimpleFieldToContractInputMapping(firstNameField));
final String script = scriptBuilder.toScript();
......@@ -54,9 +55,11 @@ public class MappingOperationScriptBuilderTest {
public void should_need_data_dependency_for_a_relation_mapping() throws Exception {
final SimpleField streetField = aSimpleField().withName("street").ofType(FieldType.TEXT).build();
final RelationField addressField = aCompositionField("address", aBO("Address").withField(streetField).build());
final RelationFieldToContractInputMapping relationFieldToContractInputMapping = new RelationFieldToContractInputMapping(addressField);
final RelationFieldToContractInputMapping relationFieldToContractInputMapping = new RelationFieldToContractInputMapping(
addressField);
relationFieldToContractInputMapping.addChild(new SimpleFieldToContractInputMapping(streetField));
final MappingOperationScriptBuilder scriptBuilder = new MappingOperationScriptBuilder(aBusinessData().withName("employee").build(),
final MappingOperationScriptBuilder scriptBuilder = new MappingOperationScriptBuilder(
aBusinessData().withName("employee").build(),
relationFieldToContractInputMapping);
final String script = scriptBuilder.toScript();
......@@ -71,11 +74,13 @@ public class MappingOperationScriptBuilderTest {
public void should_not_add_child_initializer_if_mappping_is_not_generated() throws Exception {
final SimpleField streetField = aSimpleField().withName("street").ofType(FieldType.TEXT).build();
final RelationField addressField = aCompositionField("address", aBO("Address").withField(streetField).build());
final RelationFieldToContractInputMapping relationFieldToContractInputMapping = new RelationFieldToContractInputMapping(addressField);
final RelationFieldToContractInputMapping relationFieldToContractInputMapping = new RelationFieldToContractInputMapping(
addressField);
final SimpleFieldToContractInputMapping child = new SimpleFieldToContractInputMapping(streetField);
child.setGenerated(false);
relationFieldToContractInputMapping.addChild(child);
final MappingOperationScriptBuilder scriptBuilder = new MappingOperationScriptBuilder(aBusinessData().withName("employee").build(),
final MappingOperationScriptBuilder scriptBuilder = new MappingOperationScriptBuilder(
aBusinessData().withName("employee").build(),
relationFieldToContractInputMapping);
final String script = scriptBuilder.toScript();
......@@ -88,11 +93,14 @@ public class MappingOperationScriptBuilderTest {
public void should_generate_a_closure_for_deep_relation_mapping() throws Exception {
final SimpleField streetField = aSimpleField().withName("street").ofType(FieldType.TEXT).build();
final RelationField countryField = aCompositionField("country", aBO("Country").build());
final RelationField addressField = aCompositionField("address", aBO("Address").withField(streetField).withField(countryField).build());
final RelationFieldToContractInputMapping relationFieldToContractInputMapping = new RelationFieldToContractInputMapping(addressField);
final RelationField addressField = aCompositionField("address",
aBO("Address").withField(streetField).withField(countryField).build());
final RelationFieldToContractInputMapping relationFieldToContractInputMapping = new RelationFieldToContractInputMapping(
addressField);
relationFieldToContractInputMapping.addChild(new SimpleFieldToContractInputMapping(streetField));
relationFieldToContractInputMapping.addChild(new RelationFieldToContractInputMapping(countryField));
final MappingOperationScriptBuilder scriptBuilder = new MappingOperationScriptBuilder(aBusinessData().withName("employee").build(),
final MappingOperationScriptBuilder scriptBuilder = new MappingOperationScriptBuilder(
aBusinessData().withName("employee").build(),
relationFieldToContractInputMapping);
final String script = scriptBuilder.toScript();
......@@ -100,7 +108,7 @@ public class MappingOperationScriptBuilderTest {
assertThat(script).isEqualTo("def addressVar = new Address()" + System.lineSeparator()
+ "addressVar.street = address.street" + System.lineSeparator()
+ "addressVar.country = {" + System.lineSeparator()
+ SWT.TAB + "def countryVar = addressVar.country == null ? new Country() : addressVar.country" + System.lineSeparator()
+ SWT.TAB + "def countryVar = addressVar.country ?: new Country()" + System.lineSeparator()
+ SWT.TAB + "return countryVar}()" + System.lineSeparator()
+ "return addressVar");
}
......@@ -122,7 +130,8 @@ public class MappingOperationScriptBuilderTest {
}
};
final MappingOperationScriptBuilder scriptBuilder = new MappingOperationScriptBuilder(aBusinessData().withName("employee").build(),
final MappingOperationScriptBuilder scriptBuilder = new MappingOperationScriptBuilder(
aBusinessData().withName("employee").build(),
mapping);
thrown.expect(UnsupportedOperationException.class);
......
......@@ -39,11 +39,11 @@ public class AggregationReferencePropertyInitializerTest {
assertThat(initialValue).isEqualTo("{" + System.lineSeparator()
+ "//Retrieve aggregated country using its DAO and persistenceId" + System.lineSeparator()
+ "def countryVar = countryDAO.findByPersistenceId(country.persistenceId_string.toLong())"
+ "def countryVar = countryDAO.findByPersistenceId(country.persistenceId_string?.toLong())"
+ System.lineSeparator()
+ "if(!countryVar) {"
+ System.lineSeparator()
+ "throw new IllegalArgumentException(\"The aggregated reference of type `country` with the persistence id \" + country.persistenceId_string.toLong() + \" has not been found.\")"
+ "throw new IllegalArgumentException(\"The aggregated reference of type `country` with the persistence id \" + country.persistenceId_string?.toLong() + \" has not been found.\")"
+ System.lineSeparator()
+ "}"
+ System.lineSeparator()
......
......@@ -57,11 +57,11 @@ public class BusinessObjectQueryInitializerTest {
assertThat(initialValue).isEqualTo(
"//Retrieve aggregated Country using its DAO and persistenceId" + System.lineSeparator()
+ "def countryVar = countryDAO.findByPersistenceId(countryInput.persistenceId_string.toLong())"
+ "def countryVar = countryDAO.findByPersistenceId(countryInput.persistenceId_string?.toLong())"
+ System.lineSeparator()
+ "if(!countryVar) {"
+ System.lineSeparator()
+ "throw new IllegalArgumentException(\"The aggregated reference of type `Country` with the persistence id \" + countryInput.persistenceId_string.toLong() + \" has not been found.\")"
+ "throw new IllegalArgumentException(\"The aggregated reference of type `Country` with the persistence id \" + countryInput.persistenceId_string?.toLong() + \" has not been found.\")"
+ System.lineSeparator()
+ "}"
+ System.lineSeparator()
......
......@@ -39,41 +39,44 @@ public class CompositionReferencePropertyInitializerTest {
final SimpleField streetField = aSimpleField().withName("street").ofType(FieldType.TEXT).notNullable().build();
final InitializerContext context = new InitializerContext();
final RelationFieldToContractInputMapping mapping = new RelationFieldToContractInputMapping(aCompositionField("address",
aBO("org.test.Address").withField(streetField).build()));
final RelationFieldToContractInputMapping mapping = new RelationFieldToContractInputMapping(
aCompositionField("address", aBO("org.test.Address").withField(streetField).build()));
context.setMapping(mapping);
context.setData(aBusinessData().withName("employee").build());
context.setContractInput(aContractInput().build());
context.setLocalVariableName("addressVar");
final CompositionReferencePropertyInitializer propertyInitializer = new CompositionReferencePropertyInitializer(context);
final CompositionReferencePropertyInitializer propertyInitializer = new CompositionReferencePropertyInitializer(
context);
propertyInitializer.addPropertyInitializer(new SimpleFieldPropertyInitializer(null,
streetField, aContractInput().withName("street")
.in(aContractInput().withName("address").withType(ContractInputType.COMPLEX)
.in(aContractInput().withName("employee").withType(ContractInputType.COMPLEX))).build()));
.in(aContractInput().withName("employee").withType(ContractInputType.COMPLEX)))
.build()));
assertThat(propertyInitializer.getInitialValue()).isEqualTo(
"{"
+ System.lineSeparator()
+ "def addressVar = employee.address == null ? new org.test.Address() : employee.address"
+ "def addressVar = employee.address ?: new org.test.Address()"
+ System.lineSeparator()
+ "addressVar.street = employee.address.street"
+ System.lineSeparator()
+ "return addressVar}()"
);
+ "return addressVar}()");
}
@Test
public void should_not_throw_an_BusinessObjectInstantiationException_when_creating_an_inconsistent_business_object_having_missing_mandatory_attributes()
throws Exception {
final InitializerContext context = new InitializerContext();
final RelationFieldToContractInputMapping mapping = new RelationFieldToContractInputMapping(aCompositionField("address", aBO("org.test.Address")
.withField(aSimpleField().withName("street").notNullable().build()).build()));
final RelationFieldToContractInputMapping mapping = new RelationFieldToContractInputMapping(
aCompositionField("address",
aBO("org.test.Address").withField(aSimpleField().withName("street").notNullable().build()).build()));
context.setMapping(mapping);
context.setData(aBusinessData().withName("employee").build());
context.setContractInput(aContractInput().build());
context.setLocalVariableName("addressVar");
final CompositionReferencePropertyInitializer propertyInitializer = new CompositionReferencePropertyInitializer(context);
final CompositionReferencePropertyInitializer propertyInitializer = new CompositionReferencePropertyInitializer(
context);
propertyInitializer.getInitialValue();
}
......
......@@ -75,11 +75,11 @@ public class MultipleAggregationBusinessObjectQueryInitializerTest {
+ "employeeInput.each{" + System.lineSeparator()
+ "//Add Employee instance" + System.lineSeparator()
+ "employeeList.add({ currentEmployeeInput ->" + System.lineSeparator()
+ "def employeeVar = employeeDAO.findByPersistenceId(currentEmployeeInput.persistenceId_string.toLong())"
+ "def employeeVar = employeeDAO.findByPersistenceId(currentEmployeeInput.persistenceId_string?.toLong())"
+ System.lineSeparator()
+ "if(!employeeVar) {"
+ System.lineSeparator()
+ "throw new IllegalArgumentException(\"The aggregated reference of type `Employee` with the persistence id \" + currentEmployeeInput.persistenceId_string.toLong() + \" has not been found.\")"
+ "throw new IllegalArgumentException(\"The aggregated reference of type `Employee` with the persistence id \" + currentEmployeeInput.persistenceId_string?.toLong() + \" has not been found.\")"
+ System.lineSeparator()
+ "}"
+ System.lineSeparator()
......
......@@ -64,11 +64,11 @@ public class MultipleAggregationReferencePropertyInitializerTest {
+ "employees.each{" + System.lineSeparator()
+ "//Add Employee instance" + System.lineSeparator()
+ "employeeList.add({ currentEmployeeInput ->" + System.lineSeparator()
+ "def employeeVar = employeeDAO.findByPersistenceId(currentEmployeeInput.persistenceId_string.toLong())"
+ "def employeeVar = employeeDAO.findByPersistenceId(currentEmployeeInput.persistenceId_string?.toLong())"
+ System.lineSeparator()
+ "if(!employeeVar) {"
+ System.lineSeparator()
+ "throw new IllegalArgumentException(\"The aggregated reference of type `Employee` with the persistence id \" + currentEmployeeInput.persistenceId_string.toLong() + \" has not been found.\")"
+ "throw new IllegalArgumentException(\"The aggregated reference of type `Employee` with the persistence id \" + currentEmployeeInput.persistenceId_string?.toLong() + \" has not been found.\")"
+ System.lineSeparator()
+ "}"
+ System.lineSeparator()
......@@ -110,11 +110,11 @@ public class MultipleAggregationReferencePropertyInitializerTest {
+ "employees.each{" + System.lineSeparator()
+ "//Add Employee instance" + System.lineSeparator()
+ "employeeList.add({ currentEmployeeInput ->" + System.lineSeparator()
+ "def employeeVar = employeeDAO.findByPersistenceId(currentEmployeeInput.persistenceId_string.toLong())"
+ "def employeeVar = employeeDAO.findByPersistenceId(currentEmployeeInput.persistenceId_string?.toLong())"
+ System.lineSeparator()
+ "if(!employeeVar) {"
+ System.lineSeparator()
+ "throw new IllegalArgumentException(\"The aggregated reference of type `Employee` with the persistence id \" + currentEmployeeInput.persistenceId_string.toLong() + \" has not been found.\")"
+ "throw new IllegalArgumentException(\"The aggregated reference of type `Employee` with the persistence id \" + currentEmployeeInput.persistenceId_string?.toLong() + \" has not been found.\")"
+ System.lineSeparator()
+ "}"
+ System.lineSeparator()
......@@ -159,11 +159,11 @@ public class MultipleAggregationReferencePropertyInitializerTest {
+ "currentDirectoryInput.employees.each{" + System.lineSeparator()
+ "//Add Employee instance" + System.lineSeparator()
+ "employeeList.add({ currentEmployeeInput ->" + System.lineSeparator()
+ "def employeeVar = employeeDAO.findByPersistenceId(currentEmployeeInput.persistenceId_string.toLong())"
+ "def employeeVar = employeeDAO.findByPersistenceId(currentEmployeeInput.persistenceId_string?.toLong())"
+ System.lineSeparator()
+ "if(!employeeVar) {"
+ System.lineSeparator()
+ "throw new IllegalArgumentException(\"The aggregated reference of type `Employee` with the persistence id \" + currentEmployeeInput.persistenceId_string.toLong() + \" has not been found.\")"
+ "throw new IllegalArgumentException(\"The aggregated reference of type `Employee` with the persistence id \" + currentEmployeeInput.persistenceId_string?.toLong() + \" has not been found.\")"
+ System.lineSeparator()
+ "}"
+ System.lineSeparator()
......
......@@ -51,7 +51,8 @@ public class NewBusinessObjectInitializerTest {
final NewBusinessObjectInitializer propertyInitializer = new NewBusinessObjectInitializer(context);
assertThat(propertyInitializer.getInitialValue()).isEqualTo(
"def addressVar = employee.address == null ? new org.test.Address() : employee.address" + System.lineSeparator() + "return addressVar");
"def addressVar = employee.address ?: new org.test.Address()" + System.lineSeparator()
+ "return addressVar");
}
@Test
......@@ -59,8 +60,9 @@ public class NewBusinessObjectInitializerTest {
final SimpleField streetField = aSimpleField().withName("street").ofType(FieldType.STRING).notNullable().build();
final InitializerContext context = new InitializerContext();
final RelationFieldToContractInputMapping mapping = new RelationFieldToContractInputMapping(aCompositionField("address",
aBO("org.test.Address").withField(streetField).build()));
final RelationFieldToContractInputMapping mapping = new RelationFieldToContractInputMapping(
aCompositionField("address",
aBO("org.test.Address").withField(streetField).build()));
context.setMapping(mapping);
context.setData(aBusinessData().withName("employee").build());
context.setContractInput(aContractInput().withName("employee").multiple()
......@@ -74,12 +76,14 @@ public class NewBusinessObjectInitializerTest {
propertyInitializer.addPropertyInitializer(new SimpleFieldPropertyInitializer(null,
streetField, aContractInput().withName("street")
.in(aContractInput().withName("address").withType(ContractInputType.COMPLEX)
.in(aContractInput().withName("employee").withType(ContractInputType.COMPLEX))).build()));
assertThat(propertyInitializer.getInitialValue()).isEqualTo("def addressVar = employee.address == null ? new org.test.Address() : employee.address"
+ System.lineSeparator()
+ "addressVar.street = employee.address.street"
+ System.lineSeparator()
+ "return addressVar");
.in(aContractInput().withName("employee").withType(ContractInputType.COMPLEX)))
.build()));
assertThat(propertyInitializer.getInitialValue())
.isEqualTo("def addressVar = employee.address ?: new org.test.Address()"
+ System.lineSeparator()
+ "addressVar.street = employee.address.street"
+ System.lineSeparator()
+ "return addressVar");
}
}
......@@ -27,7 +27,8 @@ public class SimpleFieldPropertyInitializerTest {
@Test
public void should_return_name_of_the_property_to_initialize() throws Exception {
final SimpleFieldPropertyInitializer initializer = new SimpleFieldPropertyInitializer(null, aSimpleField().withName("lastName").build(),
final SimpleFieldPropertyInitializer initializer = new SimpleFieldPropertyInitializer(null,
aSimpleField().withName("lastName").build(),
aContractInput()
.build());
......@@ -38,7 +39,9 @@ public class SimpleFieldPropertyInitializerTest {
public void should_return_a_groovy_expression_retrieving_contract_input_value() throws Exception {
final SimpleFieldPropertyInitializer initializer = new SimpleFieldPropertyInitializer(null,
aSimpleField().withName("lastName").ofType(FieldType.STRING)
.build(), aContractInput().withName("lastName").in(aContractInput().withName("employee").withType(ContractInputType.COMPLEX)).build());
.build(),
aContractInput().withName("lastName")
.in(aContractInput().withName("employee").withType(ContractInputType.COMPLEX)).build());
assertThat(initializer.getInitialValue()).isEqualTo("employee.lastName");
}
......@@ -49,7 +52,7 @@ public class SimpleFieldPropertyInitializerTest {
aSimpleField().withName("id").ofType(FieldType.LONG).build(), aContractInput().withName("id")
.in(aContractInput().withName("employee").withType(ContractInputType.COMPLEX)).build());
assertThat(initializer.getInitialValue()).isEqualTo("employee.id.toLong()");
assertThat(initializer.getInitialValue()).isEqualTo("employee.id?.toLong()");
}
@Test
......@@ -59,17 +62,18 @@ public class SimpleFieldPropertyInitializerTest {
aSimpleField().withName("salary").ofType(FieldType.FLOAT).build(), aContractInput().withName("salary")
.in(aContractInput().withName("employee").withType(ContractInputType.COMPLEX)).build());
assertThat(initializer.getInitialValue()).isEqualTo("employee.salary.toFloat()");
assertThat(initializer.getInitialValue()).isEqualTo("employee.salary?.toFloat()");
}
@Test
public void should_return_a_groovy_expression_retrieving_contract_input_value_cast_to_float_list() throws Exception {
final SimpleFieldPropertyInitializer initializer = new SimpleFieldPropertyInitializer(
null,
(SimpleField) aSimpleField().withName("grades").ofType(FieldType.FLOAT).multiple().build(), aContractInput().withName("grades").multiple()
(SimpleField) aSimpleField().withName("grades").ofType(FieldType.FLOAT).multiple().build(),
aContractInput().withName("grades").multiple()
.in(aContractInput().withName("employee").withType(ContractInputType.COMPLEX)).build());
assertThat(initializer.getInitialValue()).isEqualTo("employee.grades.collect{ it.toFloat() }");
assertThat(initializer.getInitialValue()).isEqualTo("employee.grades?.collect{ it.toFloat() }");
}
@Test
......@@ -79,6 +83,6 @@ public class SimpleFieldPropertyInitializerTest {
aSimpleField().withName("ids").ofType(FieldType.LONG).build(), aContractInput().withName("ids").multiple()
.in(aContractInput().withName("employee").withType(ContractInputType.COMPLEX)).build());
assertThat(initializer.getInitialValue()).isEqualTo("employee.ids.collect{ it.toLong() }");
assertThat(initializer.getInitialValue()).isEqualTo("employee.ids?.collect{ it.toLong() }");
}
}
......@@ -31,10 +31,12 @@ import java.util.Optional;
import org.bonitasoft.engine.bdm.model.BusinessObject;
import org.bonitasoft.engine.bdm.model.field.RelationField;
import org.bonitasoft.engine.bdm.model.field.RelationField.Type;
import org.bonitasoft.studio.businessobject.core.repository.BusinessObjectModelFileStore;
import org.bonitasoft.studio.businessobject.core.repository.BusinessObjectModelRepositoryStore;
import org.bonitasoft.studio.contract.core.mapping.FieldToContractInputMapping;
import org.bonitasoft.studio.contract.core.mapping.FieldToContractInputMappingFactory;
import org.bonitasoft.studio.contract.core.mapping.RelationFieldToContractInputMapping;
import org.bonitasoft.studio.contract.core.mapping.operation.VariableNameResolver;
import org.bonitasoft.studio.contract.core.mapping.operation.initializer.AggregationReferencePropertyInitializer;
import org.bonitasoft.studio.contract.core.mapping.operation.initializer.CompositionReferencePropertyInitializer;
......@@ -124,6 +126,34 @@ public class RelationPropertyInitializerFactoryTest {
assertThat(propertyInitializer).isInstanceOf(MultipleAggregationReferencePropertyInitializer.class);
}
@Test
public void should_check_existence_for_composition_field_with_multiple_parent_on_a_task() {
RelationPropertyInitializerFactory factory = newFactory();
BusinessObject businessObject = aBO("Employee").build();
RelationField aCompositionField = aCompositionField("address", businessObject);
businessObject.addField(aCompositionField);
BusinessObjectData businessObjectData = new BusinessObjectDataBuilder()
.withClassname(businessObject.getQualifiedName())
.multiple()
.build();
BusinessObjectModelRepositoryStore<BusinessObjectModelFileStore> repositoryStore = mock(
BusinessObjectModelRepositoryStore.class);
when(repositoryStore.getBusinessObjectByQualifiedName(businessObjectData.getClassName()))
.thenReturn(Optional.of(businessObject));
List<FieldToContractInputMapping> mappings = new FieldToContractInputMappingFactory(repositoryStore)
.createMappingForBusinessObjectType(aPool().build(), businessObjectData);
FieldToContractInputMapping addressMapping = mappings.get(0);
RelationField parentRelationField = new RelationField();
parentRelationField.setCollection(true);
parentRelationField.setType(Type.COMPOSITION);
new RelationFieldToContractInputMapping(parentRelationField).addChild(addressMapping);
assertThat(factory.checkExistence(addressMapping, false)).isTrue();
assertThat(factory.checkExistence(addressMapping, true)).isFalse();
}
private RelationPropertyInitializerFactory newFactory() {
return new RelationPropertyInitializerFactory(new VariableNameResolver());
}
......
......@@ -23,6 +23,7 @@ import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.bonitasoft.studio.businessobject.core.repository.BusinessObjectModelRepositoryStore;
import org.bonitasoft.studio.model.process.BusinessObjectData;
......@@ -43,10 +44,12 @@ import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Text;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
......@@ -59,6 +62,11 @@ public class SelectDataWizardPageTest {
@Mock
private BusinessObjectModelRepositoryStore store;
@Before
public void setUp() throws Exception {
when(store.getBusinessObjectByQualifiedName(Mockito.anyString())).thenReturn(Optional.empty());
}
@Test
public void should_isPageComplete_ReturnFalse_when_available_data_is_empty() {
......@@ -67,7 +75,7 @@ public class SelectDataWizardPageTest {
final Contract contract = aContract().build();
final WritableValue selectedDataObservable = new WritableValue();
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
selectedDataObservable, store);
selectedDataObservable, new GenerationOptions(), store);
assertThat(page.isPageComplete()).isFalse();
}
......@@ -78,7 +86,7 @@ public class SelectDataWizardPageTest {
final Contract contract = aContract().build();
final WritableValue selectedDataObservable = new WritableValue();
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
selectedDataObservable, store);
selectedDataObservable, new GenerationOptions(), store);
page.setBusinessDataTypeSelected(false);
assertThat(page.isPageComplete()).isFalse();
}
......@@ -92,7 +100,7 @@ public class SelectDataWizardPageTest {
final WritableValue selectedDataObservable = new WritableValue();
selectedDataObservable.setValue(new Object());
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
selectedDataObservable, store);
selectedDataObservable, new GenerationOptions(), store);
assertThat(page.isPageComplete()).isTrue();
}
......@@ -108,7 +116,7 @@ public class SelectDataWizardPageTest {
final WritableValue selectedDataObservable = new WritableValue();
selectedDataObservable.setValue(document);
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
selectedDataObservable, store);
selectedDataObservable, new GenerationOptions(), store);
page.setBusinessDataTypeSelected(false);
assertThat(page.isPageComplete()).isTrue();
}
......@@ -122,7 +130,7 @@ public class SelectDataWizardPageTest {
availableBusinessData.add(bd);
final WritableValue selectedDataObservable = new WritableValue();
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
selectedDataObservable, store);
selectedDataObservable, new GenerationOptions(), store);
assertThat(selectedDataObservable).isNotNull();
assertThat(page.isPageComplete()).isTrue();
}
......@@ -138,7 +146,7 @@ public class SelectDataWizardPageTest {
selectedDataObservable.setValue(bd);
final WritableValue rootNameObservable = new WritableValue();
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
rootNameObservable, store);
rootNameObservable, new GenerationOptions(), store);
page.setWizard(wizardWithContainer());
page.createControl(realmWithDisplay.createComposite());
assertThat(rootNameObservable.getValue()).isEqualTo("myDataInput");
......@@ -155,7 +163,7 @@ public class SelectDataWizardPageTest {
selectedDataObservable.setValue(bd);
final WritableValue rootNameObservable = new WritableValue();
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
rootNameObservable, store);
rootNameObservable, new GenerationOptions(), store);
page.setWizard(wizardWithContainer());
page.createControl(realmWithDisplay.createComposite());
final Text text = widgetFinder.<Text> withLabel(realmWithDisplay.getShell(), org.bonitasoft.studio.contract.i18n.Messages.rootContractInputName);
......@@ -176,7 +184,7 @@ public class SelectDataWizardPageTest {
final WritableValue selectedDataObservable = new WritableValue();
selectedDataObservable.setValue(document);
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
selectedDataObservable, store);
selectedDataObservable, new GenerationOptions(), store);
page.setBusinessDataTypeSelected(false);
assertThat(selectedDataObservable).isNotNull();
assertThat(page.isPageComplete()).isTrue();
......@@ -194,7 +202,7 @@ public class SelectDataWizardPageTest {
final WritableValue selectedDataObservable = new WritableValue();
selectedDataObservable.setValue(document);
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
selectedDataObservable, store);
selectedDataObservable, new GenerationOptions(), store);
page.setBusinessDataTypeSelected(false);
assertThat(page.createDefaultValueAlreadyDefinedValidator().validate(document)).isEqualTo(Status.OK_STATUS);
}
......@@ -214,7 +222,7 @@ public class SelectDataWizardPageTest {
final WritableValue selectedDataObservable = new WritableValue();
selectedDataObservable.setValue(document);
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
selectedDataObservable, store);
selectedDataObservable, new GenerationOptions(), store);
page.setBusinessDataTypeSelected(false);
assertThat(page.createDefaultValueAlreadyDefinedValidator().validate(document)).isNotEqualTo(Status.OK_STATUS);
}
......@@ -231,7 +239,7 @@ public class SelectDataWizardPageTest {
final WritableValue selectedDataObservable = new WritableValue();
selectedDataObservable.setValue(document);
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
selectedDataObservable, store);
selectedDataObservable, new GenerationOptions(), store);
page.setBusinessDataTypeSelected(false);
assertThat(page.canFlipToNextPage()).isFalse();
}
......@@ -248,7 +256,7 @@ public class SelectDataWizardPageTest {
final WritableValue selectedDataObservable = new WritableValue();
selectedDataObservable.setValue(document);
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
selectedDataObservable, store);
selectedDataObservable, new GenerationOptions(), store);
page.setBusinessDataTypeSelected(false);
final SelectionAdapter bvSelectionAdapter = page.createBusinessVariableSelectionAdapter();
bvSelectionAdapter.widgetSelected(mock(SelectionEvent.class));
......@@ -268,7 +276,7 @@ public class SelectDataWizardPageTest {
final WritableValue selectedDataObservable = new WritableValue();
selectedDataObservable.setValue(bd);
final SelectDataWizardPage page = new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
selectedDataObservable, store);
selectedDataObservable, new GenerationOptions(), store);
page.setBusinessDataTypeSelected(true);
final SelectionAdapter documentSelectionAdapter = page.createDocumentSelectionAdapter();
documentSelectionAdapter.widgetSelected(mock(SelectionEvent.class));
......
......@@ -20,6 +20,7 @@ import org.bonitasoft.engine.bdm.model.field.RelationField;
import org.bonitasoft.engine.bdm.model.field.SimpleField;
import org.bonitasoft.studio.contract.core.mapping.RelationFieldToContractInputMapping;
import org.bonitasoft.studio.contract.core.mapping.SimpleFieldToContractInputMapping;
import org.bonitasoft.studio.contract.core.mapping.UnselectLazyReferencesInMultipleContainer;
import org.bonitasoft.studio.model.businessObject.BusinessObjectBuilder;
import org.bonitasoft.studio.model.businessObject.FieldBuilder.RelationFieldBuilder;
import org.bonitasoft.studio.model.businessObject.FieldBuilder.SimpleFieldBuilder;
......@@ -31,7 +32,7 @@ public class FieldNameColumnLabelProviderTest {
public void should_return_a_simpleField_name() {
final SimpleFieldToContractInputMapping mapping = new SimpleFieldToContractInputMapping((SimpleField) SimpleFieldBuilder.aSimpleField()
.withName("employee").build());
final FieldNameColumnLabelProvider provider = new FieldNameColumnLabelProvider();
final FieldNameColumnLabelProvider provider = new FieldNameColumnLabelProvider(new UnselectLazyReferencesInMultipleContainer());
assertThat(provider.getText(mapping)).isEqualTo("employee");
}
......@@ -41,9 +42,8 @@ public class FieldNameColumnLabelProviderTest {
final RelationFieldToContractInputMapping mapping = new RelationFieldToContractInputMapping((RelationField) RelationFieldBuilder.anAggregationField(
"employee",
BusinessObjectBuilder.aBO("Employee").build()));
final FieldNameColumnLabelProvider provider = new FieldNameColumnLabelProvider();
final FieldNameColumnLabelProvider provider = new FieldNameColumnLabelProvider(new UnselectLazyReferencesInMultipleContainer());
assertThat(provider.getText(mapping)).isEqualTo("employee");
}
}
......@@ -65,7 +65,7 @@ public abstract class FieldToContractInputMapping {
}
public List<FieldToContractInputMapping> getChildren() {
return Collections.<FieldToContractInputMapping> unmodifiableList(children);
return children;
}
public FieldToContractInputMapping getParent() {
......
......@@ -5,27 +5,38 @@
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.contract.core.mapping;
import org.bonitasoft.studio.designer.core.operation.IContractReferenceResolver;
import org.bonitasoft.studio.model.process.ContractInput;
import java.util.List;
import java.util.Objects;
import org.bonitasoft.engine.bdm.model.field.RelationField;
import org.bonitasoft.engine.bdm.model.field.RelationField.Type;
public class ContractReferenceResolver implements IContractReferenceResolver {
@Override
public String resolveReference(ContractInput input) {
// TODO Auto-generated method stub
return null;
public class RemoveAggregateReferencesChildren {
public void apply(List<FieldToContractInputMapping> mappings) {
removeAggregateReferencesChildren(mappings);
}
private void removeAggregateReferencesChildren(List<FieldToContractInputMapping> mappings) {
for (FieldToContractInputMapping mapping : mappings) {
if (mapping.getField() instanceof RelationField
&& ((RelationField) mapping.getField()).getType() == Type.AGGREGATION) {
mapping.getChildren()
.removeIf(childMapping -> !Objects.equals(childMapping.getField().getName(),FieldToContractInputMappingFactory.PERSISTENCE_ID_STRING_FIELD_NAME));
}
removeAggregateReferencesChildren(mapping.getChildren());
}
}
}
/**
* Copyright (C) 2019 BonitaSoft S.A.
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.contract.core.mapping;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bonitasoft.engine.bdm.model.field.RelationField;
import org.bonitasoft.studio.contract.i18n.Messages;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
public class UnselectLazyReferencesInMultipleContainer {
private Map<FieldToContractInputMapping, IStatus> statuses = new HashMap<FieldToContractInputMapping, IStatus>();
public void apply(List<FieldToContractInputMapping> mappings, boolean multipleData) {
statuses.clear();
updateGeneratedMappings(mappings, multipleData);
}
private void updateGeneratedMappings(List<FieldToContractInputMapping> mappings, boolean multipleData) {
for (FieldToContractInputMapping mapping : mappings) {
if (mapping.getField() instanceof RelationField
&& ((RelationField) mapping.getField()).isLazy()
&& (multipleData || hasAMultipleParent(mapping))) {
mapping.setGenerated(false);
statuses.put(mapping,
ValidationStatus
.warning(String.format(Messages.lazyFieldInAMultipleParentRelationHasBeenDeselect,
((RelationField) mapping.getParent().getField()).getReference().getSimpleName(),
mapping.getField().getName())));
FieldToContractInputMapping parent = mapping.getParent();
while (parent != null) {
statuses.put(parent,ValidationStatus.warning(Messages.aChildHasBeenUnselected));
parent = parent.getParent();
}
unselect(mapping.getChildren());
}else {
updateGeneratedMappings(mapping.getChildren(), multipleData);
}
}
}
private void unselect(List<FieldToContractInputMapping> children) {
for (FieldToContractInputMapping mapping : children) {
mapping.setGenerated(false);
unselect(mapping.getChildren());
}
}
private boolean hasAMultipleParent(FieldToContractInputMapping mapping) {
FieldToContractInputMapping parent = mapping.getParent();
while (parent != null && !parent.getField().isCollection()) {
parent = parent.getParent();
}
return parent != null && parent.getField().isCollection();
}
public IStatus getStatus(FieldToContractInputMapping mapping) {
return statuses.getOrDefault(mapping,Status.OK_STATUS);
}
}
......@@ -18,7 +18,7 @@ import org.bonitasoft.studio.common.emf.tools.ModelHelper;
import org.bonitasoft.studio.contract.core.mapping.operation.BusinessObjectInstantiationException;
import org.bonitasoft.studio.model.process.ContractInput;
public class CompositionReferencePropertyInitializer extends NewBusinessObjectInitializer implements IPropertyInitializer {
public class CompositionReferencePropertyInitializer extends NewBusinessObjectInitializer {
public CompositionReferencePropertyInitializer(final InitializerContext context) {
super(context);
......@@ -37,11 +37,14 @@ public class CompositionReferencePropertyInitializer extends NewBusinessObjectIn
@Override
protected boolean checkExistence() {
return !hasAMultipleParent();
return hasAMultipleParent()
? super.checkExistence()
: true;
}
private boolean hasAMultipleParent() {
final ContractInput parentInput = ModelHelper.getFirstContainerOfType(context.getContractInput().eContainer(), ContractInput.class);
final ContractInput parentInput = ModelHelper.getFirstContainerOfType(context.getContractInput().eContainer(),
ContractInput.class);
return parentInput != null && parentInput.isMultiple();
}
......
......@@ -16,7 +16,7 @@ package org.bonitasoft.studio.contract.core.mapping.operation.initializer;
import org.bonitasoft.engine.bdm.model.BusinessObject;
public class NewBusinessObjectInitializer extends AbstractBusinessObjectInitializer implements IPropertyInitializer {
public class NewBusinessObjectInitializer extends AbstractBusinessObjectInitializer {
public NewBusinessObjectInitializer(final InitializerContext context) {
super(context);
......@@ -28,20 +28,16 @@ public class NewBusinessObjectInitializer extends AbstractBusinessObjectInitiali
}
@Override
protected void constructor(final StringBuilder scriptBuilder, final BusinessObject bo) {
protected void constructor(StringBuilder scriptBuilder, BusinessObject bo) {
if (checkExistence()) {
final String ref = context.getRef(getParent() != null ? getParent().getContext() : null);
String ref = context.getRef(getParent() != null ? getParent().getContext() : null);
scriptBuilder.append(ref);
scriptBuilder.append(" == null ? ");
newBusinessObject(scriptBuilder, bo);
scriptBuilder.append(" : ");
scriptBuilder.append(ref);
} else {
newBusinessObject(scriptBuilder, bo);
scriptBuilder.append(" ?: ");
}
newBusinessObject(scriptBuilder, bo);
}
private void newBusinessObject(final StringBuilder scriptBuilder, final BusinessObject bo) {
private void newBusinessObject(StringBuilder scriptBuilder, BusinessObject bo) {
scriptBuilder.append("new");
scriptBuilder.append(" ");
scriptBuilder.append(bo.getQualifiedName());
......
......@@ -118,11 +118,19 @@ public class NewBusinessObjectListInitializer extends AbstractBusinessObjectInit
@Override
protected boolean checkExistence() {
return false;
return context.checkExistence();
}
@Override
protected void constructor(final StringBuilder scriptBuilder, final BusinessObject businessObject) {
if (checkExistence()) {
String ref = context.getRef(getParent() != null ? getParent().getContext() : null);
scriptBuilder.append(ref);
scriptBuilder.append("?.find { ");
scriptBuilder.append("it.persistenceId.toString() == ");
scriptBuilder.append(String.format("%s.persistenceId_string", iteratorName(businessObject)));
scriptBuilder.append(" } ?: ");
}
scriptBuilder.append("new ");
scriptBuilder.append(businessObject.getQualifiedName());
scriptBuilder.append("()");
......
......@@ -32,7 +32,8 @@ public class SimpleFieldPropertyInitializer implements IPropertyInitializer {
private final BusinessObject parentBusinessObject;
private AbstractBusinessObjectInitializer parent;
public SimpleFieldPropertyInitializer(final BusinessObject parentBusinessObject, final SimpleField field, final ContractInput contractInput) {
public SimpleFieldPropertyInitializer(final BusinessObject parentBusinessObject, final SimpleField field,
final ContractInput contractInput) {
this.parentBusinessObject = parentBusinessObject;
this.field = field;
this.contractInput = contractInput;
......@@ -49,9 +50,10 @@ public class SimpleFieldPropertyInitializer implements IPropertyInitializer {
@Override
public String getInitialValue() {
final StringBuilder scriptBuilder = withComplexMultipleInHierarchy().apply(contractInput) ?
new StringBuilder(prefixIterator(Joiner.on(".").join(toAncestorNameListUntilMultipleComplex().apply(contractInput)))) :
new StringBuilder(Joiner.on(".").join(ContractInputFunctions.toAncestorNameList().apply(contractInput)));
final StringBuilder scriptBuilder = withComplexMultipleInHierarchy().apply(contractInput)
? new StringBuilder(
prefixIterator(Joiner.on(".").join(toAncestorNameListUntilMultipleComplex().apply(contractInput))))
: new StringBuilder(Joiner.on(".").join(ContractInputFunctions.toAncestorNameList().apply(contractInput)));
castInputValue(scriptBuilder);
return scriptBuilder.toString();
}
......@@ -59,10 +61,10 @@ public class SimpleFieldPropertyInitializer implements IPropertyInitializer {
private void castInputValue(final StringBuilder scriptBuilder) {
switch (field.getType()) {
case FLOAT:
scriptBuilder.append(contractInput.isMultiple() ? ".collect{ it.toFloat() }" : ".toFloat()");
scriptBuilder.append(contractInput.isMultiple() ? "?.collect{ it.toFloat() }" : "?.toFloat()");
break;
case LONG:
scriptBuilder.append(contractInput.isMultiple() ? ".collect{ it.toLong() }" : ".toLong()");
scriptBuilder.append(contractInput.isMultiple() ? "?.collect{ it.toLong() }" : "?.toLong()");
break;
default:
break;
......@@ -74,7 +76,8 @@ public class SimpleFieldPropertyInitializer implements IPropertyInitializer {
}
private String iteratorName() {
return "current" + BDMSimpleNameProvider.getSimpleBusinessObjectName(parentBusinessObject.getQualifiedName()) + "Input";
return "current" + BDMSimpleNameProvider.getSimpleBusinessObjectName(parentBusinessObject.getQualifiedName())
+ "Input";
}
@Override
......
......@@ -14,6 +14,8 @@
*/
package org.bonitasoft.studio.contract.core.mapping.operation.initializer.factory;
import org.bonitasoft.engine.bdm.model.field.Field;
import org.bonitasoft.engine.bdm.model.field.RelationField;
import org.bonitasoft.engine.bdm.model.field.RelationField.Type;
import org.bonitasoft.studio.contract.core.mapping.FieldToContractInputMapping;
import org.bonitasoft.studio.contract.core.mapping.operation.VariableNameResolver;
......@@ -36,12 +38,22 @@ public class RelationPropertyInitializerFactory extends AbsractInitializerFactor
@Override
public IPropertyInitializer newPropertyInitializer(FieldToContractInputMapping mapping,
BusinessObjectData data, boolean isOnPool) {
InitializerContext context = createContext(data, variableNameResolver, mapping, false, isOnPool);
InitializerContext context = createContext(data, variableNameResolver, mapping, checkExistence(mapping, isOnPool),
isOnPool);
return context.getField().getType() == Type.AGGREGATION
? newAggregatedReferenceInitializer(context)
: newComposedReferenceInitializer(context);
}
protected boolean checkExistence(FieldToContractInputMapping mapping, boolean isOnPool) {
if (!isOnPool && mapping.getParent() != null) {
Field parent = mapping.getParent().getField();
boolean isComposition = ((RelationField) mapping.getField()).getType().equals(RelationField.Type.COMPOSITION);
return parent.isCollection() && isComposition;
}
return false;
}
private IPropertyInitializer newAggregatedReferenceInitializer(InitializerContext context) {
return context.getField().isCollection()
? new MultipleAggregationReferencePropertyInitializer(
......
......@@ -126,4 +126,9 @@ public class Messages extends NLS {
public static String taskBdmTips;
public static String poolBdmTips;
public static String creatingNewForm;
public static String createDataFromContractChoice;
public static String editDataFromContractChoice;
public static String lazyFieldInAMultipleParentRelationHasBeenDeselect;
public static String aChildHasBeenUnselected;
public static String moreInfoFormGenerationLink;
}
......@@ -181,8 +181,12 @@ public class ContractInputProposalsCodeVisitorSupport extends CodeVisitorSupport
Collections.<ClassNode> emptySet(), prefix.toString(),
false, false);
for (final IGroovyProposal p : allProposals) {
final IJavaCompletionProposal javaProposal = p.createJavaProposal(contentAssistContext, javaContext);
result.add(javaProposal);
try {
final IJavaCompletionProposal javaProposal = p.createJavaProposal(contentAssistContext, javaContext);
result.add(javaProposal);
}catch (NullPointerException e) {
// No CompletionEngine available ?
}
}
return result;
}
......
......@@ -33,11 +33,12 @@ import org.eclipse.core.runtime.Status;
public final class AvailableDataValidator extends MultiValidator {
private final List<Data> availableBusinessData;
private final WritableValue selectedDataObservable;
private final WritableValue<Object> selectedDataObservable;
private final BusinessObjectModelRepositoryStore<BusinessObjectModelFileStore> businessObjectStore;
private final List<Document> availableDocuments;
public AvailableDataValidator(final List<Data> availableBusinessData, final WritableValue selectedDataObservable,
public AvailableDataValidator(final List<Data> availableBusinessData,
final WritableValue<Object> selectedDataObservable,
final List<Document> availableDocuments,
final BusinessObjectModelRepositoryStore<BusinessObjectModelFileStore> businessObjectStore) {
this.availableBusinessData = availableBusinessData;
......
......@@ -35,6 +35,7 @@ import org.bonitasoft.studio.contract.core.mapping.operation.DocumentUpdateOpera
import org.bonitasoft.studio.contract.core.mapping.operation.FieldToContractInputMappingOperationBuilder;
import org.bonitasoft.studio.contract.core.mapping.operation.OperationCreationException;
import org.bonitasoft.studio.contract.i18n.Messages;
import org.bonitasoft.studio.contract.ui.wizard.GenerationOptions.EditMode;
import org.bonitasoft.studio.groovy.ui.viewer.GroovySourceViewerFactory;
import org.bonitasoft.studio.model.expression.Operation;
import org.bonitasoft.studio.model.process.AbstractProcess;
......@@ -107,8 +108,7 @@ public class ContractInputGenerationWizard extends Wizard {
generationOptions = new GenerationOptions();
this.editingDomain = editingDomain;
this.repositoryAccessor = repositoryAccessor;
fieldToContractInputMappingFactory = new FieldToContractInputMappingFactory(
repositoryAccessor.getRepositoryStore(BusinessObjectModelRepositoryStore.class));
fieldToContractInputMappingFactory = new FieldToContractInputMappingFactory(repositoryAccessor.getRepositoryStore(BusinessObjectModelRepositoryStore.class));
this.operationBuilder = operationBuilder;
this.expressionBuilder = expressionBuilder;
this.preferenceStore = preferenceStore;
......@@ -120,8 +120,8 @@ public class ContractInputGenerationWizard extends Wizard {
@Override
public void addPages() {
selectedDataObservable = new WritableValue();
rootNameObservable = new WritableValue();
selectedDataObservable = new WritableValue<Object>();
rootNameObservable = new WritableValue<String>();
fieldToContractInputMappingsObservable = new WritableList(new ArrayList<FieldToContractInputMapping>(),
FieldToContractInputMapping.class);
availableBusinessData = availableBusinessData();
......@@ -136,14 +136,19 @@ public class ContractInputGenerationWizard extends Wizard {
availableDocuments = ModelHelper.getParentPool(contractContainer).getDocuments();
selectBusinessDataWizardPage = contractInputWizardPagesFactory.createSelectBusinessDataWizardPage(
contractContainer.getContract(),
availableBusinessData, availableDocuments,
availableBusinessData,
availableDocuments,
selectedDataObservable,
rootNameObservable,
generationOptions,
repositoryAccessor.getRepositoryStore(BusinessObjectModelRepositoryStore.class));
addPage(selectBusinessDataWizardPage);
contractInputFromBusinessObjectWizardPage = contractInputWizardPagesFactory
.createCreateContratInputFromBusinessObjectWizardPage(
contractContainer, generationOptions, selectedDataObservable, rootNameObservable,
contractContainer,
generationOptions,
selectedDataObservable,
rootNameObservable,
fieldToContractInputMappingFactory,
fieldToContractInputMappingsObservable,
repositoryAccessor.getRepositoryStore(BusinessObjectModelRepositoryStore.class));
......@@ -164,10 +169,7 @@ public class ContractInputGenerationWizard extends Wizard {
return newArrayList(filter(pool.getData(), instanceOf(BusinessObjectData.class)));
}
/*
* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
@Override
public boolean canFinish() {
if (availableBusinessData.isEmpty() && availableDocuments.isEmpty()) {
......@@ -176,10 +178,7 @@ public class ContractInputGenerationWizard extends Wizard {
return super.canFinish();
}
/*
* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#performFinish()
*/
@Override
public boolean performFinish() {
final Object selectedData = selectedDataObservable.getValue();
......@@ -299,7 +298,7 @@ public class ContractInputGenerationWizard extends Wizard {
private int openInfoDialog() {
return infoDialogFactory.openInfoDialog(preferenceStore, getShell(), contractContainer,
generationOptions.isAutogeneratedScript());
generationOptions.isAutoGeneratedScript());
}
protected CompoundCommand createCommand(final RootContractInputGenerator contractInputGenerator,
......@@ -309,12 +308,12 @@ public class ContractInputGenerationWizard extends Wizard {
contractInputGenerator.getRootContractInput()));
if (contractContainer instanceof OperationContainer
&& generationOptions.isAutogeneratedScript()) {
&& generationOptions.isAutoGeneratedScript()) {
cc.appendIfCanExecute(AddCommand.create(editingDomain, contractContainer,
ProcessPackage.Literals.OPERATION_CONTAINER__OPERATIONS,
contractInputGenerator.getMappingOperations()));
}
if (contractContainer instanceof Pool && generationOptions.isAutogeneratedScript()) {
if (contractContainer instanceof Pool && generationOptions.isAutoGeneratedScript()) {
cc.appendIfCanExecute(SetCommand.create(editingDomain, data, ProcessPackage.Literals.DATA__DEFAULT_VALUE,
contractInputGenerator.getInitialValueExpression()));
......
......@@ -52,9 +52,10 @@ public class ContractInputGenerationWizardPagesFactory {
List<Document> availableDocuments,
WritableValue selectedDataObservable,
WritableValue rootNameObservable,
GenerationOptions generateOptions,
BusinessObjectModelRepositoryStore businessObjectStore) {
return new SelectDataWizardPage(contract, availableBusinessData, availableDocuments, selectedDataObservable,
rootNameObservable, businessObjectStore);
rootNameObservable, generateOptions,businessObjectStore);
}
public GeneratedScriptPreviewPage createGeneratedScriptPreviewPage(WritableValue rootNameObservable,
......
......@@ -14,22 +14,50 @@
*/
package org.bonitasoft.studio.contract.ui.wizard;
/**
* @author aurelie
*/
import org.eclipse.core.databinding.beans.PojoProperties;
import org.eclipse.core.databinding.observable.value.IObservableValue;
public class GenerationOptions {
private boolean autogeneratedScript = true;
public enum EditMode {
CREATE, EDIT
}
private boolean autoGeneratedScript = true;
private EditMode editMode = EditMode.CREATE;
private IObservableValue<EditMode> editModeObservable;
private IObservableValue<Boolean> autogeneratedScriptObservable;
public void setEditMode(EditMode mode) {
this.editMode = mode;
}
public EditMode getEditMode() {
return editMode;
}
public IObservableValue<EditMode> getEditModeObservable() {
if(editModeObservable == null) {
editModeObservable = PojoProperties.value("editMode").observe(this);
}
return editModeObservable;
}
public boolean isAutoGeneratedScript() {
return autoGeneratedScript;
}
public boolean isAutogeneratedScript() {
return autogeneratedScript;
public void setAutoGeneratedScript(boolean isAutoGeneratedScript) {
this.autoGeneratedScript = isAutoGeneratedScript;
}
/**
* @param isAutogeneratedScript the isAutogeneratedScript to set
*/
public void setAutogeneratedScript(final boolean isAutogeneratedScript) {
autogeneratedScript = isAutogeneratedScript;
public IObservableValue<Boolean> getAutoGeneratedScriptObservable() {
if(autogeneratedScriptObservable == null) {
autogeneratedScriptObservable = PojoProperties.value("autoGeneratedScript").observe(this);
}
return autogeneratedScriptObservable;
}
}
......@@ -15,24 +15,69 @@
package org.bonitasoft.studio.contract.ui.wizard.labelProvider;
import org.bonitasoft.studio.contract.core.mapping.FieldToContractInputMapping;
import org.bonitasoft.studio.contract.core.mapping.SimpleFieldToContractInputMapping;
import org.bonitasoft.studio.contract.core.mapping.UnselectLazyReferencesInMultipleContainer;
import org.bonitasoft.studio.model.process.Task;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
/**
* @author aurelie
*/
public class FieldNameColumnLabelProvider extends ColumnLabelProvider {
/*
* (non-Javadoc)
* @see org.eclipse.jface.viewers.ColumnLabelProvider#getText(java.lang.Object)
*/