Subversion Repositories SmartDukaan

Rev

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