Subversion Repositories SmartDukaan

Rev

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