Subversion Repositories SmartDukaan

Rev

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