Subversion Repositories SmartDukaan

Rev

Rev 35523 | Rev 35528 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
25380 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.google.gson.Gson;
30080 amit.gupta 4
import com.jcraft.jsch.*;
25380 amit.gupta 5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
6
import com.spice.profitmandi.common.solr.SolrService;
7
import com.spice.profitmandi.dao.entity.catalog.Item;
33443 ranu 8
import com.spice.profitmandi.dao.entity.cs.PartnerRegion;
9
import com.spice.profitmandi.dao.entity.cs.Region;
28264 tejbeer 10
import com.spice.profitmandi.dao.entity.dtr.DocumentUrl;
33443 ranu 11
import com.spice.profitmandi.dao.entity.fofo.PrintResource;
12
import com.spice.profitmandi.dao.entity.fofo.PrintResourceRegion;
13
import com.spice.profitmandi.dao.entity.user.User;
35487 ranu 14
import com.spice.profitmandi.dao.enumuration.inventory.CatalogMovingEnum;
33443 ranu 15
import com.spice.profitmandi.dao.model.*;
16
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
35487 ranu 17
import com.spice.profitmandi.dao.repository.catalog.CatalogRepository;
31330 tejbeer 18
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
25380 amit.gupta 19
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
33973 tejus.loha 20
import com.spice.profitmandi.dao.repository.catalog.SuperCatalogRepository;
33443 ranu 21
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
22
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
28264 tejbeer 23
import com.spice.profitmandi.dao.repository.dtr.DocumentUrlRepository;
25380 amit.gupta 24
import com.spice.profitmandi.dao.repository.dtr.Mongo;
33443 ranu 25
import com.spice.profitmandi.dao.repository.fofo.PrintResourceRegionRepository;
26
import com.spice.profitmandi.dao.repository.fofo.PrintResourceRepository;
27
import com.spice.profitmandi.dao.repository.user.UserRepository;
32952 amit.gupta 28
import com.spice.profitmandi.service.catalog.ItemLoaderService;
25380 amit.gupta 29
import com.spice.profitmandi.web.model.EntityMediaPojo;
33443 ranu 30
import com.spice.profitmandi.web.model.LoginDetails;
31
import com.spice.profitmandi.web.util.CookiesProcessor;
25380 amit.gupta 32
import com.spice.profitmandi.web.util.MVCResponseSender;
30080 amit.gupta 33
import org.apache.commons.csv.CSVFormat;
34
import org.apache.commons.csv.CSVParser;
35
import org.apache.commons.csv.CSVRecord;
36
import org.apache.commons.lang3.StringUtils;
37
import org.apache.logging.log4j.LogManager;
38
import org.apache.logging.log4j.Logger;
31330 tejbeer 39
import org.json.JSONArray;
40
import org.json.JSONObject;
30080 amit.gupta 41
import org.springframework.beans.factory.annotation.Autowired;
35525 ranu 42
import org.springframework.http.HttpStatus;
35346 ranu 43
import org.springframework.http.ResponseEntity;
30080 amit.gupta 44
import org.springframework.stereotype.Controller;
35487 ranu 45
import org.springframework.transaction.annotation.Transactional;
30080 amit.gupta 46
import org.springframework.ui.Model;
47
import org.springframework.web.bind.annotation.*;
48
import org.springframework.web.multipart.MultipartFile;
25380 amit.gupta 49
 
30080 amit.gupta 50
import javax.servlet.http.HttpServletRequest;
51
import javax.xml.bind.DatatypeConverter;
52
import java.io.*;
53
import java.sql.Timestamp;
54
import java.time.LocalDate;
55
import java.time.LocalDateTime;
56
import java.time.ZoneOffset;
57
import java.util.*;
58
import java.util.stream.Collectors;
59
 
35458 amit 60
@Transactional(rollbackFor = Throwable.class)
25380 amit.gupta 61
@Controller
62
public class ContentController {
63
	@Autowired
64
	MVCResponseSender mvcResponseSender;
65
 
66
	@Autowired
67
	Mongo mongoClient;
68
 
69
	@Autowired
70
	SolrService solrService;
71
 
72
	@Autowired
73
	ItemRepository itemRepository;
74
 
28264 tejbeer 75
	@Autowired
76
	DocumentUrlRepository documentUrlRepository;
77
 
31330 tejbeer 78
	@Autowired
79
	FocusedModelRepository focusedModelRepository;
33443 ranu 80
 
81
	@Autowired
82
	PrintResourceRepository printResourceRepository;
83
	@Autowired
84
	AuthRepository authRepository;
85
	@Autowired
86
	RegionRepository regionRepository;
87
	@Autowired
88
	PrintResourceRegionRepository printResourceRegionRepository;
89
	@Autowired
90
	PartnerRegionRepository partnerRegionRepository;
33973 tejus.loha 91
	@Autowired
92
	SuperCatalogRepository superCatalogRepository;
35487 ranu 93
	@Autowired
94
	CatalogRepository catalogRepository;
33443 ranu 95
 
25380 amit.gupta 96
	private Gson gson = new Gson();
97
 
98
	public static final int Entity_Id = 0;
99
	public static final int Title = 1;
100
	public static final int KeySpec1 = 2;
101
	public static final int KeySpec2 = 3;
102
	public static final int KeySpec3 = 4;
103
	public static final int KeySpec4 = 5;
104
	public static final int Warranty = 6;
105
	public static final int Package_Contents = 7;
28264 tejbeer 106
	private static final String IMAGE_REMOTE_DIR = "/var/www/dtrdashboard/uploads/campaigns/";
107
	private static final String IMAGE_STATIC_SERVER_URL = "https://images.smartdukaan.com/uploads/campaigns";
25380 amit.gupta 108
 
29900 amit.gupta 109
	private static final String REMOTE_DIR = "/var/www/static.saholic.com/images/media/";
31330 tejbeer 110
	// private static final String REMOTE_DIR = "/tmp";
25986 amit.gupta 111
	private static final String STATIC_SERVER_URL = "https://static%d.smartdukaan.com/images/media/";
25380 amit.gupta 112
 
113
	private static final String THUMBNAIL = "thumbnail";
114
	private static final String ICON = "icon";
115
	private static final String DEFAULT = "default";
116
	private static final String NONE = "";
25409 amit.gupta 117
 
25400 amit.gupta 118
	private static final Logger LOGGER = LogManager.getLogger(ContentController.class);
25380 amit.gupta 119
 
120
	private String getFileName(int entityId, String description, String extension) {
121
		List<Item> items = itemRepository.selectAllByCatalogItemId(entityId);
25409 amit.gupta 122
		String imageString = getMediaPrefix(items.get(0).getItemDescriptionNoColor() + " " + description) + "-"
25380 amit.gupta 123
				+ LocalDateTime.now().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30));
25413 amit.gupta 124
		return imageString + "." + extension;
25380 amit.gupta 125
	}
126
 
35525 ranu 127
/*	@PostMapping(value = "/content/upload")
128
	public String uploadContent(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model)
129
			throws Exception {
130
		List<ContentPojo> contentPojos = readFile(file);
131
		for (ContentPojo contentPojo : contentPojos) {
132
			mongoClient.persistEntity(contentPojo);
133
		}
134
		//List<SuperCatalog> superCatalog = superCatalogRepository.selectAll();
135
 
136
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
137
		return "response";
138
	}*/
139
 
25380 amit.gupta 140
	@PostMapping(value = "/content/upload")
35525 ranu 141
	public ResponseEntity<?> uploadContent(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model)
142
			throws Exception {
143
 
35523 ranu 144
		try {
145
			List<ContentPojo> contentPojos = readFile(file);
146
 
147
			for (ContentPojo contentPojo : contentPojos) {
148
				mongoClient.persistEntity(contentPojo);
149
			}
150
 
35525 ranu 151
			return ResponseEntity.ok(
152
					mvcResponseSender.createResponseString(true)
153
			);
35523 ranu 154
 
155
		} catch (Exception e) {
35525 ranu 156
			e.printStackTrace();
157
			return ResponseEntity
158
					.status(HttpStatus.INTERNAL_SERVER_ERROR)
159
					.body(mvcResponseSender.createResponseString(false));
25380 amit.gupta 160
		}
161
	}
162
 
35525 ranu 163
 
32952 amit.gupta 164
	@Autowired
165
	ItemLoaderService itemLoaderService;
166
	@PostMapping(value = "/catalog/upload")
167
	public String uploadCatalog(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model)
168
			throws Exception {
169
		itemLoaderService.parse(file);
170
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
171
		return "response";
172
	}
173
 
25380 amit.gupta 174
	@PostMapping(value = "/content/media/upload")
175
	public String uploadMediaContent(HttpServletRequest request, @RequestBody EntityMediaPojo entityMediaPojo,
176
			Model model) throws Exception {
177
		ContentPojo contentPojo = mongoClient.getEntityById(entityMediaPojo.getEntityId());
178
		Map<String, InputStream> fileStreamsMap = getStreamFileMap(contentPojo, entityMediaPojo);
25400 amit.gupta 179
		LOGGER.info("fileStreamsMap {}, " + fileStreamsMap.keySet());
29900 amit.gupta 180
		uploadContentFiles(fileStreamsMap, entityMediaPojo.getEntityId());
25380 amit.gupta 181
		mongoClient.persistEntity(contentPojo);
31238 amit.gupta 182
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
25380 amit.gupta 183
		return "response";
184
	}
185
 
35346 ranu 186
	@PostMapping(value = "/content/video/upload")
187
	public String uploadVideoUrls(HttpServletRequest request,
188
								  @RequestPart("file") MultipartFile file,
189
								  Model model) throws Exception {
190
 
191
		List<VideoUrlPojo> videoRows = readVideoFile(file);
192
 
193
		LOGGER.info("Received {} video rows", videoRows.size());
194
 
195
		// group by catalogId
196
		Map<Integer, List<VideoUrlPojo>> videoCatalogMap =
197
				videoRows.stream().collect(Collectors.groupingBy(VideoUrlPojo::getCatalogId));
198
 
35348 ranu 199
		LOGGER.info("videoCatalogMap {}", videoCatalogMap);
200
 
35346 ranu 201
		for (Map.Entry<Integer, List<VideoUrlPojo>> entry : videoCatalogMap.entrySet()) {
202
 
203
			int catalogId = entry.getKey();
35348 ranu 204
 
205
			LOGGER.info("catalogId {}", catalogId);
206
 
35346 ranu 207
			List<VideoUrlPojo> rowsForCatalog = entry.getValue();
208
 
209
			ContentPojo content = mongoClient.getEntityById(catalogId);
210
 
211
			if (content == null) {
212
				LOGGER.warn("No content found for catalogId {}", catalogId);
213
				continue;
214
			}
215
 
216
			updateVideoUrls(content, rowsForCatalog);
217
 
218
			mongoClient.persistEntity(content);
219
 
220
			LOGGER.info("Updated video URLs for catalogId {}", catalogId);
221
		}
222
 
223
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
224
		return "response";
225
	}
226
 
227
 
228
	private void updateVideoUrls(ContentPojo content, List<VideoUrlPojo> rows) {
229
 
230
		if (content.getVideoUrls() == null) {
231
			content.setVideoUrls(new ArrayList<>());
232
		}
233
 
234
		List<VideoUrlsContentPojo> existing = content.getVideoUrls();
235
 
236
		for (VideoUrlPojo row : rows) {
237
			VideoUrlsContentPojo newUrl = new VideoUrlsContentPojo(row.getUrl());
238
 
239
			// add only if not duplicate
240
			if (!existing.contains(newUrl)) {
241
				existing.add(newUrl);
242
			}
243
		}
244
 
245
		content.setVideoUrls(existing);
246
 
247
		LOGGER.info("Final video list = {}", existing);
248
	}
249
 
250
 
251
 
252
 
28264 tejbeer 253
	@PostMapping(value = "/image/media/upload")
254
	public String uploadImageMediaContent(HttpServletRequest request, @RequestBody MediaPojo mediaPojo, Model model)
255
			throws Exception {
256
 
257
		LOGGER.info("mediaPojo" + mediaPojo);
258
		Map<String, InputStream> fileStreamsMap = new HashMap<>();
259
		String extension;
260
		String base64String = mediaPojo.getImageData();
261
		String[] strings = base64String.split(",");
262
		switch (strings[0]) {// check image's extension
263
		case "data:image/jpeg;base64":
264
			extension = "jpeg";
265
			break;
266
		case "data:image/png;base64":
267
			extension = "png";
268
			break;
32304 amit.gupta 269
			case "data:image/webp;base64":
32305 amit.gupta 270
				extension = "webp";
32304 amit.gupta 271
				break;
28264 tejbeer 272
		default:// should write cases for more images types
32304 amit.gupta 273
			extension = "jpg";
28264 tejbeer 274
			break;
275
		}
276
		LOGGER.info("After switch statement = {}", extension);
277
		// convert base64 string to binary data
278
		byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
279
		Timestamp tm = new Timestamp(System.currentTimeMillis());
28320 tejbeer 280
		String urlTitle = mediaPojo.getTitle().toLowerCase();
281
		String fileName = urlTitle.replace(' ', '-') + tm.getTime() + "." + extension;
28264 tejbeer 282
		LOGGER.info("After switch statement Filename = {}", fileName);
283
		mediaPojo.setImageData(null);
284
		mediaPojo.setUrl(IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName);
285
		fileStreamsMap.put(fileName, new ByteArrayInputStream(data));
286
		LOGGER.info("fileStreamsMap" + fileStreamsMap);
287
 
288
		uploadFile(fileStreamsMap);
289
 
290
		DocumentUrl du = new DocumentUrl();
291
		du.setTitle(mediaPojo.getTitle());
292
		du.setUrl(mediaPojo.getUrl());
293
		du.setCreatedTimestamp(LocalDateTime.now());
294
		documentUrlRepository.persist(du);
295
 
296
		model.addAttribute("documents", du);
297
		return "image-url";
298
	}
299
 
300
	private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
301
			throws SftpException, FileNotFoundException {
302
 
303
		channelSftp.cd(destinationPath);
304
		String folderName = "image" + LocalDate.now();
305
 
306
		channelSftp.cd(destinationPath);
307
		SftpATTRS attrs = null;
308
 
309
		// check if the directory is already existing
310
		try {
311
			attrs = channelSftp.stat(folderName);
312
		} catch (Exception e) {
313
			System.out.println(destinationPath + "/" + "image" + LocalDate.now() + " not found");
314
		}
315
 
316
		// else create a directory
317
		if (attrs == null) {
318
			channelSftp.mkdir(folderName);
319
			channelSftp.chmod(0755, ".");
320
		}
321
		channelSftp.cd(folderName);
322
 
323
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
324
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
325
		}
326
 
327
	}
328
 
329
	@GetMapping(value = "/search/image/media")
330
	public String getImage(HttpServletRequest request, Model model, @RequestParam String title) throws Exception {
331
		List<DocumentUrl> documents = documentUrlRepository.selectBySearch(title);
332
 
333
		model.addAttribute("documents", documents);
334
		return "image-url";
335
 
336
	}
337
 
25380 amit.gupta 338
	@GetMapping(value = "/content/media")
339
	public String getMediaContent(HttpServletRequest request, Model model, @RequestParam int entityId)
340
			throws Exception {
341
		ContentPojo contentPojo = mongoClient.getEntityById(entityId);
25409 amit.gupta 342
		if (contentPojo == null) {
25380 amit.gupta 343
			throw new Exception("Please add content first");
344
		}
345
		EntityMediaPojo empojo = getEntityMediaPojo(contentPojo);
31238 amit.gupta 346
		model.addAttribute("response1", mvcResponseSender.createResponseString(empojo));
25380 amit.gupta 347
		return "response";
348
	}
28264 tejbeer 349
 
27185 amit.gupta 350
	@GetMapping(value = "/catalog-item")
28264 tejbeer 351
	public String catalogItem(HttpServletRequest request, Model model) throws Exception {
27185 amit.gupta 352
		return "catalog-item";
353
	}
25380 amit.gupta 354
 
355
	private EntityMediaPojo getEntityMediaPojo(ContentPojo contentPojo) {
356
		EntityMediaPojo ep = new EntityMediaPojo();
357
		int defaultIndex = 0;
25409 amit.gupta 358
		if (contentPojo.getImages() == null) {
25380 amit.gupta 359
			ep.setMediaPojos(new ArrayList<>());
360
		} else {
361
			ep.setMediaPojos(contentPojo.getImages());
362
			for (MediaPojo mediaPojo : contentPojo.getImages()) {
25409 amit.gupta 363
				if (mediaPojo.getUrl() == null)
364
					continue;
365
 
25380 amit.gupta 366
				if (!mediaPojo.getUrl().equals(contentPojo.getDefaultImageUrl())) {
367
					defaultIndex++;
368
				}
369
			}
370
		}
371
		ep.setDefaultImageIndex(defaultIndex);
372
		return ep;
373
	}
374
 
375
	@GetMapping(value = "/entity")
28264 tejbeer 376
	public String searchEntity(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
31330 tejbeer 377
			@RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
378
			@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
379
			Model model) throws Exception {
380
		model.addAttribute("response1", solrService.getContent(query, categoryId > 0 ? Arrays.asList(categoryId) : null,
31711 amit.gupta 381
				brands, limit, false));
25380 amit.gupta 382
		return "response";
383
	}
384
 
31330 tejbeer 385
	@GetMapping(value = "/focusedEntity")
386
	public String focusedEntity(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
387
			@RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
388
			@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
389
			Model model) throws Exception {
390
 
391
		List<Integer> catalogIds = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
392
				.collect(Collectors.toList());
393
		JSONArray docA = solrService.getContentDocs(query, categoryId > 0 ? Arrays.asList(categoryId) : null, brands,
394
				limit, activeOnly);
395
 
396
		Iterator<Object> jsonIterator = docA.iterator();
397
		while (jsonIterator.hasNext()) {
398
			JSONObject i = (JSONObject) jsonIterator.next();
399
 
400
			if (!catalogIds.contains(i.get("catalogId_i"))) {
401
				jsonIterator.remove();
402
			}
403
 
404
		}
405
 
406
		model.addAttribute("response1", docA.toString());
407
 
408
		return "response";
409
	}
410
 
35487 ranu 411
	@GetMapping(value = "/statusWiseCatalogs")
412
	public String statusWiseCatalogs(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
413
									 @RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
414
									 @RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
415
									 Model model) throws Exception {
416
 
417
		List<CatalogMovingEnum> catalogMovingEnums = Arrays.asList(CatalogMovingEnum.HID, CatalogMovingEnum.FASTMOVING, CatalogMovingEnum.RUNNING);
418
 
419
		List<Integer> catalogIds = catalogRepository.selectAllStatusAndBrandWise(brands, catalogMovingEnums);
420
 
421
		JSONArray docA = solrService.getContentDocs(query, categoryId > 0 ? Arrays.asList(categoryId) : null, brands,
422
				limit, activeOnly);
423
 
424
		Iterator<Object> jsonIterator = docA.iterator();
425
		while (jsonIterator.hasNext()) {
426
			JSONObject i = (JSONObject) jsonIterator.next();
427
 
428
			if (!catalogIds.contains(i.get("catalogId_i"))) {
429
				jsonIterator.remove();
430
			}
431
 
432
		}
433
 
434
		model.addAttribute("response1", docA.toString());
435
 
436
		return "response";
437
	}
438
 
25380 amit.gupta 439
	@GetMapping(value = "/content/index")
440
	public String index(HttpServletRequest request, Model model) throws Exception {
33973 tejus.loha 441
 
25380 amit.gupta 442
		return "content";
443
	}
444
 
445
	private List<ContentPojo> readFile(MultipartFile file) throws Exception {
446
		CSVParser parser = new CSVParser(new InputStreamReader(file.getInputStream()), CSVFormat.DEFAULT);
447
		List<CSVRecord> records = parser.getRecords();
448
		if (records.size() < 2) {
449
			parser.close();
450
			throw new ProfitMandiBusinessException("Uploaded File", "", "No records Found");
451
		}
452
		// Remove header
453
		records.remove(0);
454
		List<ContentPojo> returnList = new ArrayList<ContentPojo>();
455
		for (CSVRecord record : records) {
25430 amit.gupta 456
			ContentPojo cp = null;
457
			Long entityId = Long.parseLong(record.get(Entity_Id));
25380 amit.gupta 458
			try {
25430 amit.gupta 459
				cp = mongoClient.getEntityById(entityId);
460
			} catch (Exception e) {
461
			}
462
			try {
463
				if (cp == null) {
464
					cp = new ContentPojo(entityId);
465
				}
25380 amit.gupta 466
				cp.setWarranty(record.get(Warranty));
467
				cp.setKeySpecs(Arrays
468
						.asList(record.get(KeySpec1), record.get(KeySpec2), record.get(KeySpec3), record.get(KeySpec4))
25429 amit.gupta 469
						.stream().filter(x -> x != null && !x.equals("")).collect(Collectors.toList()));
25380 amit.gupta 470
				cp.setPackageContents(Arrays.asList(record.get(Package_Contents).split(",")));
471
				cp.setDetailedSpecs(getDetailedSpecs(record));
472
				returnList.add(cp);
473
			} catch (Exception e) {
474
				continue;
475
			}
476
		}
477
		parser.close();
478
		return returnList;
479
	}
480
 
35346 ranu 481
 
482
	private List<VideoUrlPojo> readVideoFile(MultipartFile file) throws Exception {
483
 
484
		CSVParser parser = new CSVParser(
485
				new InputStreamReader(file.getInputStream()),
486
				CSVFormat.DEFAULT
487
		);
488
 
489
		List<CSVRecord> records = parser.getRecords();
490
 
491
		if (records.size() < 2) {
492
			parser.close();
493
			throw new ProfitMandiBusinessException("Uploaded File", "", "No records found");
494
		}
495
 
496
		// Remove header
497
		records.remove(0);
498
 
499
		List<VideoUrlPojo> returnList = new ArrayList<>();
500
 
501
		for (CSVRecord record : records) {
502
 
503
			try {
504
				// Must match CSV column order
35348 ranu 505
				Long catalogId = Long.parseLong(record.get(1));
506
				String url = record.get(2);
35346 ranu 507
 
508
				VideoUrlPojo row = new VideoUrlPojo();
509
				row.setCatalogId(Math.toIntExact(catalogId));
510
				row.setUrl(url);
511
 
512
				returnList.add(row);
513
 
514
			} catch (Exception e) {
515
				// skip bad rows, same as your style
516
				continue;
517
			}
518
		}
519
 
520
		parser.close();
521
		return returnList;
522
	}
523
 
524
 
25380 amit.gupta 525
	private List<SpecificationGroup> getDetailedSpecs(CSVRecord record) throws Exception {
526
		List<SpecificationGroup> specificationGroups = new ArrayList<>();
527
		int currentIndex = 8;
528
		while (StringUtils.isNotEmpty(record.get(currentIndex))) {
529
			int start = currentIndex;
530
			List<Specification> specifications = new ArrayList<>();
531
			int begin = 0;
532
			while (begin < 5) {
533
				int specKeyIndex = (begin * 2) + 1;
534
				int specValueIndex = (begin * 2) + 2;
535
 
536
				if (StringUtils.isNotEmpty(record.get(currentIndex + specKeyIndex))
537
						&& StringUtils.isNotEmpty(record.get(currentIndex + specValueIndex))) {
538
					Specification specification = new Specification(record.get(currentIndex + specKeyIndex),
539
							Arrays.asList(record.get(currentIndex + specValueIndex)));
540
					specifications.add(specification);
541
				}
542
				begin++;
543
			}
544
			SpecificationGroup specificationGroup = new SpecificationGroup(record.get(start), specifications);
545
			specificationGroups.add(specificationGroup);
25392 amit.gupta 546
			currentIndex += 11;
25380 amit.gupta 547
		}
548
 
549
		return specificationGroups;
550
	}
551
 
552
	private ChannelSftp setupJsch() throws JSchException {
553
		JSch jsch = new JSch();
33463 amit.gupta 554
		Session jschSession = jsch.getSession("root", "172.105.58.16");
31330 tejbeer 555
		// Session jschSession = jsch.getSession("root", "173.255.254.24");
556
		LOGGER.info("getClass().getResource(\"id_rsa\") {}",
557
				getClass().getClassLoader().getResource("id_rsa").getPath());
29881 amit.gupta 558
		jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
31330 tejbeer 559
		// jschSession.setPassword("spic@2015static0");
25396 amit.gupta 560
		jschSession.setConfig("StrictHostKeyChecking", "no");
25380 amit.gupta 561
		jschSession.connect();
562
		return (ChannelSftp) jschSession.openChannel("sftp");
563
	}
564
 
29900 amit.gupta 565
	private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
25380 amit.gupta 566
		ChannelSftp channelSftp = setupJsch();
567
		channelSftp.connect();
29900 amit.gupta 568
		this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
569
		channelSftp.exit();
570
	}
571
 
572
	private void uploadContentFiles(Map<String, InputStream> fileStreamsMap, int entityId) throws Exception {
573
		ChannelSftp channelSftp = setupJsch();
574
		channelSftp.connect();
25380 amit.gupta 575
		this.folderUpload(channelSftp, fileStreamsMap, REMOTE_DIR, entityId + "");
576
		channelSftp.exit();
577
	}
578
 
579
	private void recursiveFolderUpload(ChannelSftp channelSftp, String sourcePath, String destinationPath)
580
			throws SftpException, FileNotFoundException {
581
 
582
		File sourceFile = new File(sourcePath);
583
		if (sourceFile.isFile()) {
584
 
585
			// copy if it is a file
586
			channelSftp.cd(destinationPath);
587
			if (!sourceFile.getName().startsWith("."))
588
				channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE);
589
 
590
		} else {
591
 
592
			System.out.println("inside else " + sourceFile.getName());
593
			File[] files = sourceFile.listFiles();
594
 
595
			if (files != null && !sourceFile.getName().startsWith(".")) {
596
 
597
				channelSftp.cd(destinationPath);
598
				SftpATTRS attrs = null;
599
 
600
				// check if the directory is already existing
601
				try {
602
					attrs = channelSftp.stat(destinationPath + "/" + sourceFile.getName());
603
				} catch (Exception e) {
604
					System.out.println(destinationPath + "/" + sourceFile.getName() + " not found");
605
				}
606
 
607
				// else create a directory
608
				if (attrs != null) {
609
					System.out.println("Directory exists IsDir=" + attrs.isDir());
610
				} else {
611
					System.out.println("Creating dir " + sourceFile.getName());
612
					channelSftp.mkdir(sourceFile.getName());
613
				}
614
 
615
				for (File f : files) {
616
					recursiveFolderUpload(channelSftp, f.getAbsolutePath(),
617
							destinationPath + "/" + sourceFile.getName());
618
				}
619
 
620
			}
621
		}
622
 
623
	}
624
 
625
	private void folderUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath,
626
			String folderName) throws SftpException, FileNotFoundException {
627
 
628
		channelSftp.cd(destinationPath);
629
		SftpATTRS attrs = null;
630
 
631
		// check if the directory is already existing
632
		try {
633
			attrs = channelSftp.stat(folderName);
634
		} catch (Exception e) {
635
			System.out.println(destinationPath + "/" + folderName + " not found");
636
		}
637
 
638
		// else create a directory
25413 amit.gupta 639
		if (attrs == null) {
640
			channelSftp.mkdir(folderName);
641
			channelSftp.chmod(0755, ".");
25380 amit.gupta 642
		}
643
		channelSftp.cd(folderName);
25413 amit.gupta 644
		channelSftp.rm("*");
25380 amit.gupta 645
 
646
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
647
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
648
		}
649
 
650
	}
651
 
652
	private Map<String, InputStream> getStreamFileMap(ContentPojo contentPojo, EntityMediaPojo entityMediaPojo) {
653
		Map<String, InputStream> map = new HashMap<>();
25401 amit.gupta 654
		LOGGER.info("entityMediaPojo.getMediaPojos() -[{}]", entityMediaPojo.getMediaPojos());
25404 amit.gupta 655
		for (int i = 0; i < entityMediaPojo.getMediaPojos().size(); i++) {
25380 amit.gupta 656
			MediaPojo mediaPojo = entityMediaPojo.getMediaPojos().get(i);
657
			String extension;
658
			String base64String = mediaPojo.getImageData();
659
			String[] strings = base64String.split(",");
660
			switch (strings[0]) {// check image's extension
661
			case "data:image/jpeg;base64":
662
				extension = "jpeg";
663
				break;
664
			case "data:image/png;base64":
665
				extension = "png";
666
				break;
667
			default:// should write cases for more images types
668
				extension = "jpg";
669
				break;
670
			}
25402 amit.gupta 671
			LOGGER.info("After switch statement = {}", extension);
25380 amit.gupta 672
			// convert base64 string to binary data
673
			byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
674
			String fileName = getFileName(entityMediaPojo.getEntityId(), mediaPojo.getTitle(), extension);
25402 amit.gupta 675
			LOGGER.info("After switch statement Filename = {}", fileName);
25380 amit.gupta 676
			mediaPojo.setImageData(null);
25430 amit.gupta 677
			String staticServerUrl = String.format(STATIC_SERVER_URL, entityMediaPojo.getEntityId() % 3);
25414 amit.gupta 678
			mediaPojo.setUrl(staticServerUrl + entityMediaPojo.getEntityId() + "/" + fileName);
25380 amit.gupta 679
			map.put(fileName, new ByteArrayInputStream(data));
680
			if (i == entityMediaPojo.getDefaultImageIndex()) {
681
				String defaultFileName = getFileName(entityMediaPojo.getEntityId(), DEFAULT, extension);
682
				map.put(defaultFileName, new ByteArrayInputStream(data));
25414 amit.gupta 683
				contentPojo.setDefaultImageUrl(staticServerUrl + entityMediaPojo.getEntityId() + "/" + defaultFileName);
25380 amit.gupta 684
			}
685
		}
686
		contentPojo.setImages(entityMediaPojo.getMediaPojos());
687
 
688
		return map;
689
	}
690
 
25409 amit.gupta 691
	private String getMediaPrefix(String productName) {
692
		String mediaPrefix = productName.toLowerCase().replace(' ', '-');
693
		mediaPrefix = mediaPrefix.replaceAll("/", "-");
694
		mediaPrefix = mediaPrefix.replaceAll("-+", "-");
695
		return mediaPrefix;
696
	}
697
 
28264 tejbeer 698
	@GetMapping(value = "/urlGeneration")
699
	public String urlGeneration(HttpServletRequest request, Model model) throws Exception {
700
		return "url-generation";
701
	}
33443 ranu 702
	@Autowired
703
	UserRepository userRepository;
704
	@Autowired
705
	private CookiesProcessor cookiesProcessor;
706
 
707
	@GetMapping(value = "/printResources")
708
	public String printResources(HttpServletRequest request, Model model) throws Exception {
709
		List<Region> regionList = regionRepository.selectAll();
710
		model.addAttribute("regionList", regionList);
711
		return "print-resource";
712
	}
713
 
714
	@RequestMapping(value = "/postPrintResource", method = RequestMethod.POST)
715
	public String postPrintResource(HttpServletRequest request, @RequestBody PrintResourceModel printResourceModel,
716
									Model model) throws Exception {
717
		LOGGER.info("printResourceModel {}", printResourceModel);
718
		PrintResource printResource = new PrintResource();
719
		printResource.setTitle(printResourceModel.getTitle());
720
		printResource.setStartDate(printResourceModel.getStartDate().atStartOfDay());
721
		if (printResourceModel.getEndDate() != null) {
722
			printResource.setEndDate(printResourceModel.getEndDate().atStartOfDay());
723
		} else {
724
			printResource.setEndDate(null);
725
		}
726
 
727
		printResource.setCreateTimestamp(LocalDateTime.now());
728
		printResource.setImgUrl(printResourceModel.getImgUrl());
33501 ranu 729
		printResource.setThumbnailUrl(printResourceModel.getThumbnailUrl());
33443 ranu 730
		printResourceRepository.persist(printResource);
731
 
732
		PrintResourceRegion printResourceRegion = new PrintResourceRegion();
733
		int regionId = Integer.parseInt(printResourceModel.getRegion());
734
		printResourceRegion.setRegionId(regionId);
735
		printResourceRegion.setResourceId(printResource.getId());
736
		printResourceRegionRepository.persist(printResourceRegion);
737
 
738
 
739
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
740
 
741
		return "response";
742
	}
743
 
744
	@RequestMapping(value = "/changeEndDate", method = RequestMethod.POST)
745
	public String changeEndDate(HttpServletRequest request, @RequestParam LocalDate date, @RequestParam int resourceId,
746
								Model model) throws Exception {
747
 
748
		PrintResource printResource = printResourceRepository.selectById(resourceId);
749
		printResource.setEndDate(date.atStartOfDay());
750
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
751
		return "response";
752
	}
753
 
754
	@GetMapping(value = "/partnerPrintResources")
755
	public String partnerPrintResources(HttpServletRequest request, Model model) throws Exception {
756
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
757
		int fofoId = loginDetails.getFofoId();
758
		User user = userRepository.selectById(fofoId);
759
		List<PartnerRegion> partnerRegion = partnerRegionRepository.selectByfofoId(user.getId());
760
		LocalDateTime currentDate = LocalDateTime.now();
761
		List<PrintResource> printResources = printResourceRepository.selectPrintResourcesByFofoRegion(partnerRegion.get(0).getRegionId(), currentDate);
762
		LOGGER.info("printresourcesList {}", printResources);
763
		model.addAttribute("printResources", printResources);
764
		return "partner_print_resource";
765
	}
766
 
767
	@GetMapping(value = "/allPrintResources")
768
	public String allPrintResources(HttpServletRequest request, Model model) throws Exception {
769
		LocalDateTime currentDate = LocalDateTime.now();
770
		List<PrintResource> printResources = printResourceRepository.selectAllPrintResources(currentDate);
771
		model.addAttribute("printResources", printResources);
772
		return "all-print-resource";
773
	}
774
 
35346 ranu 775
	@GetMapping("/content/video/check/{catalogId}")
776
	public ResponseEntity<?> checkVideo(@PathVariable int catalogId) throws Exception {
777
		ContentPojo cp = mongoClient.getEntityById(catalogId);
778
 
779
		LOGGER.info("Video Url {}", cp.getVideoUrls());
780
		return ResponseEntity.ok(cp.getVideoUrls());
781
	}
782
 
783
 
25380 amit.gupta 784
}