Subversion Repositories SmartDukaan

Rev

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