1341b8bd1dfb6f8b5b06f9b365e5dc64fcb13098
[ccsdk/cds.git] /
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2019 IBM Intellectual Property. All rights reserved.
5 ===================================================================
6
7 Unless otherwise specified, all software contained herein is licensed
8 under the Apache License, Version 2.0 (the License);
9 you may not use this software except in compliance with the License.
10 You may obtain a copy of the License at
11
12     http://www.apache.org/licenses/LICENSE-2.0
13
14 Unless required by applicable law or agreed to in writing, software
15 distributed under the License is distributed on an "AS IS" BASIS,
16 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 See the License for the specific language governing permissions and
18 limitations under the License.
19 ============LICENSE_END============================================
20 */
21
22 import { Component, OnInit, ViewChild, EventEmitter, Output } from '@angular/core';
23 import { FormBuilder, FormGroup, Validators } from '@angular/forms';
24 import { Store } from '@ngrx/store';
25 import { SearchTemplateService } from '../search-template.service';
26 import { MatAutocompleteTrigger } from '@angular/material';
27 import { NotificationHandlerService } from 'src/app/common/core/services/notification-handler.service';
28 import { SearchPipe } from 'src/app/common/shared/pipes/search.pipe';
29 import * as JSZip from 'jszip';
30 import { SortPipe } from '../../../../../common/shared/pipes/sort.pipe';
31 import { LoaderService } from '../../../../../common/core/services/loader.service';
32 import { IBlueprint } from '../../../../../common/core/store/models/blueprint.model';
33 import { IBlueprintState } from '../../../../../common/core/store/models/blueprintState.model';
34 import { IAppState } from '../../../../../common/core/store/state/app.state';
35 import { SetBlueprintState } from '../../../../../common/core/store/actions/blueprint.action';
36 import { SelectTemplateService } from '../../select-template.service';
37 @Component({
38   selector: 'app-search-from-database',
39   templateUrl: './search-from-database.component.html',
40   styleUrls: ['./search-from-database.component.scss']
41 })
42 export class SearchFromDatabaseComponent implements OnInit {
43
44   myControl: FormGroup;
45   @Output() resourcesData = new EventEmitter();
46   options: any[] = [];
47   // @ViewChild('resourceSelect', { read: MatAutocompleteTrigger }) resourceSelect: MatAutocompleteTrigger;
48
49   validfile: boolean = false;
50   filesTree: any = [];
51   filesData: any = [];
52   private zipFile: JSZip = new JSZip();
53   private paths = [];
54   private tree;
55   private fileObject: any;
56   private activationBlueprint: any;
57   private tocsaMetadaData: any;
58   private blueprintName: string;
59   private entryDefinition: string;
60   uploadedFileName: string;
61
62   searchText: string = '';
63   constructor(private _formBuilder: FormBuilder,
64     private searchService: SearchTemplateService, private alertService: NotificationHandlerService,
65     private loader: LoaderService, private store: Store<IAppState>, private cbEditOption: SelectTemplateService) { }
66
67   ngOnInit() {
68     this.myControl = this._formBuilder.group({
69       search_input: ['', Validators.required]
70     });
71   }
72   selected(value) {
73     this.resourcesData.emit(value);
74   }
75
76   fetchResourceByName() {
77     this.options = [];
78     this.searchService.searchByTags(this.searchText)
79       .subscribe(data => {
80         data.forEach(element => {
81           this.options.push(element)
82         });
83       }, error => {
84         this.alertService.error('Blueprint not matching the search tag' + error);
85       })
86   }
87
88   editCBA(artifactName: string, artifactVersion: string, option: string) {
89     this.cbEditOption.setCbaOption(option);
90     this.uploadedFileName = artifactName;
91     console.log("filename:" + this.uploadedFileName);
92     this.zipFile.generateAsync({ type: "blob" })
93       .then(blob => {
94         const formData = new FormData();
95         formData.append("file", blob);
96         // this.editorService.enrich("/enrich-blueprint/", formData)
97         this.searchService.getBlueprintZip(artifactName + "/" + artifactVersion)
98           .subscribe(
99             (response) => {
100               // console.log(response);
101               this.zipFile.files = {};
102               this.zipFile.loadAsync(response)
103                 .then((zip) => {
104                   if (zip) {
105                     this.buildFileViewData(zip);
106                   }
107                 });
108               // this.alertService.success('Blueprint enriched successfully');
109             },
110             (error) => {
111               this.alertService.error('Blue print error' + error.message);
112             });
113       });
114   }
115
116   async buildFileViewData(zip) {
117     this.validfile = false;
118     this.paths = [];
119     // console.log(zip.files);
120     for (var file in zip.files) {
121       console.log("name: " + zip.files[file].name);
122       this.fileObject = {
123         // nameForUIDisplay: this.uploadedFileName + '/' + zip.files[file].name,
124         // name: zip.files[file].name,
125         name: this.uploadedFileName + '/' + zip.files[file].name,
126         data: ''
127       };
128       const value = <any>await zip.files[file].async('string');
129       this.fileObject.data = value;
130       this.paths.push(this.fileObject);
131     }
132
133     if (this.paths) {
134       this.paths.forEach(path => {
135         if (path.name.includes("TOSCA.meta")) {
136           this.validfile = true
137         }
138       });
139     } else {
140       alert('Please update proper file');
141     }
142
143     if (this.validfile) {
144       this.fetchTOSACAMetadata();
145       this.paths = new SortPipe().transform(this.paths, 'asc', 'name');
146       this.tree = this.arrangeTreeData(this.paths);
147     } else {
148       alert('Please update proper file with TOSCA metadata');
149     }
150   }
151
152   arrangeTreeData(paths) {
153     const tree = [];
154
155     paths.forEach((path) => {
156
157       const pathParts = path.name.split('/');
158       // pathParts.shift();
159       let currentLevel = tree;
160
161       pathParts.forEach((part) => {
162         const existingPath = currentLevel.filter(level => level.name === part);
163
164         if (existingPath.length > 0) {
165           currentLevel = existingPath[0].children;
166         } else {
167           const newPart = {
168             name: part,
169             children: [],
170             data: path.data,
171             path: path.name
172           };
173           if (part.trim() == this.blueprintName.trim()) {
174             this.activationBlueprint = path.data;
175             newPart.data = JSON.parse(this.activationBlueprint.toString());
176             // console.log('newpart', newPart);
177             this.entryDefinition = path.name.trim();
178           }
179           if (newPart.name !== '') {
180             currentLevel.push(newPart);
181             currentLevel = newPart.children;
182           }
183         }
184       });
185     });
186     this.loader.hideLoader();
187     this.filesTree = tree;
188     this.updateBlueprint();
189   }
190
191   fetchTOSACAMetadata() {
192     let toscaData = {};
193     this.paths.forEach(file => {
194       if (file.name.includes('TOSCA.meta')) {
195         let keys = file.data.split("\n");
196         keys.forEach((key) => {
197           let propertyData = key.split(':');
198           toscaData[propertyData[0]] = propertyData[1];
199         });
200       }
201     });
202     this.blueprintName = (((toscaData['Entry-Definitions']).split('/'))[1]).toString();;
203     // console.log(toscaData);
204   }
205
206   updateBlueprint() {
207
208     let data: IBlueprint = this.activationBlueprint ? JSON.parse(this.activationBlueprint.toString()) : this.activationBlueprint;
209     let blueprintState = {
210       blueprint: data,
211       name: this.blueprintName,
212       files: this.filesTree,
213       filesData: this.filesData,
214       uploadedFileName: this.uploadedFileName,
215       entryDefinition: this.entryDefinition
216     }
217     this.store.dispatch(new SetBlueprintState(blueprintState));
218   }
219
220 }