Subversion Repositories SmartDukaan

Rev

Rev 25402 | Rev 25404 | 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/";
84
	private static final String STATIC_SERVER_URL = "http://static.saholic.com/images/media/";
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 = "";
25400 amit.gupta 90
 
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);
95
		String imageString = items.get(0).getItemDescriptionNoColor() + " " + description + " "
96
				+ LocalDateTime.now().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30));
97
		return imageString.replaceAll("\\s+", " ") + "." + extension;
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);
127
		if(contentPojo==null) {
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
	}
134
 
135
	private EntityMediaPojo getEntityMediaPojo(ContentPojo contentPojo) {
136
		EntityMediaPojo ep = new EntityMediaPojo();
137
		int defaultIndex = 0;
138
		if(contentPojo.getImages()==null) {
139
			ep.setMediaPojos(new ArrayList<>());
140
		} else {
141
			ep.setMediaPojos(contentPojo.getImages());
142
			for (MediaPojo mediaPojo : contentPojo.getImages()) {
25397 amit.gupta 143
				if(mediaPojo.getUrl()==null) continue;
144
 
25380 amit.gupta 145
				if (!mediaPojo.getUrl().equals(contentPojo.getDefaultImageUrl())) {
146
					defaultIndex++;
147
				}
148
			}
149
		}
150
		ep.setDefaultImageIndex(defaultIndex);
151
		return ep;
152
	}
153
 
154
	@GetMapping(value = "/entity")
155
	public String searchEntity(HttpServletRequest request, @RequestParam String query, Model model) throws Exception {
156
		solrService.getContent(query);
157
		model.addAttribute("response", solrService.getContent(query));
158
		return "response";
159
	}
160
 
161
	@GetMapping(value = "/content/index")
162
	public String index(HttpServletRequest request, Model model) throws Exception {
163
		return "content";
164
	}
165
 
166
	private List<ContentPojo> readFile(MultipartFile file) throws Exception {
167
		CSVParser parser = new CSVParser(new InputStreamReader(file.getInputStream()), CSVFormat.DEFAULT);
168
		List<CSVRecord> records = parser.getRecords();
169
		if (records.size() < 2) {
170
			parser.close();
171
			throw new ProfitMandiBusinessException("Uploaded File", "", "No records Found");
172
		}
173
		// Remove header
174
		records.remove(0);
175
		List<ContentPojo> returnList = new ArrayList<ContentPojo>();
176
		for (CSVRecord record : records) {
177
			try {
178
				ContentPojo cp = new ContentPojo(Long.parseLong(record.get(Entity_Id)));
179
				cp.setWarranty(record.get(Warranty));
180
				cp.setKeySpecs(Arrays
181
						.asList(record.get(KeySpec1), record.get(KeySpec2), record.get(KeySpec3), record.get(KeySpec4))
182
						.stream().filter(x -> x == null || x.equals("")).collect(Collectors.toList()));
183
				cp.setPackageContents(Arrays.asList(record.get(Package_Contents).split(",")));
184
				cp.setDetailedSpecs(getDetailedSpecs(record));
185
				returnList.add(cp);
186
			} catch (Exception e) {
187
				continue;
188
			}
189
		}
190
		parser.close();
191
		return returnList;
192
	}
193
 
194
	private List<SpecificationGroup> getDetailedSpecs(CSVRecord record) throws Exception {
195
		List<SpecificationGroup> specificationGroups = new ArrayList<>();
196
		int currentIndex = 8;
197
		while (StringUtils.isNotEmpty(record.get(currentIndex))) {
198
			int start = currentIndex;
199
			List<Specification> specifications = new ArrayList<>();
200
			int begin = 0;
201
			while (begin < 5) {
202
				int specKeyIndex = (begin * 2) + 1;
203
				int specValueIndex = (begin * 2) + 2;
204
 
205
				if (StringUtils.isNotEmpty(record.get(currentIndex + specKeyIndex))
206
						&& StringUtils.isNotEmpty(record.get(currentIndex + specValueIndex))) {
207
					Specification specification = new Specification(record.get(currentIndex + specKeyIndex),
208
							Arrays.asList(record.get(currentIndex + specValueIndex)));
209
					specifications.add(specification);
210
				}
211
				begin++;
212
			}
213
			SpecificationGroup specificationGroup = new SpecificationGroup(record.get(start), specifications);
214
			specificationGroups.add(specificationGroup);
25392 amit.gupta 215
			currentIndex += 11;
25380 amit.gupta 216
		}
217
 
218
		return specificationGroups;
219
	}
220
 
221
	private ChannelSftp setupJsch() throws JSchException {
222
		JSch jsch = new JSch();
223
		jsch.setKnownHosts("/root/.ssh/known_hosts");
224
		Session jschSession = jsch.getSession("root", "192.168.191.71");
25392 amit.gupta 225
		jschSession.setPassword("spic@2015cs");
25396 amit.gupta 226
		jschSession.setConfig("StrictHostKeyChecking", "no");
25380 amit.gupta 227
		jschSession.connect();
228
		return (ChannelSftp) jschSession.openChannel("sftp");
229
	}
230
 
231
	private void uploadFiles(Map<String, InputStream> fileStreamsMap, int entityId) throws Exception {
232
		ChannelSftp channelSftp = setupJsch();
233
		channelSftp.connect();
234
		this.folderUpload(channelSftp, fileStreamsMap, REMOTE_DIR, entityId + "");
235
		channelSftp.exit();
236
	}
237
 
238
	private void recursiveFolderUpload(ChannelSftp channelSftp, String sourcePath, String destinationPath)
239
			throws SftpException, FileNotFoundException {
240
 
241
		File sourceFile = new File(sourcePath);
242
		if (sourceFile.isFile()) {
243
 
244
			// copy if it is a file
245
			channelSftp.cd(destinationPath);
246
			if (!sourceFile.getName().startsWith("."))
247
				channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE);
248
 
249
		} else {
250
 
251
			System.out.println("inside else " + sourceFile.getName());
252
			File[] files = sourceFile.listFiles();
253
 
254
			if (files != null && !sourceFile.getName().startsWith(".")) {
255
 
256
				channelSftp.cd(destinationPath);
257
				SftpATTRS attrs = null;
258
 
259
				// check if the directory is already existing
260
				try {
261
					attrs = channelSftp.stat(destinationPath + "/" + sourceFile.getName());
262
				} catch (Exception e) {
263
					System.out.println(destinationPath + "/" + sourceFile.getName() + " not found");
264
				}
265
 
266
				// else create a directory
267
				if (attrs != null) {
268
					System.out.println("Directory exists IsDir=" + attrs.isDir());
269
				} else {
270
					System.out.println("Creating dir " + sourceFile.getName());
271
					channelSftp.mkdir(sourceFile.getName());
272
				}
273
 
274
				for (File f : files) {
275
					recursiveFolderUpload(channelSftp, f.getAbsolutePath(),
276
							destinationPath + "/" + sourceFile.getName());
277
				}
278
 
279
			}
280
		}
281
 
282
	}
283
 
284
	private void folderUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath,
285
			String folderName) throws SftpException, FileNotFoundException {
286
 
287
		channelSftp.cd(destinationPath);
288
		SftpATTRS attrs = null;
289
 
290
		// check if the directory is already existing
291
		try {
292
			attrs = channelSftp.stat(folderName);
293
		} catch (Exception e) {
294
			System.out.println(destinationPath + "/" + folderName + " not found");
295
		}
296
 
297
		// else create a directory
298
		if (attrs != null) {
299
			channelSftp.rmdir(folderName);
300
		}
301
 
302
		channelSftp.mkdir(folderName);
303
		channelSftp.cd(folderName);
304
		channelSftp.chmod(644, ".");
305
 
306
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
307
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
308
		}
309
 
310
	}
311
 
312
	private Map<String, InputStream> getStreamFileMap(ContentPojo contentPojo, EntityMediaPojo entityMediaPojo) {
313
		Map<String, InputStream> map = new HashMap<>();
25401 amit.gupta 314
		LOGGER.info("entityMediaPojo.getMediaPojos() -[{}]", entityMediaPojo.getMediaPojos());
25380 amit.gupta 315
		for (int i = 0; i > entityMediaPojo.getMediaPojos().size(); i++) {
316
			MediaPojo mediaPojo = entityMediaPojo.getMediaPojos().get(i);
317
			String extension;
318
			String base64String = mediaPojo.getImageData();
319
			String[] strings = base64String.split(",");
320
			switch (strings[0]) {// check image's extension
321
			case "data:image/jpeg;base64":
25403 amit.gupta 322
				LOGGER.info("In Jpeg");
25380 amit.gupta 323
				extension = "jpeg";
324
				break;
325
			case "data:image/png;base64":
25403 amit.gupta 326
				LOGGER.info("In Png");
25380 amit.gupta 327
				extension = "png";
328
				break;
329
			default:// should write cases for more images types
25403 amit.gupta 330
				LOGGER.info("In Default");
25380 amit.gupta 331
				extension = "jpg";
332
				break;
333
			}
25402 amit.gupta 334
			LOGGER.info("After switch statement = {}", extension);
25380 amit.gupta 335
			// convert base64 string to binary data
336
			byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
337
			String fileName = getFileName(entityMediaPojo.getEntityId(), mediaPojo.getTitle(), extension);
25402 amit.gupta 338
			LOGGER.info("After switch statement Filename = {}", fileName);
25380 amit.gupta 339
			mediaPojo.setImageData(null);
25399 amit.gupta 340
			mediaPojo.setUrl(STATIC_SERVER_URL + entityMediaPojo.getEntityId() + "/" + fileName);
25380 amit.gupta 341
			map.put(fileName, new ByteArrayInputStream(data));
342
			if (i == entityMediaPojo.getDefaultImageIndex()) {
343
				String defaultFileName = getFileName(entityMediaPojo.getEntityId(), DEFAULT, extension);
344
				map.put(defaultFileName, new ByteArrayInputStream(data));
25399 amit.gupta 345
				contentPojo.setDefaultImageUrl(STATIC_SERVER_URL + entityMediaPojo.getEntityId() + "/" + fileName);
25380 amit.gupta 346
			}
347
		}
348
		contentPojo.setImages(entityMediaPojo.getMediaPojos());
349
 
350
		return map;
351
	}
352
 
353
}