Subversion Repositories SmartDukaan

Rev

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