Subversion Repositories SmartDukaan

Rev

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