Subversion Repositories SmartDukaan

Rev

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