private static void fillRequirementsMap(
     Map<String, Requirement> map,
     List<RequirementDefinition> elements,
     Collection<CSARDependency> dependencies,
     Map<String, Requirement> mapToMerge,
     IToscaElementFinder toscaElementFinder) {
   if (elements == null) {
     return;
   }
   for (RequirementDefinition requirement : elements) {
     Requirement toAddRequirement = MapUtils.getObject(mapToMerge, requirement.getId());
     if (toAddRequirement == null) {
       toAddRequirement = new Requirement();
       toAddRequirement.setType(requirement.getType());
       IndexedCapabilityType indexedReq =
           toscaElementFinder.getElementInDependencies(
               IndexedCapabilityType.class, requirement.getType(), dependencies);
       if (indexedReq != null && indexedReq.getProperties() != null) {
         toAddRequirement.setProperties(
             PropertyUtil.getDefaultPropertyValuesFromPropertyDefinitions(
                 indexedReq.getProperties()));
       }
     }
     map.put(requirement.getId(), toAddRequirement);
   }
 }
  @SuppressWarnings("unchecked")
  @Test
  public void testNodeType() throws FileNotFoundException, ParsingException {
    Mockito.reset(repositorySearchService);
    IndexedNodeType mockedResult = Mockito.mock(IndexedNodeType.class);
    Mockito.when(
            repositorySearchService.getElementInDependencies(
                Mockito.eq(IndexedNodeType.class),
                Mockito.eq("tosca.nodes.SoftwareComponent"),
                Mockito.any(List.class)))
        .thenReturn(mockedResult);
    Mockito.when(mockedResult.getDerivedFrom()).thenReturn(Lists.newArrayList("tosca.nodes.Root"));
    Mockito.when(
            repositorySearchService.getElementInDependencies(
                Mockito.eq(IndexedNodeType.class),
                Mockito.eq("tosca.nodes.Root"),
                Mockito.any(List.class)))
        .thenReturn(mockedResult);

    Mockito.when(
            repositorySearchService.getElementInDependencies(
                Mockito.eq(IndexedNodeType.class),
                Mockito.eq("tosca.nodes.Compute"),
                Mockito.any(List.class)))
        .thenReturn(mockedResult);
    IndexedCapabilityType mockedCapabilityResult = Mockito.mock(IndexedCapabilityType.class);
    Mockito.when(
            repositorySearchService.getElementInDependencies(
                Mockito.eq(IndexedCapabilityType.class),
                Mockito.eq("mytypes.mycapabilities.MyCapabilityTypeName"),
                Mockito.any(List.class)))
        .thenReturn(mockedCapabilityResult);
    Mockito.when(
            repositorySearchService.getElementInDependencies(
                Mockito.eq(IndexedCapabilityType.class),
                Mockito.eq("mytypes.mycapabilities.MyCapabilityTypeName"),
                Mockito.any(List.class)))
        .thenReturn(mockedCapabilityResult);

    Mockito.when(
            repositorySearchService.getElementInDependencies(
                Mockito.eq(IndexedCapabilityType.class),
                Mockito.eq("tosca.capabilities.Endpoint"),
                Mockito.any(List.class)))
        .thenReturn(mockedCapabilityResult);
    IndexedRelationshipType hostedOn = new IndexedRelationshipType();
    Mockito.when(
            repositorySearchService.getElementInDependencies(
                Mockito.eq(IndexedRelationshipType.class),
                Mockito.eq("tosca.relationships.HostedOn"),
                Mockito.any(List.class)))
        .thenReturn(hostedOn);

    ParsingResult<ArchiveRoot> parsingResult =
        parser.parseFile(Paths.get(getRootDirectory(), "tosca-node-type.yml"));

    assertNoBlocker(parsingResult);
    ArchiveRoot archiveRoot = parsingResult.getResult();
    Assert.assertNotNull(archiveRoot.getArchive());
    Assert.assertEquals(getToscaVersion(), archiveRoot.getArchive().getToscaDefinitionsVersion());
    Assert.assertEquals(1, archiveRoot.getNodeTypes().size());
    // check node type.
    Entry<String, IndexedNodeType> entry = archiveRoot.getNodeTypes().entrySet().iterator().next();

    Assert.assertEquals("my_company.my_types.MyAppNodeType", entry.getKey());
    IndexedNodeType nodeType = entry.getValue();

    Assert.assertEquals(
        Lists.newArrayList("tosca.nodes.SoftwareComponent", "tosca.nodes.Root"),
        nodeType.getDerivedFrom());
    Assert.assertEquals("My company’s custom applicaton", nodeType.getDescription());

    // validate properties parsing
    Assert.assertEquals(4, nodeType.getProperties().size());

    PropertyDefinition def1 = new PropertyDefinition();
    def1.setType("string");
    def1.setDefault(new ScalarPropertyValue("default"));
    def1.setDescription("application password");
    List<PropertyConstraint> constraints = Lists.newArrayList();
    constraints.add(new MinLengthConstraint(6));
    constraints.add(new MaxLengthConstraint(10));
    def1.setConstraints(constraints);

    PropertyDefinition def2 = new PropertyDefinition();
    def2.setType("integer");
    def2.setDescription("application port number");

    PropertyDefinition def3 = new PropertyDefinition();
    def3.setType("scalar-unit.size");
    def3.setDefault(new ScalarPropertyValue("1 GB"));
    LessThanConstraint ltConstraint = new LessThanConstraint();
    ltConstraint.setLessThan("1 TB");
    constraints = Lists.<PropertyConstraint>newArrayList(ltConstraint);
    def3.setConstraints(constraints);

    PropertyDefinition def4 = new PropertyDefinition();
    def4.setType("scalar-unit.time");
    def4.setDefault(new ScalarPropertyValue("1 d"));
    GreaterThanConstraint gtConstraint = new GreaterThanConstraint();
    gtConstraint.setGreaterThan("1 h");
    constraints = Lists.<PropertyConstraint>newArrayList(gtConstraint);
    def4.setConstraints(constraints);

    Assert.assertEquals(
        MapUtil.newHashMap(
            new String[] {"my_app_password", "my_app_duration", "my_app_size", "my_app_port"},
            new PropertyDefinition[] {def1, def4, def3, def2}),
        nodeType.getProperties());

    // check requirements
    Assert.assertEquals(2, nodeType.getRequirements().size());
    RequirementDefinition rd0 = nodeType.getRequirements().get(0);
    Assert.assertEquals("host", rd0.getId());
    Assert.assertEquals(1, rd0.getLowerBound());
    Assert.assertEquals(1, rd0.getUpperBound());

    RequirementDefinition rd1 = nodeType.getRequirements().get(1);
    Assert.assertEquals("other", rd1.getId());
    Assert.assertEquals(0, rd1.getLowerBound());
    Assert.assertEquals(Integer.MAX_VALUE, rd1.getUpperBound());

    // validate attributes parsing

    // nodeType.getAttributes()
    // nodeType.getInterfaces()
    // nodeType.getCapabilities()
    // nodeType.get
  }
  public void updateSubstitutionType(final Topology topology) {
    if (!topology.getDelegateType().equalsIgnoreCase(TopologyTemplate.class.getSimpleName())) {
      return;
    }
    if (topology.getSubstitutionMapping() == null
        || topology.getSubstitutionMapping().getSubstitutionType() == null) {
      return;
    }
    IndexedNodeType nodeType =
        csarRepoSearchService.getElementInDependencies(
            IndexedNodeType.class,
            topology.getSubstitutionMapping().getSubstitutionType().getElementId(),
            topology.getDependencies());

    TopologyTemplate topologyTemplate =
        alienDAO.findById(TopologyTemplate.class, topology.getDelegateId());
    TopologyTemplateVersion topologyTemplateVersion =
        topologyTemplateVersionService.getByTopologyId(topology.getId());

    Set<CSARDependency> inheritanceDependencies = Sets.newHashSet();
    inheritanceDependencies.add(
        new CSARDependency(nodeType.getArchiveName(), nodeType.getArchiveVersion()));

    // we have to search for the eventually existing CSar to update it' deps
    // actually, the csar is not renamed when the topology template is renamed (this is not quite
    // simple to rename a csar if it
    // is used in topologies ....). So we have to search the csar using the topology id.
    Csar csar = csarService.getTopologySubstitutionCsar(topology.getId());
    if (csar == null) {
      // the csar can not be found, we create it
      String archiveName = topologyTemplate.getName();
      String archiveVersion = topologyTemplateVersion.getVersion();
      csar = new Csar(archiveName, archiveVersion);
      csar.setSubstitutionTopologyId(topology.getId());
    }
    csar.setDependencies(inheritanceDependencies);
    csar.getDependencies().addAll(topology.getDependencies());
    csarService.save(csar);

    IndexedNodeType topologyTemplateType = new IndexedNodeType();
    topologyTemplateType.setArchiveName(csar.getName());
    topologyTemplateType.setArchiveVersion(csar.getVersion());
    topologyTemplateType.setElementId(csar.getName());
    topologyTemplateType.setDerivedFrom(Lists.newArrayList(nodeType.getElementId()));
    topologyTemplateType.setSubstitutionTopologyId(topology.getId());
    List<CapabilityDefinition> capabilities = Lists.newArrayList();
    topologyTemplateType.setCapabilities(capabilities);
    List<RequirementDefinition> requirements = Lists.newArrayList();
    topologyTemplateType.setRequirements(requirements);
    // inputs from topology become properties of type
    topologyTemplateType.setProperties(topology.getInputs());
    // output attributes become attributes for the type
    Map<String, IValue> attributes = Maps.newHashMap();
    topologyTemplateType.setAttributes(attributes);
    Map<String, Set<String>> outputAttributes = topology.getOutputAttributes();
    if (outputAttributes != null) {
      for (Entry<String, Set<String>> oae : outputAttributes.entrySet()) {
        String nodeName = oae.getKey();
        NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName);
        IndexedNodeType nodeTemplateType =
            csarRepoSearchService.getRequiredElementInDependencies(
                IndexedNodeType.class, nodeTemplate.getType(), topology.getDependencies());
        for (String attributeName : oae.getValue()) {
          IValue ivalue = nodeTemplateType.getAttributes().get(attributeName);
          // we have an issue here : if several nodes have the same attribute name, there is a
          // conflict
          if (ivalue != null && !attributes.containsKey(attributeName)) {
            attributes.put(attributeName, ivalue);
          }
        }
      }
    }
    // output properties become attributes for the type
    Map<String, Set<String>> outputProperties = topology.getOutputProperties();
    if (outputProperties != null) {
      for (Entry<String, Set<String>> ope : outputProperties.entrySet()) {
        String nodeName = ope.getKey();
        NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName);
        IndexedNodeType nodeTemplateType =
            csarRepoSearchService.getRequiredElementInDependencies(
                IndexedNodeType.class, nodeTemplate.getType(), topology.getDependencies());
        for (String propertyName : ope.getValue()) {
          PropertyDefinition pd = nodeTemplateType.getProperties().get(propertyName);
          // we have an issue here : if several nodes have the same attribute name, there is a
          // conflict
          if (pd != null && !attributes.containsKey(propertyName)) {
            attributes.put(propertyName, pd);
          }
        }
      }
    }
    // output capabilities properties also become attributes for the type
    Map<String, Map<String, Set<String>>> outputCapabilityProperties =
        topology.getOutputCapabilityProperties();
    if (outputCapabilityProperties != null) {
      for (Entry<String, Map<String, Set<String>>> ocpe : outputCapabilityProperties.entrySet()) {
        String nodeName = ocpe.getKey();
        NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName);
        for (Entry<String, Set<String>> cpe : ocpe.getValue().entrySet()) {
          String capabilityName = cpe.getKey();
          String capabilityTypeName = nodeTemplate.getCapabilities().get(capabilityName).getType();
          IndexedCapabilityType capabilityType =
              csarRepoSearchService.getRequiredElementInDependencies(
                  IndexedCapabilityType.class, capabilityTypeName, topology.getDependencies());
          for (String propertyName : cpe.getValue()) {
            PropertyDefinition pd = capabilityType.getProperties().get(propertyName);
            // we have an issue here : if several nodes have the same attribute name, there is a
            // conflict
            if (pd != null && !attributes.containsKey(propertyName)) {
              attributes.put(propertyName, pd);
            }
          }
        }
      }
    }

    // capabilities substitution
    if (topology.getSubstitutionMapping().getCapabilities() != null) {
      for (Entry<String, SubstitutionTarget> e :
          topology.getSubstitutionMapping().getCapabilities().entrySet()) {
        String key = e.getKey();
        String nodeName = e.getValue().getNodeTemplateName();
        String capabilityName = e.getValue().getTargetId();
        NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName);
        IndexedNodeType nodeTemplateType =
            csarRepoSearchService.getRequiredElementInDependencies(
                IndexedNodeType.class, nodeTemplate.getType(), topology.getDependencies());
        CapabilityDefinition capabilityDefinition =
            IndexedModelUtils.getCapabilityDefinitionById(
                nodeTemplateType.getCapabilities(), capabilityName);
        capabilityDefinition.setId(key);
        topologyTemplateType.getCapabilities().add(capabilityDefinition);
      }
    }
    // requirement substitution
    if (topology.getSubstitutionMapping().getRequirements() != null) {
      for (Entry<String, SubstitutionTarget> e :
          topology.getSubstitutionMapping().getRequirements().entrySet()) {
        String key = e.getKey();
        String nodeName = e.getValue().getNodeTemplateName();
        String requirementName = e.getValue().getTargetId();
        NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeName);
        IndexedNodeType nodeTemplateType =
            csarRepoSearchService.getRequiredElementInDependencies(
                IndexedNodeType.class, nodeTemplate.getType(), topology.getDependencies());
        RequirementDefinition requirementDefinition =
            IndexedModelUtils.getRequirementDefinitionById(
                nodeTemplateType.getRequirements(), requirementName);
        requirementDefinition.setId(key);
        topologyTemplateType.getRequirements().add(requirementDefinition);
      }
    }
    indexerService.indexInheritableElement(
        csar.getName(), csar.getVersion(), topologyTemplateType, inheritanceDependencies);
  }