summaryrefslogtreecommitdiffstats
path: root/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WidgetsCatalogController.java
blob: 4b68a01ef864639e03cb7c60cbd68a8697704bac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*-
 * ============LICENSE_START==========================================
 * ONAP Portal
 * ===================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 *
 * Unless otherwise specified, all software contained herein is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this software except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Unless otherwise specified, all documentation contained herein is licensed
 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 * you may not use this documentation except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             https://creativecommons.org/licenses/by/4.0/
 *
 * Unless required by applicable law or agreed to in writing, documentation
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ============LICENSE_END============================================
 *
 *
 */
package org.onap.portalapp.portal.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.onap.portalapp.controller.EPRestrictedBaseController;
import org.onap.portalapp.portal.domain.EPUser;
import org.onap.portalapp.portal.domain.MicroserviceParameter;
import org.onap.portalapp.portal.domain.WidgetCatalog;
import org.onap.portalapp.portal.domain.WidgetCatalogParameter;
import org.onap.portalapp.portal.domain.WidgetParameterResult;
import org.onap.portalapp.portal.domain.WidgetServiceHeaders;
import org.onap.portalapp.portal.ecomp.model.PortalRestResponse;
import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum;
import org.onap.portalapp.portal.logging.aop.EPAuditLog;
import org.onap.portalapp.portal.service.WidgetMService;
import org.onap.portalapp.portal.service.MicroserviceService;
import org.onap.portalapp.portal.service.WidgetParameterService;
import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalapp.util.EPUserUtils;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.util.SystemProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@SuppressWarnings("unchecked")
@RestController
@org.springframework.context.annotation.Configuration
@EnableAspectJAutoProxy
@EPAuditLog
public class WidgetsCatalogController extends EPRestrictedBaseController {

	private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogController.class);

	private static final String MS_WIDGET_LOCAL_PORT = "microservices.widget.local.port";

	private static final String UNAUTHORIZED_OR_FORBIDDEN_FOR_A_DISABLED_USER = "Unauthorized or  Forbidden for a disabled user";

    private static final String MS_WIDGET_CATALOG_URL = "/widget/microservices/widgetCatalog/";

    private static final String MS_WIDGET_URL = "/widget/microservices/";

	private RestTemplate template = new RestTemplate();

	private String whatService = "widgets-service";

	@Autowired
	private WidgetMService widgetMService;

	@Autowired
	private MicroserviceService microserviceService;

	@Autowired
	private WidgetParameterService widgetParameterService;

	@Bean
	public CommonsMultipartResolver multipartResolver() {
		return new CommonsMultipartResolver();
	}

	static {
		// for localhost testing only
		javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
			public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
				if ("localhost".equals(hostname))
					return true;
				return false;
			}
		});
	}

	@GetMapping(value = { "/portalApi/microservices/widgetCatalog/{loginName}" })
	public List<WidgetCatalog> getUserWidgetCatalog(@PathVariable("loginName") String loginName) {
		List<WidgetCatalog> widgets = new ArrayList<>();
		try {
			ResponseEntity<List> ans = template.exchange(
					EcompPortalUtils.widgetMsProtocol() + "://"
							+ widgetMService.getServiceLocation(whatService,
									SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
                            + MS_WIDGET_CATALOG_URL + loginName,
					HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), List.class);
			widgets = ans.getBody();
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getUserWidgetCatalog failed", e);
			// returning null because null help check on the UI if there was a
			// communication problem with Microservice.
			return null;
		}
		return widgets;
	}

	@GetMapping(value = { "/portalApi/microservices/widgetCatalog" })
	public List<WidgetCatalog> getWidgetCatalog() {
		List<WidgetCatalog> widgets = new ArrayList<>();
		try {
			ResponseEntity<List> ans = template.exchange(
					EcompPortalUtils.widgetMsProtocol() + "://"
							+ widgetMService.getServiceLocation(whatService,
									SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
							+ "/widget/microservices/widgetCatalog",
					HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), List.class);
			widgets = ans.getBody();
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getWidgetCatalog failed", e);
			// returning null because null help check on the UI if there was a
			// communication problem with Microservice.
			return null;
		}
		return widgets;
	}

	@PutMapping(value = {
			"/portalApi/microservices/widgetCatalog/{widgetId}" }, produces = "application/json")
	public void updateWidgetCatalog(@RequestBody WidgetCatalog newWidgetCatalog, @PathVariable("widgetId") long widgetId) throws Exception {
		template.exchange(
				EcompPortalUtils.widgetMsProtocol() + "://"
						+ widgetMService.getServiceLocation(whatService,
								SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
                        + MS_WIDGET_CATALOG_URL + widgetId,
				HttpMethod.PUT, new HttpEntity<>(newWidgetCatalog, WidgetServiceHeaders.getInstance()), String.class);
	}

	@DeleteMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" })
	public void deleteOnboardingWidget(@PathVariable("widgetId") long widgetId) throws Exception {
		template.exchange(
				EcompPortalUtils.widgetMsProtocol() + "://"
						+ widgetMService.getServiceLocation(whatService,
								SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
                        + MS_WIDGET_CATALOG_URL + widgetId,
				HttpMethod.DELETE, new HttpEntity<>(WidgetServiceHeaders.getInstance()), String.class);
	}

	@PostMapping(value = { "/portalApi/microservices/widgetCatalog/{widgetId}" })
	public String updateWidgetCatalogWithFiles(HttpServletRequest request,
			@PathVariable("widgetId") long widgetId) throws RestClientException, Exception {
		MultipartHttpServletRequest mRequest;
		MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
		String fileName;
		String tmpFolderName = "/tmp/";
		String respond = null;
        try {
            mRequest = (MultipartHttpServletRequest) request;
            MultipartFile mFile = mRequest.getFile("file");
            fileName = mFile.getOriginalFilename();
            try (FileOutputStream fo = new FileOutputStream(tmpFolderName + fileName)) {
                fo.write(mFile.getBytes());
            }

			HttpHeaders header = new HttpHeaders();
			header.setContentType(MediaType.MULTIPART_FORM_DATA);
			multipartRequest.add("file", new FileSystemResource(tmpFolderName + fileName));
			multipartRequest.add("widget", request.getParameter("newWidget"));
			respond = template.postForObject(
					EcompPortalUtils.widgetMsProtocol() + "://"
							+ widgetMService.getServiceLocation(whatService,
									SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
                            + MS_WIDGET_CATALOG_URL + widgetId,
					new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
			File f = new File(tmpFolderName + fileName);
			f.delete();
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "updateWidgetCatalogWithFiles failed", e);
        }
		return respond;
	}

	@PostMapping(value = { "/portalApi/microservices/widgetCatalog" })
	public String createWidgetCatalog(HttpServletRequest request)
			throws Exception {

		if (StringUtils.isNotBlank(SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG))
                && "false".equalsIgnoreCase(
                        SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG))) {
			return UNAUTHORIZED_OR_FORBIDDEN_FOR_A_DISABLED_USER;
		}

		MultipartHttpServletRequest mRequest;
		MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
		String fileName;
		String tmpFolderName = "/tmp/";
		String respond = null;
		try {
			mRequest = (MultipartHttpServletRequest) request;
			MultipartFile mFile = mRequest.getFile("file");
			fileName = mFile.getOriginalFilename();
            try (FileOutputStream fo = new FileOutputStream(tmpFolderName + fileName)) {
                fo.write(mFile.getBytes());
            }

			HttpHeaders header = new HttpHeaders();
			header.setContentType(MediaType.MULTIPART_FORM_DATA);
			multipartRequest.add("file", new FileSystemResource(tmpFolderName + fileName));
			multipartRequest.add("widget", request.getParameter("newWidget"));

			respond = template.postForObject(
					EcompPortalUtils.widgetMsProtocol() + "://"
							+ widgetMService.getServiceLocation(whatService,
									SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
							+ "/widget/microservices/widgetCatalog",
					new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class);
			File f = new File(tmpFolderName + fileName);
			f.delete();
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "createWidgetCatalog failed", e);
		}
		return respond;
	}

	@GetMapping(value = "/portalApi/microservices/{widgetId}/framework.js")
	public String getWidgetFramework(@PathVariable("widgetId") long widgetId) throws Exception {
		return template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://"
				+ widgetMService.getServiceLocation(whatService,
						SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
                + MS_WIDGET_URL + widgetId + "/framework.js", String.class,
				WidgetServiceHeaders.getInstance());
	}

	@GetMapping(value = "/portalApi/microservices/{widgetId}/controller.js")
	public String getWidgetController(@PathVariable("widgetId") long widgetId) throws Exception {
		return template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://"
				+ widgetMService.getServiceLocation(whatService,
						SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
                + MS_WIDGET_URL + widgetId + "/controller.js", String.class,
				WidgetServiceHeaders.getInstance());
	}

	@GetMapping(value = "/portalApi/microservices/{widgetId}/style.css")
	public String getWidgetCSS(@PathVariable("widgetId") long widgetId) throws Exception {
		return template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://"
				+ widgetMService.getServiceLocation(whatService,
						SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT))
                + MS_WIDGET_URL + widgetId + "/styles.css", String.class,
				WidgetServiceHeaders.getInstance());
	}

	@GetMapping(value = { "/portalApi/microservices/parameters/{widgetId}" })
	public PortalRestResponse<List<WidgetParameterResult>> getWidgetParameterResult(HttpServletRequest request,
			@PathVariable("widgetId") long widgetId) throws Exception {
		EPUser user = EPUserUtils.getUserSession(request);

		List<WidgetParameterResult> list = new ArrayList<>();
		Long serviceId = template.exchange(
				EcompPortalUtils.widgetMsProtocol() + "://"
						+ widgetMService.getServiceLocation(whatService,
								SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
						+ "/widget/microservices/widgetCatalog/parameters/" + widgetId,
				HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), Long.class).getBody();
		if (serviceId == null) {
			// return ok/sucess and no service parameter for this widget
            return new PortalRestResponse<>(PortalRestStatusEnum.WARN,
					"No service parameters for this widget", list);
		} else {
			List<MicroserviceParameter> defaultParam = microserviceService.getParametersById(serviceId);
			for (MicroserviceParameter param : defaultParam) {
				WidgetParameterResult userResult = new WidgetParameterResult();
				userResult.setParam_id(param.getId());
				userResult.setDefault_value(param.getPara_value());
				userResult.setParam_key(param.getPara_key());
				WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
						param.getId());
				if (userValue == null)
					userResult.setUser_value(param.getPara_value());
				else {
					userResult.setUser_value(userValue.getUser_value());
				}
				list.add(userResult);
			}
		}
        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", list);
	}

	@GetMapping(value = { "/portalApi/microservices/services/{paramId}" })
	public List<WidgetCatalogParameter> getUserParameterById(	@PathVariable("paramId") long paramId) {
        return widgetParameterService.getUserParameterById(paramId);
	}

	@DeleteMapping(value = { "/portalApi/microservices/services/{paramId}" })
	public void deleteUserParameterById(@PathVariable("paramId") long paramId) {
		widgetParameterService.deleteUserParameterById(paramId);
	}

	@GetMapping(value = { "/portalApi/microservices/download/{widgetId}" })
	public void doDownload(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("widgetId") long widgetId) throws Exception {

		ServletContext context = request.getServletContext();
		byte[] byteFile = template
				.exchange(
						EcompPortalUtils.widgetMsProtocol() + "://"
								+ widgetMService.getServiceLocation(whatService,
										SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT))
								+ "/widget/microservices/download/" + widgetId,
						HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), byte[].class)
				.getBody();

		File downloadFile = File.createTempFile("temp", ".zip");
		try(FileOutputStream stream = new FileOutputStream(downloadFile.getPath())){
			stream.write(byteFile);
		}catch(Exception e)
		{
			logger.error(EELFLoggerDelegate.errorLogger, "doDownload failed", e);
			throw e;
		}

		try(FileInputStream inputStream = new FileInputStream(downloadFile);
			OutputStream outStream = response.getOutputStream()){
			String mimeType = context.getMimeType(downloadFile.getPath());
			if (mimeType == null) {
				mimeType = "application/octet-stream";
			}

			response.setContentType(mimeType);
			response.setContentLength((int) downloadFile.length());
			String headerKey = "Content-Disposition";
			String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
			downloadFile.delete();
			response.setHeader(headerKey, headerValue);

			byte[] buffer = new byte[32 * 1024];
			int bytesRead;
			while ((bytesRead = inputStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, bytesRead);
			}
		}catch(Exception e)
		{
			logger.error(EELFLoggerDelegate.errorLogger, "doDownload failed", e);
			throw e;
		}
	}

	@PostMapping(value = { "/portalApi/microservices/parameters" })
	public PortalRestResponse<String> saveWidgetParameter(HttpServletRequest request,
			@RequestBody WidgetCatalogParameter widgetParameters) {
		EPUser user = EPUserUtils.getUserSession(request);
		widgetParameters.setUserId(user.getId());
		try {
			WidgetCatalogParameter oldParam = widgetParameterService.getUserParamById(widgetParameters.getWidgetId(),
					widgetParameters.getUserId(), widgetParameters.getParamId());
			if (oldParam != null) {
				widgetParameters.setId(oldParam.getId());
			}
			widgetParameterService.saveUserParameter(widgetParameters);

		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetParameter failed", e);
			return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
		}
		return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", "");
	}

	@GetMapping(value = { "/portalApi/microservices/uploadFlag" })
	public String getUploadFlag() {
	     String uplaodFlag="";
		try {
			uplaodFlag = SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG);
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "uploadFlag failed", e);
			return null;
		}
		return uplaodFlag;
	}
}