summaryrefslogtreecommitdiffstats
path: root/ecomp-portal-widget-ms/widget-ms/src/main/java/org/onap/portalapp/widget/service/impl/StorageServiceImpl.java
blob: 7a35ba4efb4b35584ce8bbb737549950d09ca377 (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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package org.onap.portalapp.widget.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.onap.portalapp.widget.constant.WidgetConstant;
import org.onap.portalapp.widget.domain.ValidationRespond;
import org.onap.portalapp.widget.domain.WidgetCatalog;
import org.onap.portalapp.widget.domain.WidgetFile;
import org.onap.portalapp.widget.excetpion.StorageException;
import org.onap.portalapp.widget.service.StorageService;
import org.onap.portalapp.widget.service.WidgetCatalogService;
import org.onap.portalapp.widget.utils.UnzipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Service
public class StorageServiceImpl implements StorageService {

	private static final Logger logger = LoggerFactory.getLogger(StorageServiceImpl.class);
	private final String TMP_PATH = "/tmp/";

	@Autowired
	private SessionFactory sessionFactory;

	@Autowired
	WidgetCatalogService widgetCatalogService;

	@Override
	@Transactional
	public void deleteWidgetFile(long widgetId) {
		WidgetFile widgetFile = getWidgetFile(widgetId);
		logger.debug("StorageServiceImpl.deleteWidgetFile: deleting widget file {}", widgetId);
		if (widgetFile == null) {
			logger.debug(
					"StorageServiceImpl.deleteWidgetFile: No widget file found in database while performing StorageServiceImpl.deleteWidgetFile.");
			return;
		}
		Session session = sessionFactory.getCurrentSession();
		Transaction tx = session.beginTransaction();
		session.delete(widgetFile);
		tx.commit();
	}

	@Override
	@SuppressWarnings("unchecked")
	@Transactional
	public WidgetFile getWidgetFile(long widgetId) {
		logger.debug("StorageServiceImpl.getWidgetFile: getting widget file {}", widgetId);
		WidgetFile widgetFile = null;
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(WidgetFile.class);
		criteria.add(Restrictions.eq("widgetId", widgetId));
		List<WidgetFile> widgetFiles = criteria.list();
		session.flush();
		session.close();
		if (widgetFiles.size() > 0)
			widgetFile = widgetFiles.get(0);
		return widgetFile;
	}

	@Override
	public ValidationRespond checkZipFile(MultipartFile file) {
		StringBuilder error_msg = new StringBuilder();
		UnzipUtil unzipper = new UnzipUtil();
		Map<String, byte[]> map;
		File convFile;
		boolean isValid = true;
		if (!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.')).equals(".zip")) {
			isValid = false;
			error_msg.append(WidgetConstant.VALIDATION_MESSAGE_ZIP);
			logger.error("StorageServiceImpl.checkZipFile: invalid file format");
		}
		try {
			if (file.isEmpty()) {
				logger.error(
						"StorageServiceImpl.checkZipFile: Failed to store empty file " + file.getOriginalFilename());
				throw new StorageException(
						"StorageServiceImpl.checkZipFile: Failed to store empty file " + file.getOriginalFilename());
			}

			String fileLocation = TMP_PATH+file.getOriginalFilename();
			logger.debug("StorageServiceImpl.checkZipFile: store the widget to:" + fileLocation);
			convFile = new File(fileLocation);
			try(FileOutputStream fos = new FileOutputStream(convFile)){
				fos.write(file.getBytes());
			}
			map = unzipper.unzip_db(fileLocation, TMP_PATH, "tempWidgets");
			convFile.delete();
		} catch (IOException e) {
			logger.error("StorageServiceImpl.checkZipFile: Failed to store file " + file.getOriginalFilename(), e);
			throw new StorageException(
					"torageServiceImpl.checkZipFile: Failed to store file " + file.getOriginalFilename(), e);
		}

		for (byte[] b : map.values()) {
			if (isValid && b == null) {
				isValid = false;
				error_msg.append(WidgetConstant.VALIDATION_MESSAGE_FILES);
				break;
			}
		}
		return new ValidationRespond(isValid, error_msg.toString());
	}

	@Override
	@Transactional
	public void save(MultipartFile file, WidgetCatalog newWidget, long widgetId) {

		UnzipUtil unzipper = new UnzipUtil();
		Map<String, byte[]> map;
		File convFile;
		try {
			if (file.isEmpty()) {
				logger.error("Failed to store empty file " + file.getOriginalFilename());
				throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
			}
			String fileLocation = file.getOriginalFilename();
			logger.debug("StorageServiceImpl.save: store the widget to:" + fileLocation);
			convFile = new File(fileLocation);
			try(FileOutputStream fos = new FileOutputStream(convFile)){
				fos.write(file.getBytes());
			}
			map = unzipper.unzip_db(fileLocation, ".", "tempWidgets");
			convFile.delete();
		} catch (IOException e) {
			logger.error("StorageServiceImpl.save: Failed to store file " + file.getOriginalFilename(), e);
			throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
		}
		saveHelper(newWidget, widgetId, map);
	}

	@Override
	@Transactional
	public void initSave(File file, WidgetCatalog newWidget, long widgetId) {

		UnzipUtil unzipper = new UnzipUtil();
		Map<String, byte[]> map;

		try {
			String fileLocation = file.getPath();
			logger.debug("StorageServiceImpl.save: store the widget to:" + fileLocation);
			map = unzipper.unzip_db(fileLocation, ".", "tempWidgets");
		} catch (IOException e) {
			logger.error("StorageServiceImpl.save: Failed to store file " + file.getName(), e);
			throw new StorageException("Failed to store file " + file.getName(), e);
		}
		
		saveHelper(newWidget, widgetId, map);
	}

	/**
	 * Helper method for saving widget files (controller.js, framework.js,
	 * markup.html and style.css) to ep_widget_catalog_files table in database
	 * 
	 * @param newWidget
	 * @param widgetId
	 * @param map
	 */
	private void saveHelper(WidgetCatalog newWidget, long widgetId, Map<String, byte[]> map) {

		logger.debug("Going to save widget " + newWidget);
		WidgetFile widgetFile = new WidgetFile();
		widgetFile.setName(newWidget.getName());
		widgetFile.setWidgetId(widgetId);

		

		String sb = null;
		try(InputStream fileInputStream = this.getClass().getClassLoader().getResourceAsStream("framework-template.js")) {
			byte[] bytes = new byte[fileInputStream.available()];
			if(fileInputStream.read(bytes) > 0) {
				sb = new String(bytes, "UTF-8");
			}
		} catch (IOException e) {
			logger.error("StorageServiceImpl.save: Failed to load framework-template.js file ", e);
		}

		String namespace = "Portal" + widgetId + "Widget";
		String controllerName = "Portal" + widgetId + "Ctrl";
		String cssName = "portal" + widgetId + "-css-ready";
		String colorArg1 = "color: #fff";
		String framework="";
		if(sb!=null) {
			framework = sb.replaceAll("ARGUMENT1", namespace).replaceAll("ARGUMENT2", controllerName)
					.replaceAll("ARGUMENT3", cssName).replaceAll("CSS_ARG1", colorArg1)
					.replaceAll("MICROSERVICE_ID", newWidget.getServiceId().toString())
					.replaceAll("WIDGET_ID", Long.toString(widgetId));
		}
		widgetFile.setFramework(framework.getBytes());

		final byte[] controllerLoc = map.get(WidgetConstant.WIDGET_CONTROLLER_LOCATION);
		if (controllerLoc == null || controllerLoc.length == 0)
			throw new IllegalArgumentException(
					"Map is missing required key " + WidgetConstant.WIDGET_CONTROLLER_LOCATION);
		String javascript = new String(controllerLoc);
		String functionHeader = javascript.substring(javascript.indexOf("function"), javascript.indexOf(")") + 1);
		String functionName = functionHeader.substring(functionHeader.indexOf(" "), functionHeader.indexOf("(")).trim();
		javascript = javascript.replaceFirst(functionName, controllerName);
		String functionParam = functionHeader.substring(functionHeader.indexOf("(") + 1, functionHeader.indexOf(")"));
		List<String> paramList = Arrays.asList(functionParam.split(","));

		int left_bracket_index = javascript.indexOf("{") + 1;
		String widgetData = namespace + "=" + namespace + "||{};" + "var res = " + namespace + ".widgetData;";
		javascript = javascript.substring(0, left_bracket_index) + widgetData
				+ javascript.substring(left_bracket_index);

		StringBuilder injectStr = new StringBuilder().append("[");
		for (int i = 0; i < paramList.size(); i++) {
			if (i == paramList.size() - 1)
				injectStr.append("'" + paramList.get(i).trim() + "'];");
			else
				injectStr.append("'" + paramList.get(i).trim() + "',");
		}
		javascript = namespace + ".controller = " + javascript + ";" + namespace + ".controller.$inject = "
				+ injectStr.toString();

		String html = new String(map.get(WidgetConstant.WIDGET_MARKUP_LOCATION)).replaceFirst(functionName,
				controllerName);
		;

		Pattern cssPattern = Pattern.compile("#.*-css-ready");
		Matcher cssMatcher = cssPattern.matcher(new String(map.get(WidgetConstant.WIDGET_STYLE_LOCATION)));
		if (cssMatcher.find()) {
			widgetFile.setCss(new String(map.get(WidgetConstant.WIDGET_STYLE_LOCATION))
					.replace(cssMatcher.group(0), "#" + cssName).getBytes());
		}

		widgetFile.setMarkup(html.getBytes());
		widgetFile.setController(javascript.getBytes());
		Session session = sessionFactory.openSession();
		session.save(widgetFile);
		session.flush();
		session.close();
		// sessionFactory.getCurrentSession().save(widgetFile);
		logger.debug(
				"StorageServiceImpl.save: saved fraemwork.js controller.js, markup.html and style.css files to the database for widget {}",
				widgetId);

	}

	@Override
	public void update(MultipartFile file, WidgetCatalog newWidget, long widgetId) {
		UnzipUtil unzipper = new UnzipUtil();
		Map<String, byte[]> map;
		File convFile;
		try {
			if (file.isEmpty()) {
				logger.error("StorageServiceImpl.update: Failed to store empty file " + file.getOriginalFilename());
				throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
			}
			String fileLocation = file.getOriginalFilename();
			logger.debug("StorageServiceImpl.update: store the widget to:" + fileLocation);
			convFile = new File(fileLocation);
			try(FileOutputStream fos = new FileOutputStream(convFile)){
				fos.write(file.getBytes());
			}
			map = unzipper.unzip_db(fileLocation, ".", "tempWidgets");
			convFile.delete();
		} catch (IOException e) {
			logger.error("StorageServiceImpl.update: Failed to store file " + file.getOriginalFilename(), e);
			throw new StorageException("StorageServiceImpl.update: Failed to store file " + file.getOriginalFilename(),
					e);
		}
		WidgetFile widgetFile = getWidgetFile(widgetId);

		String sb = null;
		try(InputStream fileInputStream = this.getClass().getClassLoader().getResourceAsStream("framework-template.js")){
			byte[] bytes = new byte[fileInputStream.available()];
			if(fileInputStream.read(bytes) > 0) {
				sb = new String(bytes, "UTF-8");
			}
		} catch (IOException e) {
			logger.error("StorageServiceImpl.save: Failed to load framework-template.js file ", e);
		}

		String namespace = "Portal" + widgetId + "Widget";
		String controllerName = "Portal" + widgetId + "Ctrl";
		String cssName = "portal" + widgetId + "-css-ready";
		String colorArg1 = "color: #fff";
		String framework="";
		if(sb!=null) {
			framework = sb.replaceAll("ARGUMENT1", namespace).replaceAll("ARGUMENT2", controllerName)
					.replaceAll("ARGUMENT3", cssName).replaceAll("CSS_ARG1", colorArg1)
					.replaceAll("MICROSERVICE_ID", newWidget.getServiceId().toString())
					.replaceAll("WIDGET_ID", Long.toString(widgetId));
		}
		widgetFile.setFramework(framework.getBytes());

		String javascript = new String(map.get(WidgetConstant.WIDGET_CONTROLLER_LOCATION));
		String functionHeader = javascript.substring(javascript.indexOf("function"), javascript.indexOf(")") + 1);
		String functionName = functionHeader.substring(functionHeader.indexOf(" "), functionHeader.indexOf("(")).trim();
		javascript = javascript.replaceFirst(functionName, controllerName);
		String functionParam = functionHeader.substring(functionHeader.indexOf("(") + 1, functionHeader.indexOf(")"));
		List<String> paramList = Arrays.asList(functionParam.split(","));

		int left_bracket_index = javascript.indexOf("{") + 1;
		String widgetData = namespace + "=" + namespace + "||{};" + "var res = " + namespace + ".widgetData;";
		javascript = javascript.substring(0, left_bracket_index) + widgetData
				+ javascript.substring(left_bracket_index);

		StringBuilder injectStr = new StringBuilder().append("[");
		for (int i = 0; i < paramList.size(); i++) {
			if (i == paramList.size() - 1)
				injectStr.append("'" + paramList.get(i).trim() + "'];");
			else
				injectStr.append("'" + paramList.get(i).trim() + "',");
		}
		javascript = namespace + ".controller = " + javascript + ";" + namespace + ".controller.$inject = "
				+ injectStr.toString();

		String html = new String(map.get(WidgetConstant.WIDGET_MARKUP_LOCATION)).replaceFirst(functionName,
				controllerName);
		;

		Pattern cssPattern = Pattern.compile("#.*-css-ready");
		Matcher cssMatcher = cssPattern.matcher(new String(map.get(WidgetConstant.WIDGET_STYLE_LOCATION)));
		if (cssMatcher.find()) {
			widgetFile.setCss(new String(map.get(WidgetConstant.WIDGET_STYLE_LOCATION))
					.replace(cssMatcher.group(0), "#" + cssName).getBytes());
		}

		widgetFile.setMarkup(html.getBytes());
		widgetFile.setController(javascript.getBytes());
		// widgetFile.setCss(map.get(WidgetConstant.WIDGET_STYLE_LOCATION));
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		session.update(widgetFile);
		tx.commit();
		session.flush();
		session.close();
		logger.debug(
				"StorageServiceImpl.save: updated fraemwork.js controller.js, markup.html and style.css files to the database for widget {}",
				widgetId);
	}

	@Override
	@SuppressWarnings("unchecked")
	@Transactional
	public String getWidgetMarkup(long widgetId) throws UnsupportedEncodingException {
		String markup = null;
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(WidgetFile.class);
		criteria.add(Restrictions.eq("widgetId", widgetId));
		List<WidgetFile> widgetFile = criteria.list();
		logger.debug("StorageServiceImpl.getWidgetMarkup: getting widget markup result={}", widgetFile);

		if (widgetFile.size() > 0)
			markup = new String(widgetFile.get(0).getMarkup(), "UTF-8");
		return markup;
	}

	@Override
	@SuppressWarnings("unchecked")
	@Transactional
	public String getWidgetController(long widgetId) throws UnsupportedEncodingException {
		String controller = null;
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(WidgetFile.class);
		criteria.add(Restrictions.eq("widgetId", widgetId));
		List<WidgetFile> widgetFile = criteria.list();
		logger.debug("StorageServiceImpl.getWidgetController: getting widget controller result={}", widgetFile);

		if (widgetFile.size() > 0)
			controller = new String(widgetFile.get(0).getController(), "UTF-8");
		return controller;
	}

	@Override
	@SuppressWarnings("unchecked")
	@Transactional
	public String getWidgetFramework(long widgetId) throws UnsupportedEncodingException {
		String framework = null;
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(WidgetFile.class);
		criteria.add(Restrictions.eq("widgetId", widgetId));
		List<WidgetFile> widgetFile = criteria.list();
		logger.debug("StorageServiceImpl.getWidgetFramework: getting widget framework result={}", widgetFile);

		if (widgetFile.size() > 0)
			framework = new String(widgetFile.get(0).getFramework(), "UTF-8");
		return framework;
	}

	@Override
	@SuppressWarnings("unchecked")
	@Transactional
	public String getWidgetCSS(long widgetId) throws UnsupportedEncodingException {
		String css = null;
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(WidgetFile.class);
		criteria.add(Restrictions.eq("widgetId", widgetId));
		List<WidgetFile> widgetFile = criteria.list();
		logger.debug("StorageServiceImpl.getWidgetCSS: getting widget css result={}", widgetFile);

		if (widgetFile.size() > 0)
			css = new String(widgetFile.get(0).getCss(), "UTF-8");
		return css;
	}

	@Override
	@Transactional
	public byte[] getWidgetCatalogContent(long widgetId) throws Exception {

		WidgetCatalog widget = widgetCatalogService.getWidgetCatalog(widgetId);
		String namespace = "Portal" + widgetId + "Widget";
		String controllerName = "Portal" + widgetId + "Ctrl";
		String cssName = "portal" + widgetId + "-css-ready";

		String styles = getWidgetCSS(widgetId).replaceAll(cssName, widget.getName() + "-css-ready");
		File f = File.createTempFile("temp", ".zip");
		try(ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f))){
			ZipEntry e = new ZipEntry(widget.getName() + "/styles/styles.css");
			out.putNextEntry(new ZipEntry(widget.getName() + "/"));
			out.putNextEntry(new ZipEntry(widget.getName() + "/styles/"));
			out.putNextEntry(e);
			byte[] data = styles.getBytes();
			out.write(data, 0, data.length);
	
			String widgetData = namespace + "=" + namespace + "||{};" + "var res = " + namespace + ".widgetData;";
			String javascript = getWidgetController(widgetId).replace(widgetData, "").replace(namespace + ".controller =",
					"");
	
			String functionHeader = javascript.substring(javascript.indexOf("function"), javascript.indexOf(")") + 1);
			javascript = javascript.replaceFirst(controllerName, widget.getName() + "Ctrl");
			String functionParam = functionHeader.substring(functionHeader.indexOf("(") + 1, functionHeader.indexOf(")"));
			StringBuilder injectStr = new StringBuilder().append("[");
			List<String> paramList = Arrays.asList(functionParam.split(","));
			for (int i = 0; i < paramList.size(); i++) {
				if (i == paramList.size() - 1)
					injectStr.append("'" + paramList.get(i).trim() + "'];");
				else
					injectStr.append("'" + paramList.get(i).trim() + "',");
			}
			javascript = javascript.replace(";" + namespace + ".controller.$inject = " + injectStr.toString(), "");
	
			e = new ZipEntry(widget.getName() + "/js/controller.js");
			out.putNextEntry(new ZipEntry(widget.getName() + "/js/"));
			out.putNextEntry(e);
			data = javascript.getBytes();
			out.write(data, 0, data.length);
	
			String html = getWidgetMarkup(widgetId).replaceFirst(controllerName, widget.getName() + "Ctrl");
	
			// new
			// String(map.get(WidgetConstant.WIDGET_MARKUP_LOCATION)).replaceFirst(functionName,
			// controllerName);;
	
			e = new ZipEntry(widget.getName() + "/markup/markup.html");
			out.putNextEntry(new ZipEntry(widget.getName() + "/markup/"));
			out.putNextEntry(e);
			data = html.getBytes();
			out.write(data, 0, data.length);
			out.closeEntry();
			byte[] result = Files.readAllBytes(Paths.get(f.getPath()));
			f.delete();
			return result;
		}
	}

}