Subversion Repositories SmartDukaan

Rev

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