Subversion Repositories SmartDukaan

Rev

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