Subversion Repositories SmartDukaan

Rev

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

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