Subversion Repositories SmartDukaan

Rev

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