Subversion Repositories SmartDukaan

Rev

Rev 35528 | Rev 35549 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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