Subversion Repositories SmartDukaan

Rev

Rev 35549 | 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;
35549 ranu 9
import com.spice.profitmandi.dao.entity.cs.Bulletin;
33443 ranu 10
import com.spice.profitmandi.dao.entity.cs.PartnerRegion;
11
import com.spice.profitmandi.dao.entity.cs.Region;
28264 tejbeer 12
import com.spice.profitmandi.dao.entity.dtr.DocumentUrl;
33443 ranu 13
import com.spice.profitmandi.dao.entity.fofo.PrintResource;
14
import com.spice.profitmandi.dao.entity.fofo.PrintResourceRegion;
15
import com.spice.profitmandi.dao.entity.user.User;
35487 ranu 16
import com.spice.profitmandi.dao.enumuration.inventory.CatalogMovingEnum;
33443 ranu 17
import com.spice.profitmandi.dao.model.*;
18
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
35487 ranu 19
import com.spice.profitmandi.dao.repository.catalog.CatalogRepository;
31330 tejbeer 20
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
25380 amit.gupta 21
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
33973 tejus.loha 22
import com.spice.profitmandi.dao.repository.catalog.SuperCatalogRepository;
35549 ranu 23
import com.spice.profitmandi.dao.repository.cs.BulletinRepository;
33443 ranu 24
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
25
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
28264 tejbeer 26
import com.spice.profitmandi.dao.repository.dtr.DocumentUrlRepository;
25380 amit.gupta 27
import com.spice.profitmandi.dao.repository.dtr.Mongo;
33443 ranu 28
import com.spice.profitmandi.dao.repository.fofo.PrintResourceRegionRepository;
29
import com.spice.profitmandi.dao.repository.fofo.PrintResourceRepository;
30
import com.spice.profitmandi.dao.repository.user.UserRepository;
32952 amit.gupta 31
import com.spice.profitmandi.service.catalog.ItemLoaderService;
25380 amit.gupta 32
import com.spice.profitmandi.web.model.EntityMediaPojo;
33443 ranu 33
import com.spice.profitmandi.web.model.LoginDetails;
34
import com.spice.profitmandi.web.util.CookiesProcessor;
25380 amit.gupta 35
import com.spice.profitmandi.web.util.MVCResponseSender;
30080 amit.gupta 36
import org.apache.commons.csv.CSVFormat;
37
import org.apache.commons.csv.CSVParser;
38
import org.apache.commons.csv.CSVRecord;
39
import org.apache.commons.lang3.StringUtils;
40
import org.apache.logging.log4j.LogManager;
41
import org.apache.logging.log4j.Logger;
31330 tejbeer 42
import org.json.JSONArray;
43
import org.json.JSONObject;
30080 amit.gupta 44
import org.springframework.beans.factory.annotation.Autowired;
35346 ranu 45
import org.springframework.http.ResponseEntity;
30080 amit.gupta 46
import org.springframework.stereotype.Controller;
35487 ranu 47
import org.springframework.transaction.annotation.Transactional;
30080 amit.gupta 48
import org.springframework.ui.Model;
49
import org.springframework.web.bind.annotation.*;
50
import org.springframework.web.multipart.MultipartFile;
25380 amit.gupta 51
 
30080 amit.gupta 52
import javax.servlet.http.HttpServletRequest;
53
import javax.xml.bind.DatatypeConverter;
54
import java.io.*;
55
import java.sql.Timestamp;
56
import java.time.LocalDate;
57
import java.time.LocalDateTime;
58
import java.time.ZoneOffset;
59
import java.util.*;
60
import java.util.stream.Collectors;
61
 
35458 amit 62
@Transactional(rollbackFor = Throwable.class)
25380 amit.gupta 63
@Controller
64
public class ContentController {
65
	@Autowired
66
	MVCResponseSender mvcResponseSender;
67
 
68
	@Autowired
69
	Mongo mongoClient;
70
 
71
	@Autowired
72
	SolrService solrService;
73
 
74
	@Autowired
75
	ItemRepository itemRepository;
76
 
28264 tejbeer 77
	@Autowired
78
	DocumentUrlRepository documentUrlRepository;
79
 
31330 tejbeer 80
	@Autowired
81
	FocusedModelRepository focusedModelRepository;
33443 ranu 82
 
83
	@Autowired
84
	PrintResourceRepository printResourceRepository;
85
	@Autowired
86
	AuthRepository authRepository;
87
	@Autowired
88
	RegionRepository regionRepository;
89
	@Autowired
90
	PrintResourceRegionRepository printResourceRegionRepository;
91
	@Autowired
92
	PartnerRegionRepository partnerRegionRepository;
33973 tejus.loha 93
	@Autowired
94
	SuperCatalogRepository superCatalogRepository;
35487 ranu 95
	@Autowired
96
	CatalogRepository catalogRepository;
35549 ranu 97
	@Autowired
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
 
357
	@GetMapping(value = "/entity")
28264 tejbeer 358
	public String searchEntity(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
31330 tejbeer 359
			@RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
360
			@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
361
			Model model) throws Exception {
362
		model.addAttribute("response1", solrService.getContent(query, categoryId > 0 ? Arrays.asList(categoryId) : null,
31711 amit.gupta 363
				brands, limit, false));
25380 amit.gupta 364
		return "response";
365
	}
366
 
31330 tejbeer 367
	@GetMapping(value = "/focusedEntity")
368
	public String focusedEntity(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
369
			@RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
370
			@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
371
			Model model) throws Exception {
372
 
373
		List<Integer> catalogIds = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
374
				.collect(Collectors.toList());
375
		JSONArray docA = solrService.getContentDocs(query, categoryId > 0 ? Arrays.asList(categoryId) : null, brands,
376
				limit, activeOnly);
377
 
378
		Iterator<Object> jsonIterator = docA.iterator();
379
		while (jsonIterator.hasNext()) {
380
			JSONObject i = (JSONObject) jsonIterator.next();
381
 
382
			if (!catalogIds.contains(i.get("catalogId_i"))) {
383
				jsonIterator.remove();
384
			}
385
 
386
		}
387
 
388
		model.addAttribute("response1", docA.toString());
389
 
390
		return "response";
391
	}
392
 
35487 ranu 393
	@GetMapping(value = "/statusWiseCatalogs")
394
	public String statusWiseCatalogs(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
395
									 @RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
396
									 @RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
397
									 Model model) throws Exception {
398
 
399
		List<CatalogMovingEnum> catalogMovingEnums = Arrays.asList(CatalogMovingEnum.HID, CatalogMovingEnum.FASTMOVING, CatalogMovingEnum.RUNNING);
400
 
401
		List<Integer> catalogIds = catalogRepository.selectAllStatusAndBrandWise(brands, catalogMovingEnums);
402
 
403
		JSONArray docA = solrService.getContentDocs(query, categoryId > 0 ? Arrays.asList(categoryId) : null, brands,
404
				limit, activeOnly);
405
 
406
		Iterator<Object> jsonIterator = docA.iterator();
407
		while (jsonIterator.hasNext()) {
408
			JSONObject i = (JSONObject) jsonIterator.next();
409
 
410
			if (!catalogIds.contains(i.get("catalogId_i"))) {
411
				jsonIterator.remove();
412
			}
413
 
414
		}
415
 
416
		model.addAttribute("response1", docA.toString());
417
 
418
		return "response";
419
	}
420
 
25380 amit.gupta 421
	@GetMapping(value = "/content/index")
422
	public String index(HttpServletRequest request, Model model) throws Exception {
33973 tejus.loha 423
 
25380 amit.gupta 424
		return "content";
425
	}
426
 
427
	private List<ContentPojo> readFile(MultipartFile file) throws Exception {
428
		CSVParser parser = new CSVParser(new InputStreamReader(file.getInputStream()), CSVFormat.DEFAULT);
429
		List<CSVRecord> records = parser.getRecords();
430
		if (records.size() < 2) {
431
			parser.close();
432
			throw new ProfitMandiBusinessException("Uploaded File", "", "No records Found");
433
		}
434
		// Remove header
435
		records.remove(0);
436
		List<ContentPojo> returnList = new ArrayList<ContentPojo>();
437
		for (CSVRecord record : records) {
25430 amit.gupta 438
			ContentPojo cp = null;
439
			Long entityId = Long.parseLong(record.get(Entity_Id));
25380 amit.gupta 440
			try {
25430 amit.gupta 441
				cp = mongoClient.getEntityById(entityId);
442
			} catch (Exception e) {
443
			}
444
			try {
445
				if (cp == null) {
446
					cp = new ContentPojo(entityId);
447
				}
25380 amit.gupta 448
				cp.setWarranty(record.get(Warranty));
449
				cp.setKeySpecs(Arrays
450
						.asList(record.get(KeySpec1), record.get(KeySpec2), record.get(KeySpec3), record.get(KeySpec4))
25429 amit.gupta 451
						.stream().filter(x -> x != null && !x.equals("")).collect(Collectors.toList()));
25380 amit.gupta 452
				cp.setPackageContents(Arrays.asList(record.get(Package_Contents).split(",")));
453
				cp.setDetailedSpecs(getDetailedSpecs(record));
454
				returnList.add(cp);
455
			} catch (Exception e) {
456
				continue;
457
			}
458
		}
459
		parser.close();
460
		return returnList;
461
	}
462
 
35346 ranu 463
 
464
	private List<VideoUrlPojo> readVideoFile(MultipartFile file) throws Exception {
465
 
466
		CSVParser parser = new CSVParser(
467
				new InputStreamReader(file.getInputStream()),
468
				CSVFormat.DEFAULT
469
		);
470
 
471
		List<CSVRecord> records = parser.getRecords();
472
 
473
		if (records.size() < 2) {
474
			parser.close();
475
			throw new ProfitMandiBusinessException("Uploaded File", "", "No records found");
476
		}
477
 
478
		// Remove header
479
		records.remove(0);
480
 
481
		List<VideoUrlPojo> returnList = new ArrayList<>();
482
 
483
		for (CSVRecord record : records) {
484
 
485
			try {
486
				// Must match CSV column order
35348 ranu 487
				Long catalogId = Long.parseLong(record.get(1));
488
				String url = record.get(2);
35346 ranu 489
 
490
				VideoUrlPojo row = new VideoUrlPojo();
491
				row.setCatalogId(Math.toIntExact(catalogId));
492
				row.setUrl(url);
493
 
494
				returnList.add(row);
495
 
496
			} catch (Exception e) {
497
				// skip bad rows, same as your style
498
				continue;
499
			}
500
		}
501
 
502
		parser.close();
503
		return returnList;
504
	}
505
 
506
 
25380 amit.gupta 507
	private List<SpecificationGroup> getDetailedSpecs(CSVRecord record) throws Exception {
508
		List<SpecificationGroup> specificationGroups = new ArrayList<>();
509
		int currentIndex = 8;
510
		while (StringUtils.isNotEmpty(record.get(currentIndex))) {
511
			int start = currentIndex;
512
			List<Specification> specifications = new ArrayList<>();
513
			int begin = 0;
514
			while (begin < 5) {
515
				int specKeyIndex = (begin * 2) + 1;
516
				int specValueIndex = (begin * 2) + 2;
517
 
518
				if (StringUtils.isNotEmpty(record.get(currentIndex + specKeyIndex))
519
						&& StringUtils.isNotEmpty(record.get(currentIndex + specValueIndex))) {
520
					Specification specification = new Specification(record.get(currentIndex + specKeyIndex),
521
							Arrays.asList(record.get(currentIndex + specValueIndex)));
522
					specifications.add(specification);
523
				}
524
				begin++;
525
			}
526
			SpecificationGroup specificationGroup = new SpecificationGroup(record.get(start), specifications);
527
			specificationGroups.add(specificationGroup);
25392 amit.gupta 528
			currentIndex += 11;
25380 amit.gupta 529
		}
530
 
531
		return specificationGroups;
532
	}
533
 
534
	private ChannelSftp setupJsch() throws JSchException {
535
		JSch jsch = new JSch();
33463 amit.gupta 536
		Session jschSession = jsch.getSession("root", "172.105.58.16");
31330 tejbeer 537
		// Session jschSession = jsch.getSession("root", "173.255.254.24");
538
		LOGGER.info("getClass().getResource(\"id_rsa\") {}",
539
				getClass().getClassLoader().getResource("id_rsa").getPath());
29881 amit.gupta 540
		jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
31330 tejbeer 541
		// jschSession.setPassword("spic@2015static0");
25396 amit.gupta 542
		jschSession.setConfig("StrictHostKeyChecking", "no");
25380 amit.gupta 543
		jschSession.connect();
544
		return (ChannelSftp) jschSession.openChannel("sftp");
545
	}
546
 
29900 amit.gupta 547
	private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
25380 amit.gupta 548
		ChannelSftp channelSftp = setupJsch();
549
		channelSftp.connect();
29900 amit.gupta 550
		this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
551
		channelSftp.exit();
552
	}
553
 
554
	private void uploadContentFiles(Map<String, InputStream> fileStreamsMap, int entityId) throws Exception {
555
		ChannelSftp channelSftp = setupJsch();
556
		channelSftp.connect();
25380 amit.gupta 557
		this.folderUpload(channelSftp, fileStreamsMap, REMOTE_DIR, entityId + "");
558
		channelSftp.exit();
559
	}
560
 
561
	private void recursiveFolderUpload(ChannelSftp channelSftp, String sourcePath, String destinationPath)
562
			throws SftpException, FileNotFoundException {
563
 
564
		File sourceFile = new File(sourcePath);
565
		if (sourceFile.isFile()) {
566
 
567
			// copy if it is a file
568
			channelSftp.cd(destinationPath);
569
			if (!sourceFile.getName().startsWith("."))
570
				channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE);
571
 
572
		} else {
573
 
574
			System.out.println("inside else " + sourceFile.getName());
575
			File[] files = sourceFile.listFiles();
576
 
577
			if (files != null && !sourceFile.getName().startsWith(".")) {
578
 
579
				channelSftp.cd(destinationPath);
580
				SftpATTRS attrs = null;
581
 
582
				// check if the directory is already existing
583
				try {
584
					attrs = channelSftp.stat(destinationPath + "/" + sourceFile.getName());
585
				} catch (Exception e) {
586
					System.out.println(destinationPath + "/" + sourceFile.getName() + " not found");
587
				}
588
 
589
				// else create a directory
590
				if (attrs != null) {
591
					System.out.println("Directory exists IsDir=" + attrs.isDir());
592
				} else {
593
					System.out.println("Creating dir " + sourceFile.getName());
594
					channelSftp.mkdir(sourceFile.getName());
595
				}
596
 
597
				for (File f : files) {
598
					recursiveFolderUpload(channelSftp, f.getAbsolutePath(),
599
							destinationPath + "/" + sourceFile.getName());
600
				}
601
 
602
			}
603
		}
604
 
605
	}
606
 
607
	private void folderUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath,
608
			String folderName) throws SftpException, FileNotFoundException {
609
 
610
		channelSftp.cd(destinationPath);
611
		SftpATTRS attrs = null;
612
 
613
		// check if the directory is already existing
614
		try {
615
			attrs = channelSftp.stat(folderName);
616
		} catch (Exception e) {
617
			System.out.println(destinationPath + "/" + folderName + " not found");
618
		}
619
 
620
		// else create a directory
25413 amit.gupta 621
		if (attrs == null) {
622
			channelSftp.mkdir(folderName);
623
			channelSftp.chmod(0755, ".");
25380 amit.gupta 624
		}
625
		channelSftp.cd(folderName);
25413 amit.gupta 626
		channelSftp.rm("*");
25380 amit.gupta 627
 
628
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
629
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
630
		}
631
 
632
	}
633
 
634
	private Map<String, InputStream> getStreamFileMap(ContentPojo contentPojo, EntityMediaPojo entityMediaPojo) {
635
		Map<String, InputStream> map = new HashMap<>();
25401 amit.gupta 636
		LOGGER.info("entityMediaPojo.getMediaPojos() -[{}]", entityMediaPojo.getMediaPojos());
25404 amit.gupta 637
		for (int i = 0; i < entityMediaPojo.getMediaPojos().size(); i++) {
25380 amit.gupta 638
			MediaPojo mediaPojo = entityMediaPojo.getMediaPojos().get(i);
639
			String extension;
640
			String base64String = mediaPojo.getImageData();
641
			String[] strings = base64String.split(",");
642
			switch (strings[0]) {// check image's extension
643
			case "data:image/jpeg;base64":
644
				extension = "jpeg";
645
				break;
646
			case "data:image/png;base64":
647
				extension = "png";
648
				break;
649
			default:// should write cases for more images types
650
				extension = "jpg";
651
				break;
652
			}
25402 amit.gupta 653
			LOGGER.info("After switch statement = {}", extension);
25380 amit.gupta 654
			// convert base64 string to binary data
655
			byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
656
			String fileName = getFileName(entityMediaPojo.getEntityId(), mediaPojo.getTitle(), extension);
25402 amit.gupta 657
			LOGGER.info("After switch statement Filename = {}", fileName);
25380 amit.gupta 658
			mediaPojo.setImageData(null);
25430 amit.gupta 659
			String staticServerUrl = String.format(STATIC_SERVER_URL, entityMediaPojo.getEntityId() % 3);
25414 amit.gupta 660
			mediaPojo.setUrl(staticServerUrl + entityMediaPojo.getEntityId() + "/" + fileName);
25380 amit.gupta 661
			map.put(fileName, new ByteArrayInputStream(data));
662
			if (i == entityMediaPojo.getDefaultImageIndex()) {
663
				String defaultFileName = getFileName(entityMediaPojo.getEntityId(), DEFAULT, extension);
664
				map.put(defaultFileName, new ByteArrayInputStream(data));
25414 amit.gupta 665
				contentPojo.setDefaultImageUrl(staticServerUrl + entityMediaPojo.getEntityId() + "/" + defaultFileName);
25380 amit.gupta 666
			}
667
		}
668
		contentPojo.setImages(entityMediaPojo.getMediaPojos());
669
 
670
		return map;
671
	}
672
 
25409 amit.gupta 673
	private String getMediaPrefix(String productName) {
674
		String mediaPrefix = productName.toLowerCase().replace(' ', '-');
675
		mediaPrefix = mediaPrefix.replaceAll("/", "-");
676
		mediaPrefix = mediaPrefix.replaceAll("-+", "-");
677
		return mediaPrefix;
678
	}
679
 
28264 tejbeer 680
	@GetMapping(value = "/urlGeneration")
681
	public String urlGeneration(HttpServletRequest request, Model model) throws Exception {
682
		return "url-generation";
683
	}
33443 ranu 684
	@Autowired
685
	UserRepository userRepository;
686
	@Autowired
687
	private CookiesProcessor cookiesProcessor;
688
 
689
	@GetMapping(value = "/printResources")
690
	public String printResources(HttpServletRequest request, Model model) throws Exception {
691
		List<Region> regionList = regionRepository.selectAll();
692
		model.addAttribute("regionList", regionList);
693
		return "print-resource";
694
	}
695
 
696
	@RequestMapping(value = "/postPrintResource", method = RequestMethod.POST)
697
	public String postPrintResource(HttpServletRequest request, @RequestBody PrintResourceModel printResourceModel,
698
									Model model) throws Exception {
699
		LOGGER.info("printResourceModel {}", printResourceModel);
700
		PrintResource printResource = new PrintResource();
701
		printResource.setTitle(printResourceModel.getTitle());
702
		printResource.setStartDate(printResourceModel.getStartDate().atStartOfDay());
703
		if (printResourceModel.getEndDate() != null) {
704
			printResource.setEndDate(printResourceModel.getEndDate().atStartOfDay());
705
		} else {
706
			printResource.setEndDate(null);
707
		}
708
 
709
		printResource.setCreateTimestamp(LocalDateTime.now());
710
		printResource.setImgUrl(printResourceModel.getImgUrl());
33501 ranu 711
		printResource.setThumbnailUrl(printResourceModel.getThumbnailUrl());
33443 ranu 712
		printResourceRepository.persist(printResource);
713
 
714
		PrintResourceRegion printResourceRegion = new PrintResourceRegion();
715
		int regionId = Integer.parseInt(printResourceModel.getRegion());
716
		printResourceRegion.setRegionId(regionId);
717
		printResourceRegion.setResourceId(printResource.getId());
718
		printResourceRegionRepository.persist(printResourceRegion);
719
 
720
 
721
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
722
 
723
		return "response";
724
	}
725
 
726
	@RequestMapping(value = "/changeEndDate", method = RequestMethod.POST)
727
	public String changeEndDate(HttpServletRequest request, @RequestParam LocalDate date, @RequestParam int resourceId,
728
								Model model) throws Exception {
729
 
730
		PrintResource printResource = printResourceRepository.selectById(resourceId);
731
		printResource.setEndDate(date.atStartOfDay());
732
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
733
		return "response";
734
	}
735
 
736
	@GetMapping(value = "/partnerPrintResources")
737
	public String partnerPrintResources(HttpServletRequest request, Model model) throws Exception {
738
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
739
		int fofoId = loginDetails.getFofoId();
740
		User user = userRepository.selectById(fofoId);
741
		List<PartnerRegion> partnerRegion = partnerRegionRepository.selectByfofoId(user.getId());
742
		LocalDateTime currentDate = LocalDateTime.now();
743
		List<PrintResource> printResources = printResourceRepository.selectPrintResourcesByFofoRegion(partnerRegion.get(0).getRegionId(), currentDate);
744
		LOGGER.info("printresourcesList {}", printResources);
745
		model.addAttribute("printResources", printResources);
746
		return "partner_print_resource";
747
	}
748
 
749
	@GetMapping(value = "/allPrintResources")
750
	public String allPrintResources(HttpServletRequest request, Model model) throws Exception {
751
		LocalDateTime currentDate = LocalDateTime.now();
752
		List<PrintResource> printResources = printResourceRepository.selectAllPrintResources(currentDate);
753
		model.addAttribute("printResources", printResources);
754
		return "all-print-resource";
755
	}
756
 
35346 ranu 757
	@GetMapping("/content/video/check/{catalogId}")
758
	public ResponseEntity<?> checkVideo(@PathVariable int catalogId) throws Exception {
759
		ContentPojo cp = mongoClient.getEntityById(catalogId);
760
 
761
		LOGGER.info("Video Url {}", cp.getVideoUrls());
762
		return ResponseEntity.ok(cp.getVideoUrls());
763
	}
764
 
765
 
35549 ranu 766
	@GetMapping(value = "/bulletin")
767
	public String bulletin(HttpServletRequest request, Model model) throws Exception {
768
		List<Region> regionList = regionRepository.selectAll();
769
		model.addAttribute("regionList", regionList);
770
		return "post-bulletin";
771
	}
772
 
773
 
774
	@RequestMapping(value = "/bulletinPost", method = RequestMethod.POST)
775
	public String bulletinPost(HttpServletRequest request, @RequestBody BulletinPostModel bulletinPostModel,
776
							   Model model) throws Exception {
35583 ranu 777
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
778
		String email = loginDetails.getEmailId();
779
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
35549 ranu 780
		LOGGER.info("bulletinPostModel {}", bulletinPostModel);
781
		Bulletin bulletin = new Bulletin();
782
		bulletin.setRegionId(bulletinPostModel.getRegionId());
783
		bulletin.setDescription(bulletinPostModel.getDescription());
784
		bulletin.setDocumentIds(bulletinPostModel.getDocumentIds());
785
		bulletin.setCreatedAt(LocalDateTime.now());
35583 ranu 786
		bulletin.setCreatedBy(authUser.getFullName());
35549 ranu 787
		bulletinRepository.persist(bulletin);
788
 
789
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
790
 
791
		return "response";
792
	}
793
 
794
 
795
 
796
 
25380 amit.gupta 797
}