Subversion Repositories SmartDukaan

Rev

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