Added oparent to sdc main
[sdc.git] / asdctool / src / main / java / org / openecomp / sdc / asdctool / impl / validator / executers / ArtifactValidatorExecuter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.asdctool.impl.validator.executers;
22
23 import fj.data.Either;
24 import org.openecomp.sdc.asdctool.impl.validator.config.ValidationConfigManager;
25 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
26 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
27 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
28 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
29 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
30 import org.openecomp.sdc.be.model.ArtifactDefinition;
31 import org.openecomp.sdc.be.model.Component;
32 import org.openecomp.sdc.be.model.ComponentParametersView;
33 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
34 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
35 import org.openecomp.sdc.common.log.wrappers.Logger;
36 import org.springframework.beans.factory.annotation.Autowired;
37
38 import java.io.*;
39 import java.util.*;
40 import java.util.stream.Collectors;
41
42 public class ArtifactValidatorExecuter{
43         
44          @Autowired
45          protected JanusGraphDao janusGraphDao;
46
47          @Autowired
48          private ToscaOperationFacade toscaOperationFacade;
49          private static Logger log = Logger.getLogger(ArtifactValidatorExecuter.class.getName());
50          
51          protected String name;
52
53             public void setName(String name) {
54                 this.name = name;
55             }
56
57             public String getName() {
58                 return name;
59             }
60
61          
62         
63            public Map<String, List<Component>> getVerticesToValidate(VertexTypeEnum type, Map<GraphPropertyEnum, Object> hasProps){
64                    Map<String, List<Component>> result = new HashMap<>();
65                 Either<List<GraphVertex>, JanusGraphOperationStatus> resultsEither = janusGraphDao
66               .getByCriteria(type, hasProps);
67                 if (resultsEither.isRight()) {
68                         log.error("getVerticesToValidate failed "+ resultsEither.right().value());
69                     return result;
70                 }
71                 System.out.println("getVerticesToValidate: "+resultsEither.left().value().size()+" vertices to scan");
72                 List<GraphVertex> componentsList = resultsEither.left().value();
73                 componentsList.forEach(vertex -> {
74                         String ivariantUuid = (String)vertex.getMetadataProperty(GraphPropertyEnum.INVARIANT_UUID);
75                         if(!result.containsKey(ivariantUuid)){
76                                 List<Component> compList = new ArrayList<Component>();
77                                 result.put(ivariantUuid, compList);
78                         }
79                         List<Component> compList = result.get(ivariantUuid);
80                         
81                         ComponentParametersView filter = new ComponentParametersView(true);                             
82                                 filter.setIgnoreArtifacts(false);
83                                 
84                                 Either<Component, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(vertex.getUniqueId(), filter);
85                                 if (toscaElement.isRight()) {
86                                         log.error("getVerticesToValidate: failed to find element"+ vertex.getUniqueId()+" staus is" + toscaElement.right().value());
87                                 }else{
88                                         compList.add(toscaElement.left().value());
89                                 }
90                          
91                 });             
92               
93                         return result;
94             }
95             
96            public boolean validate( Map<String, List<Component>> vertices) {
97                    boolean result = true;
98                    long time = System.currentTimeMillis();
99                    String fileName = ValidationConfigManager.getOutputFilePath() + this.getName() + "_"+ time + ".csv";
100                    try(Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"))) {
101                         writer.write("name, UUID, invariantUUID, state, version\n");
102                         Collection<List<Component>> collection = vertices.values();
103                         for(List<Component> compList: collection ){
104                                 Set<String> artifactEsId = new HashSet<>();
105                                 for(Component component: compList ){
106                                         Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
107                                         Optional<ArtifactDefinition> op = toscaArtifacts.values().
108                                                         stream().filter(a -> artifactEsId.contains(a.getEsId())).findAny();
109                                         if(op.isPresent()){
110                                                 result = false;
111                                                 writeModuleResultToFile(writer, compList);
112                                                 writer.flush();
113                                                 break;
114                                         }else{
115                                                 artifactEsId.addAll(toscaArtifacts.values().stream().map(ArtifactDefinition::getEsId).collect(Collectors.toList()))     ;
116                                         }
117                                 }
118                                 
119                         }
120                         
121                    } catch (Exception e) {
122                                 log.error("Failed to fetch vf resources ", e);
123                                 return false;
124                         } finally {
125                                 janusGraphDao.commit();
126                         }
127                         return result;
128             }
129            
130            private void writeModuleResultToFile(Writer writer, List<Component> components) {
131                         try {
132                                 // "service name, service id, state, version
133                                 for(Component component: components ){
134                                         StringBuffer sb = new StringBuffer(component.getName());
135                                         sb.append(",").append(component.getUniqueId()).append(",").append(component.getInvariantUUID()).append(",").append(component.getLifecycleState()).append(",").append(component.getVersion());
136                                         
137                                         sb.append("\n");
138                                         writer.write(sb.toString());
139                                 }
140                         } catch (IOException e) {
141                                 log.error("Failed to write module result to file ", e);
142                         }
143                 }
144
145 }