Subversion Repositories SmartDukaan

Rev

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