Subversion Repositories SmartDukaan

Rev

Rev 33501 | Rev 35346 | 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;
33973 tejus.loha 8
import com.spice.profitmandi.dao.entity.catalog.SuperCatalog;
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;
15
import com.spice.profitmandi.dao.model.*;
16
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
31330 tejbeer 17
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
25380 amit.gupta 18
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
33973 tejus.loha 19
import com.spice.profitmandi.dao.repository.catalog.SuperCatalogRepository;
33443 ranu 20
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
21
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
28264 tejbeer 22
import com.spice.profitmandi.dao.repository.dtr.DocumentUrlRepository;
25380 amit.gupta 23
import com.spice.profitmandi.dao.repository.dtr.Mongo;
33443 ranu 24
import com.spice.profitmandi.dao.repository.fofo.PrintResourceRegionRepository;
25
import com.spice.profitmandi.dao.repository.fofo.PrintResourceRepository;
26
import com.spice.profitmandi.dao.repository.user.UserRepository;
32952 amit.gupta 27
import com.spice.profitmandi.service.catalog.ItemLoaderService;
25380 amit.gupta 28
import com.spice.profitmandi.web.model.EntityMediaPojo;
33443 ranu 29
import com.spice.profitmandi.web.model.LoginDetails;
30
import com.spice.profitmandi.web.util.CookiesProcessor;
25380 amit.gupta 31
import com.spice.profitmandi.web.util.MVCResponseSender;
30080 amit.gupta 32
import org.apache.commons.csv.CSVFormat;
33
import org.apache.commons.csv.CSVParser;
34
import org.apache.commons.csv.CSVRecord;
35
import org.apache.commons.lang3.StringUtils;
36
import org.apache.logging.log4j.LogManager;
37
import org.apache.logging.log4j.Logger;
31330 tejbeer 38
import org.json.JSONArray;
39
import org.json.JSONObject;
30080 amit.gupta 40
import org.springframework.beans.factory.annotation.Autowired;
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
 
28264 tejbeer 157
	@PostMapping(value = "/image/media/upload")
158
	public String uploadImageMediaContent(HttpServletRequest request, @RequestBody MediaPojo mediaPojo, Model model)
159
			throws Exception {
160
 
161
		LOGGER.info("mediaPojo" + mediaPojo);
162
		Map<String, InputStream> fileStreamsMap = new HashMap<>();
163
		String extension;
164
		String base64String = mediaPojo.getImageData();
165
		String[] strings = base64String.split(",");
166
		switch (strings[0]) {// check image's extension
167
		case "data:image/jpeg;base64":
168
			extension = "jpeg";
169
			break;
170
		case "data:image/png;base64":
171
			extension = "png";
172
			break;
32304 amit.gupta 173
			case "data:image/webp;base64":
32305 amit.gupta 174
				extension = "webp";
32304 amit.gupta 175
				break;
28264 tejbeer 176
		default:// should write cases for more images types
32304 amit.gupta 177
			extension = "jpg";
28264 tejbeer 178
			break;
179
		}
180
		LOGGER.info("After switch statement = {}", extension);
181
		// convert base64 string to binary data
182
		byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
183
		Timestamp tm = new Timestamp(System.currentTimeMillis());
28320 tejbeer 184
		String urlTitle = mediaPojo.getTitle().toLowerCase();
185
		String fileName = urlTitle.replace(' ', '-') + tm.getTime() + "." + extension;
28264 tejbeer 186
		LOGGER.info("After switch statement Filename = {}", fileName);
187
		mediaPojo.setImageData(null);
188
		mediaPojo.setUrl(IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName);
189
		fileStreamsMap.put(fileName, new ByteArrayInputStream(data));
190
		LOGGER.info("fileStreamsMap" + fileStreamsMap);
191
 
192
		uploadFile(fileStreamsMap);
193
 
194
		DocumentUrl du = new DocumentUrl();
195
		du.setTitle(mediaPojo.getTitle());
196
		du.setUrl(mediaPojo.getUrl());
197
		du.setCreatedTimestamp(LocalDateTime.now());
198
		documentUrlRepository.persist(du);
199
 
200
		model.addAttribute("documents", du);
201
		return "image-url";
202
	}
203
 
204
	private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
205
			throws SftpException, FileNotFoundException {
206
 
207
		channelSftp.cd(destinationPath);
208
		String folderName = "image" + LocalDate.now();
209
 
210
		channelSftp.cd(destinationPath);
211
		SftpATTRS attrs = null;
212
 
213
		// check if the directory is already existing
214
		try {
215
			attrs = channelSftp.stat(folderName);
216
		} catch (Exception e) {
217
			System.out.println(destinationPath + "/" + "image" + LocalDate.now() + " not found");
218
		}
219
 
220
		// else create a directory
221
		if (attrs == null) {
222
			channelSftp.mkdir(folderName);
223
			channelSftp.chmod(0755, ".");
224
		}
225
		channelSftp.cd(folderName);
226
 
227
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
228
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
229
		}
230
 
231
	}
232
 
233
	@GetMapping(value = "/search/image/media")
234
	public String getImage(HttpServletRequest request, Model model, @RequestParam String title) throws Exception {
235
		List<DocumentUrl> documents = documentUrlRepository.selectBySearch(title);
236
 
237
		model.addAttribute("documents", documents);
238
		return "image-url";
239
 
240
	}
241
 
25380 amit.gupta 242
	@GetMapping(value = "/content/media")
243
	public String getMediaContent(HttpServletRequest request, Model model, @RequestParam int entityId)
244
			throws Exception {
245
		ContentPojo contentPojo = mongoClient.getEntityById(entityId);
25409 amit.gupta 246
		if (contentPojo == null) {
25380 amit.gupta 247
			throw new Exception("Please add content first");
248
		}
249
		EntityMediaPojo empojo = getEntityMediaPojo(contentPojo);
31238 amit.gupta 250
		model.addAttribute("response1", mvcResponseSender.createResponseString(empojo));
25380 amit.gupta 251
		return "response";
252
	}
28264 tejbeer 253
 
27185 amit.gupta 254
	@GetMapping(value = "/catalog-item")
28264 tejbeer 255
	public String catalogItem(HttpServletRequest request, Model model) throws Exception {
27185 amit.gupta 256
		return "catalog-item";
257
	}
25380 amit.gupta 258
 
259
	private EntityMediaPojo getEntityMediaPojo(ContentPojo contentPojo) {
260
		EntityMediaPojo ep = new EntityMediaPojo();
261
		int defaultIndex = 0;
25409 amit.gupta 262
		if (contentPojo.getImages() == null) {
25380 amit.gupta 263
			ep.setMediaPojos(new ArrayList<>());
264
		} else {
265
			ep.setMediaPojos(contentPojo.getImages());
266
			for (MediaPojo mediaPojo : contentPojo.getImages()) {
25409 amit.gupta 267
				if (mediaPojo.getUrl() == null)
268
					continue;
269
 
25380 amit.gupta 270
				if (!mediaPojo.getUrl().equals(contentPojo.getDefaultImageUrl())) {
271
					defaultIndex++;
272
				}
273
			}
274
		}
275
		ep.setDefaultImageIndex(defaultIndex);
276
		return ep;
277
	}
278
 
279
	@GetMapping(value = "/entity")
28264 tejbeer 280
	public String searchEntity(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
31330 tejbeer 281
			@RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
282
			@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
283
			Model model) throws Exception {
284
		model.addAttribute("response1", solrService.getContent(query, categoryId > 0 ? Arrays.asList(categoryId) : null,
31711 amit.gupta 285
				brands, limit, false));
25380 amit.gupta 286
		return "response";
287
	}
288
 
31330 tejbeer 289
	@GetMapping(value = "/focusedEntity")
290
	public String focusedEntity(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
291
			@RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
292
			@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
293
			Model model) throws Exception {
294
 
295
		List<Integer> catalogIds = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
296
				.collect(Collectors.toList());
297
		JSONArray docA = solrService.getContentDocs(query, categoryId > 0 ? Arrays.asList(categoryId) : null, brands,
298
				limit, activeOnly);
299
 
300
		Iterator<Object> jsonIterator = docA.iterator();
301
		while (jsonIterator.hasNext()) {
302
			JSONObject i = (JSONObject) jsonIterator.next();
303
 
304
			if (!catalogIds.contains(i.get("catalogId_i"))) {
305
				jsonIterator.remove();
306
			}
307
 
308
		}
309
 
310
		model.addAttribute("response1", docA.toString());
311
 
312
		return "response";
313
	}
314
 
25380 amit.gupta 315
	@GetMapping(value = "/content/index")
316
	public String index(HttpServletRequest request, Model model) throws Exception {
33973 tejus.loha 317
 
25380 amit.gupta 318
		return "content";
319
	}
320
 
321
	private List<ContentPojo> readFile(MultipartFile file) throws Exception {
322
		CSVParser parser = new CSVParser(new InputStreamReader(file.getInputStream()), CSVFormat.DEFAULT);
323
		List<CSVRecord> records = parser.getRecords();
324
		if (records.size() < 2) {
325
			parser.close();
326
			throw new ProfitMandiBusinessException("Uploaded File", "", "No records Found");
327
		}
328
		// Remove header
329
		records.remove(0);
330
		List<ContentPojo> returnList = new ArrayList<ContentPojo>();
331
		for (CSVRecord record : records) {
25430 amit.gupta 332
			ContentPojo cp = null;
333
			Long entityId = Long.parseLong(record.get(Entity_Id));
25380 amit.gupta 334
			try {
25430 amit.gupta 335
				cp = mongoClient.getEntityById(entityId);
336
			} catch (Exception e) {
337
			}
338
			try {
339
				if (cp == null) {
340
					cp = new ContentPojo(entityId);
341
				}
25380 amit.gupta 342
				cp.setWarranty(record.get(Warranty));
343
				cp.setKeySpecs(Arrays
344
						.asList(record.get(KeySpec1), record.get(KeySpec2), record.get(KeySpec3), record.get(KeySpec4))
25429 amit.gupta 345
						.stream().filter(x -> x != null && !x.equals("")).collect(Collectors.toList()));
25380 amit.gupta 346
				cp.setPackageContents(Arrays.asList(record.get(Package_Contents).split(",")));
347
				cp.setDetailedSpecs(getDetailedSpecs(record));
348
				returnList.add(cp);
349
			} catch (Exception e) {
350
				continue;
351
			}
352
		}
353
		parser.close();
354
		return returnList;
355
	}
356
 
357
	private List<SpecificationGroup> getDetailedSpecs(CSVRecord record) throws Exception {
358
		List<SpecificationGroup> specificationGroups = new ArrayList<>();
359
		int currentIndex = 8;
360
		while (StringUtils.isNotEmpty(record.get(currentIndex))) {
361
			int start = currentIndex;
362
			List<Specification> specifications = new ArrayList<>();
363
			int begin = 0;
364
			while (begin < 5) {
365
				int specKeyIndex = (begin * 2) + 1;
366
				int specValueIndex = (begin * 2) + 2;
367
 
368
				if (StringUtils.isNotEmpty(record.get(currentIndex + specKeyIndex))
369
						&& StringUtils.isNotEmpty(record.get(currentIndex + specValueIndex))) {
370
					Specification specification = new Specification(record.get(currentIndex + specKeyIndex),
371
							Arrays.asList(record.get(currentIndex + specValueIndex)));
372
					specifications.add(specification);
373
				}
374
				begin++;
375
			}
376
			SpecificationGroup specificationGroup = new SpecificationGroup(record.get(start), specifications);
377
			specificationGroups.add(specificationGroup);
25392 amit.gupta 378
			currentIndex += 11;
25380 amit.gupta 379
		}
380
 
381
		return specificationGroups;
382
	}
383
 
384
	private ChannelSftp setupJsch() throws JSchException {
385
		JSch jsch = new JSch();
33463 amit.gupta 386
		Session jschSession = jsch.getSession("root", "172.105.58.16");
31330 tejbeer 387
		// Session jschSession = jsch.getSession("root", "173.255.254.24");
388
		LOGGER.info("getClass().getResource(\"id_rsa\") {}",
389
				getClass().getClassLoader().getResource("id_rsa").getPath());
29881 amit.gupta 390
		jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
31330 tejbeer 391
		// jschSession.setPassword("spic@2015static0");
25396 amit.gupta 392
		jschSession.setConfig("StrictHostKeyChecking", "no");
25380 amit.gupta 393
		jschSession.connect();
394
		return (ChannelSftp) jschSession.openChannel("sftp");
395
	}
396
 
29900 amit.gupta 397
	private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
25380 amit.gupta 398
		ChannelSftp channelSftp = setupJsch();
399
		channelSftp.connect();
29900 amit.gupta 400
		this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
401
		channelSftp.exit();
402
	}
403
 
404
	private void uploadContentFiles(Map<String, InputStream> fileStreamsMap, int entityId) throws Exception {
405
		ChannelSftp channelSftp = setupJsch();
406
		channelSftp.connect();
25380 amit.gupta 407
		this.folderUpload(channelSftp, fileStreamsMap, REMOTE_DIR, entityId + "");
408
		channelSftp.exit();
409
	}
410
 
411
	private void recursiveFolderUpload(ChannelSftp channelSftp, String sourcePath, String destinationPath)
412
			throws SftpException, FileNotFoundException {
413
 
414
		File sourceFile = new File(sourcePath);
415
		if (sourceFile.isFile()) {
416
 
417
			// copy if it is a file
418
			channelSftp.cd(destinationPath);
419
			if (!sourceFile.getName().startsWith("."))
420
				channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE);
421
 
422
		} else {
423
 
424
			System.out.println("inside else " + sourceFile.getName());
425
			File[] files = sourceFile.listFiles();
426
 
427
			if (files != null && !sourceFile.getName().startsWith(".")) {
428
 
429
				channelSftp.cd(destinationPath);
430
				SftpATTRS attrs = null;
431
 
432
				// check if the directory is already existing
433
				try {
434
					attrs = channelSftp.stat(destinationPath + "/" + sourceFile.getName());
435
				} catch (Exception e) {
436
					System.out.println(destinationPath + "/" + sourceFile.getName() + " not found");
437
				}
438
 
439
				// else create a directory
440
				if (attrs != null) {
441
					System.out.println("Directory exists IsDir=" + attrs.isDir());
442
				} else {
443
					System.out.println("Creating dir " + sourceFile.getName());
444
					channelSftp.mkdir(sourceFile.getName());
445
				}
446
 
447
				for (File f : files) {
448
					recursiveFolderUpload(channelSftp, f.getAbsolutePath(),
449
							destinationPath + "/" + sourceFile.getName());
450
				}
451
 
452
			}
453
		}
454
 
455
	}
456
 
457
	private void folderUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath,
458
			String folderName) throws SftpException, FileNotFoundException {
459
 
460
		channelSftp.cd(destinationPath);
461
		SftpATTRS attrs = null;
462
 
463
		// check if the directory is already existing
464
		try {
465
			attrs = channelSftp.stat(folderName);
466
		} catch (Exception e) {
467
			System.out.println(destinationPath + "/" + folderName + " not found");
468
		}
469
 
470
		// else create a directory
25413 amit.gupta 471
		if (attrs == null) {
472
			channelSftp.mkdir(folderName);
473
			channelSftp.chmod(0755, ".");
25380 amit.gupta 474
		}
475
		channelSftp.cd(folderName);
25413 amit.gupta 476
		channelSftp.rm("*");
25380 amit.gupta 477
 
478
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
479
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
480
		}
481
 
482
	}
483
 
484
	private Map<String, InputStream> getStreamFileMap(ContentPojo contentPojo, EntityMediaPojo entityMediaPojo) {
485
		Map<String, InputStream> map = new HashMap<>();
25401 amit.gupta 486
		LOGGER.info("entityMediaPojo.getMediaPojos() -[{}]", entityMediaPojo.getMediaPojos());
25404 amit.gupta 487
		for (int i = 0; i < entityMediaPojo.getMediaPojos().size(); i++) {
25380 amit.gupta 488
			MediaPojo mediaPojo = entityMediaPojo.getMediaPojos().get(i);
489
			String extension;
490
			String base64String = mediaPojo.getImageData();
491
			String[] strings = base64String.split(",");
492
			switch (strings[0]) {// check image's extension
493
			case "data:image/jpeg;base64":
494
				extension = "jpeg";
495
				break;
496
			case "data:image/png;base64":
497
				extension = "png";
498
				break;
499
			default:// should write cases for more images types
500
				extension = "jpg";
501
				break;
502
			}
25402 amit.gupta 503
			LOGGER.info("After switch statement = {}", extension);
25380 amit.gupta 504
			// convert base64 string to binary data
505
			byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
506
			String fileName = getFileName(entityMediaPojo.getEntityId(), mediaPojo.getTitle(), extension);
25402 amit.gupta 507
			LOGGER.info("After switch statement Filename = {}", fileName);
25380 amit.gupta 508
			mediaPojo.setImageData(null);
25430 amit.gupta 509
			String staticServerUrl = String.format(STATIC_SERVER_URL, entityMediaPojo.getEntityId() % 3);
25414 amit.gupta 510
			mediaPojo.setUrl(staticServerUrl + entityMediaPojo.getEntityId() + "/" + fileName);
25380 amit.gupta 511
			map.put(fileName, new ByteArrayInputStream(data));
512
			if (i == entityMediaPojo.getDefaultImageIndex()) {
513
				String defaultFileName = getFileName(entityMediaPojo.getEntityId(), DEFAULT, extension);
514
				map.put(defaultFileName, new ByteArrayInputStream(data));
25414 amit.gupta 515
				contentPojo.setDefaultImageUrl(staticServerUrl + entityMediaPojo.getEntityId() + "/" + defaultFileName);
25380 amit.gupta 516
			}
517
		}
518
		contentPojo.setImages(entityMediaPojo.getMediaPojos());
519
 
520
		return map;
521
	}
522
 
25409 amit.gupta 523
	private String getMediaPrefix(String productName) {
524
		String mediaPrefix = productName.toLowerCase().replace(' ', '-');
525
		mediaPrefix = mediaPrefix.replaceAll("/", "-");
526
		mediaPrefix = mediaPrefix.replaceAll("-+", "-");
527
		return mediaPrefix;
528
	}
529
 
28264 tejbeer 530
	@GetMapping(value = "/urlGeneration")
531
	public String urlGeneration(HttpServletRequest request, Model model) throws Exception {
532
		return "url-generation";
533
	}
33443 ranu 534
	@Autowired
535
	UserRepository userRepository;
536
	@Autowired
537
	private CookiesProcessor cookiesProcessor;
538
 
539
	@GetMapping(value = "/printResources")
540
	public String printResources(HttpServletRequest request, Model model) throws Exception {
541
		List<Region> regionList = regionRepository.selectAll();
542
		model.addAttribute("regionList", regionList);
543
		return "print-resource";
544
	}
545
 
546
	@RequestMapping(value = "/postPrintResource", method = RequestMethod.POST)
547
	public String postPrintResource(HttpServletRequest request, @RequestBody PrintResourceModel printResourceModel,
548
									Model model) throws Exception {
549
		LOGGER.info("printResourceModel {}", printResourceModel);
550
		PrintResource printResource = new PrintResource();
551
		printResource.setTitle(printResourceModel.getTitle());
552
		printResource.setStartDate(printResourceModel.getStartDate().atStartOfDay());
553
		if (printResourceModel.getEndDate() != null) {
554
			printResource.setEndDate(printResourceModel.getEndDate().atStartOfDay());
555
		} else {
556
			printResource.setEndDate(null);
557
		}
558
 
559
		printResource.setCreateTimestamp(LocalDateTime.now());
560
		printResource.setImgUrl(printResourceModel.getImgUrl());
33501 ranu 561
		printResource.setThumbnailUrl(printResourceModel.getThumbnailUrl());
33443 ranu 562
		printResourceRepository.persist(printResource);
563
 
564
		PrintResourceRegion printResourceRegion = new PrintResourceRegion();
565
		int regionId = Integer.parseInt(printResourceModel.getRegion());
566
		printResourceRegion.setRegionId(regionId);
567
		printResourceRegion.setResourceId(printResource.getId());
568
		printResourceRegionRepository.persist(printResourceRegion);
569
 
570
 
571
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
572
 
573
		return "response";
574
	}
575
 
576
	@RequestMapping(value = "/changeEndDate", method = RequestMethod.POST)
577
	public String changeEndDate(HttpServletRequest request, @RequestParam LocalDate date, @RequestParam int resourceId,
578
								Model model) throws Exception {
579
 
580
		PrintResource printResource = printResourceRepository.selectById(resourceId);
581
		printResource.setEndDate(date.atStartOfDay());
582
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
583
		return "response";
584
	}
585
 
586
	@GetMapping(value = "/partnerPrintResources")
587
	public String partnerPrintResources(HttpServletRequest request, Model model) throws Exception {
588
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
589
		int fofoId = loginDetails.getFofoId();
590
		User user = userRepository.selectById(fofoId);
591
		List<PartnerRegion> partnerRegion = partnerRegionRepository.selectByfofoId(user.getId());
592
		LocalDateTime currentDate = LocalDateTime.now();
593
		List<PrintResource> printResources = printResourceRepository.selectPrintResourcesByFofoRegion(partnerRegion.get(0).getRegionId(), currentDate);
594
		LOGGER.info("printresourcesList {}", printResources);
595
		model.addAttribute("printResources", printResources);
596
		return "partner_print_resource";
597
	}
598
 
599
	@GetMapping(value = "/allPrintResources")
600
	public String allPrintResources(HttpServletRequest request, Model model) throws Exception {
601
		LocalDateTime currentDate = LocalDateTime.now();
602
		List<PrintResource> printResources = printResourceRepository.selectAllPrintResources(currentDate);
603
		model.addAttribute("printResources", printResources);
604
		return "all-print-resource";
605
	}
606
 
25380 amit.gupta 607
}