Subversion Repositories SmartDukaan

Rev

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