Subversion Repositories SmartDukaan

Rev

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