netconf-executor: adding pojo tests
[ccsdk/cds.git] / cds-ui / server / src / controllers / blueprint-rest.controller.ts
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018-19 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
23
24 import {
25   Count,
26   CountSchema,
27   Filter,
28   repository,
29   Where,
30 } from '@loopback/repository';
31 import {
32   post,
33   param,
34   get,
35   getFilterSchemaFor,
36   getWhereSchemaFor,
37   patch,
38   put,
39   del,
40   requestBody,
41   Request,
42   Response,
43   RestBindings,
44 } from '@loopback/rest';
45 import {Blueprint} from '../models';
46 import { inject } from '@loopback/core';
47 import { BlueprintService } from '../services';
48 import * as fs from 'fs';
49 import * as multiparty from 'multiparty';
50 import * as request_lib from 'request';
51
52 const REST_BLUEPRINT_CONTROLLER_BASE_URL = process.env.REST_BLUEPRINT_CONTROLLER_BASE_URL || "http://localhost:8080/api/v1";
53 const REST_BLUEPRINT_CONTROLLER_BASIC_AUTH_HEADER = process.env.REST_BLUEPRINT_CONTROLLER_BASIC_AUTH_HEADER || "Basic Y2NzZGthcHBzOmNjc2RrYXBwcw==";
54 const REST_BLUEPRINT_PROCESSOR_BASE_URL= "http://localhost:8081/api/v1";
55
56 export class BlueprintRestController {
57   constructor(
58   //  @repository(BlueprintRepository)
59   //   public blueprintRepository : BlueprintRepository,
60     @inject('services.BlueprintService') 
61     public bpservice: BlueprintService,
62   ) {}
63
64   @get('/blueprints', {
65     responses: {
66       '200': {
67         description: 'Blueprint model instance',
68         content: { 'application/json': { schema: { 'x-ts-type': Blueprint } } },
69       },
70     },
71   })
72   async getall() {
73     return await this.bpservice.getAllblueprints(REST_BLUEPRINT_CONTROLLER_BASIC_AUTH_HEADER);
74
75   }
76
77   @post('/create-blueprint')
78   async upload(
79     @requestBody({
80       description: 'multipart/form-data value.',
81       required: true,
82       content: {
83         'multipart/form-data': {
84           // Skip body parsing
85           'x-parser': 'stream',
86           schema: {type: 'object'},
87         },
88       },
89     })
90     request: Request,
91     @inject(RestBindings.Http.RESPONSE) response: Response,
92   ): Promise<object> {
93     return new Promise((resolve, reject) => { 
94        this.getFileFromMultiPartForm(request).then(file=>{
95          this.uploadFileToBlueprintController(file, "/blueprint-model/").then(resp=>{
96           response.setHeader("X-ONAP-RequestID", resp.headers['x-onap-requestid']);
97           resolve(JSON.parse(resp.body));
98          }, err=>{
99            reject(err);
100          });
101       }, err=>{
102         reject(err);
103       });
104     });
105   }
106
107   @post('/enrich-blueprint')
108   async enrich(
109     @requestBody({
110       description: 'multipart/form-data value.',
111       required: true,
112       content: {
113         'multipart/form-data': {
114           // Skip body parsing
115           'x-parser': 'stream',
116           schema: {type: 'object'},
117         },
118       },
119     })
120     request: Request,
121     @inject(RestBindings.Http.RESPONSE) response: Response,
122   ): Promise<any> {
123     return new Promise((resolve, reject) => { 
124        this.getFileFromMultiPartForm(request).then(file=>{
125          this.uploadFileToBlueprintController(file, "/blueprint-model/enrich/").then(resp=>{
126            response.setHeader("X-ONAP-RequestID", resp.headers['x-onap-requestid']);
127            response.setHeader("Content-Disposition", resp.headers['content-disposition']);
128            resolve(resp.body);
129          }, err=>{
130            reject(err);
131          });
132       }, err=>{
133         reject(err);
134       });
135     });
136   }
137
138   @get('/download-blueprint/{id}')
139   async download(
140     @param.path.string('id') id: string,
141     @inject(RestBindings.Http.REQUEST) request: Request,
142     @inject(RestBindings.Http.RESPONSE) response: Response,
143   ): Promise<any> {
144     return new Promise((resolve, reject) => { 
145       this.downloadFileFromBlueprintController("/blueprint-model/download/" + id).then(resp=>{
146         response.setHeader("X-ONAP-RequestID", resp.headers['x-onap-requestid']);
147         response.setHeader("Content-Disposition", resp.headers['content-disposition']);
148         resolve(resp.body);
149       }, err=>{
150         reject(err);
151       });
152     });
153   }
154
155   async getFileFromMultiPartForm(request: Request): Promise<any>{
156     return new Promise((resolve, reject) => {
157       // let options = {
158       //   uploadDir: MULTIPART_FORM_UPLOAD_DIR
159       // }
160       let form = new multiparty.Form();
161       form.parse(request, (err: any, fields: any, files: { [x: string]: any[]; }) => {
162         if (err) reject(err);
163         let file = files['file'][0]; // get the file from the returned files object
164         if(!file){
165           reject('File was not found in form data.');
166         }else{
167           resolve(file);
168         }
169       });
170     })
171   }
172
173   async uploadFileToBlueprintController(file: any, uri: string): Promise<any>{
174     let options = {
175       url: REST_BLUEPRINT_CONTROLLER_BASE_URL + uri,
176       headers: {
177         Authorization: REST_BLUEPRINT_CONTROLLER_BASIC_AUTH_HEADER,
178         'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
179       },
180       formData: {
181         file: {
182           value: fs.createReadStream(file.path),
183           options: {
184             filename: 'cba.zip',
185             contentType: 'application/zip'
186           }
187         }
188       }
189     };
190
191     return new Promise((resolve, reject) => {
192       request_lib.post(options, (err: any, resp: any, body: any) => {
193         if (err) {
194           //delete tmp file
195           fs.unlink(file.path, (err: any) => {
196             if (err) {
197               console.error(err);
198               return
199             }
200           })
201           reject(err);
202         }else{
203           resolve(resp);
204         }
205       })
206     })
207   }
208
209   async downloadFileFromBlueprintController(uri: string): Promise<any> {
210     let options = {
211       url: REST_BLUEPRINT_CONTROLLER_BASE_URL + uri,
212       headers: {
213         Authorization: REST_BLUEPRINT_CONTROLLER_BASIC_AUTH_HEADER,
214       }
215     };
216
217     return new Promise((resolve, reject) => {
218       request_lib.get(options, (err: any, resp: any, body: any) => {
219         if (err) {
220           reject(err);
221         }else{
222           resolve(resp);
223         }
224       })
225     })
226 }
227 }