Subversion Repositories SmartDukaan

Rev

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