public class LoginController extends BaseController {
// 我的订阅词
@Value("${mysubscription.words}")
private String mysubscriptionWords;
@Autowired
private LoginService loginService;
@Autowired
private SubscriptionService subscriptionService;
@Autowired
private UserMappingService userMappingService;
@RequestMapping(value = "/user/index.htm")
public String index() {
return "subscription";
}
@RequestMapping(value = "/user/login.htm", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> login(HttpServletRequest request, HttpServletResponse response, HttpSession session,
String userName, String password) {
Map<String, String> result = new HashMap<String, String>();
result.put(Constant.RESULT, Constant.FAIL);
if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
result.put(Constant.MSG, "邮箱或密码不能为空!");
return result;
}
if (!loginService.isExistUser(userName)) {
result.put(Constant.MSG, "登陆邮箱不存在,请先注册!");
return result;
}
User user = loginService.getUser(userName, Base64Utils.encode(password));
if (user != null) {
session.setAttribute(Constant.USER, user);
// session过期时间30分钟
session.setMaxInactiveInterval(30 * 60);
result.put(Constant.RESULT, Constant.SUCCESS);
addUserMapping(request, response, user.getId());
return result;
} else {
result.put(Constant.MSG, "邮箱或密码输入错误!");
return result;
}
}
@RequestMapping(value = "/user/logout.htm", method = RequestMethod.GET)
public String logout(HttpSession session) {
User user = (User) session.getAttribute(Constant.USER);
if (user == null) {
return "redirect:/news/finance.htm";
}
session.removeAttribute(Constant.USER);
return "redirect:/news/finance.htm";
}
@RequestMapping(value = "/user/toregister.htm")
public String toregister() {
return "register";
}
@RequestMapping(value = "/user/register.htm", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> register(HttpSession session, HttpServletRequest request, HttpServletResponse response,
User user) {
Map<String, String> result = new HashMap<String, String>();
result.put(Constant.RESULT, Constant.FAIL);
if (user == null) {
return result;
}
if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())) {
result.put(Constant.MSG, "邮箱或密码不能为空!");
return result;
}
if (loginService.isExistUser(user.getUserName())) {
result.put(Constant.MSG, "邮箱已注册!");
return result;
}
user.setPassword(Base64Utils.encode(user.getPassword()));
user.setCreateTime(new Date());
loginService.addUser(user);
// 注册成功后马上登陆
session.setAttribute(Constant.USER, user);
// session过期时间30分钟
session.setMaxInactiveInterval(30 * 60);
// addDefaultSubscription(user.getId());
result.put(Constant.RESULT, Constant.SUCCESS);
addUserMapping(request, response, user.getId());
return result;
}
/**
* 注册成功初始化默认订阅词
*
* @param userId
*/
private void addDefaultSubscription(int userId) {
if (!StringUtils.isEmpty(mysubscriptionWords)) {
if (mysubscriptionWords.indexOf(",") != -1) {
String[] words = mysubscriptionWords.split(",");
for (int i = 0, len = words.length; i < len; i++) {
Subscription subscription = new Subscription();
subscription.setKeyWord(words[i]);
subscription.setUserId(userId);
subscription.setCreateTime(new Date());
subscriptionService.addSubscription(subscription);
}
}
}
}
/**
* 维护UserMapping表
*
* @param request
* @param response
* @param userId
*/
private void addUserMapping(HttpServletRequest request, HttpServletResponse response, int LoginId) {
Cookie loginID = new Cookie("loginID", String.valueOf(LoginId));
loginID.setMaxAge(30 * 60); // set expire time,秒
loginID.setPath("/");
response.addCookie(loginID); // put cookie in response
Cookie cookies[] = request.getCookies();
String userID = "";
if (cookies != null && cookies.length > 0) {
for (int i = 0, len = cookies.length; i < len; i++) {
if ("userID".equals(cookies[i].getName())) {
userID = cookies[i].getValue();
break;
}
}
UserMapping userMapping = new UserMapping();
userMapping.setLoginId(LoginId);
userMapping.setUserId(userID);
userMapping.setCreateTime(new Date());
userMappingService.addUserMapping(userMapping);
}
}
}
@Controller
public class SubscriptionController {
@Value("${search.url}")
private String searchUrl;
@Value("${sendEmail.url}")
private String sendEmailUrl;
// 推荐订阅词
@Value("${subscription.keywords}")
private String subscriptionKeyWords;
@Autowired
private SubscriptionService subscriptionService;
@Autowired
private CrawlerStockBaseService crawlerStockBaseService;
@Autowired
private FavoriteService favoriteService;
@RequestMapping(value = "/news/subscription.htm")
public String subscription(HttpSession session, Model model) {
User user = (User) session.getAttribute(Constant.USER);
if (user != null) {
model.addAttribute("subList", subscriptionService.findListSubscriptionByUserId(user.getId()));
// model.addAttribute("subKeyWords", getSubscriptionKeyWord());
}
return "subscription";
}
@RequestMapping(value = "/my/subscriptionList.htm")
public String subscriptionList(HttpSession session, String searchText, int pageIndex, int pageSize, Model model)
throws Exception {
User user = (User) session.getAttribute(Constant.USER);
Integer userId = null;
if (user == null) {
return "subscription";
} else {
userId = user.getId();
}
if (StringUtils.isNotEmpty(searchText)) {
Map<String, Object> requestMap = new HashMap<String, Object>();
// requestMap.put("t", "01");
requestMap.put("q", searchText);
requestMap.put("n", pageSize);
requestMap.put("p", pageIndex);
String str = HttpServiceUtils.postRequest(searchUrl, requestMap);
SearchInfoVo searchInfoVo = JsonUtil.String2Object(str, SearchInfoVo.class);
if (searchInfoVo != null && searchInfoVo.getRetCode() == 0) {
List<SearchVo> newList = new ArrayList<SearchVo>();
if (searchInfoVo.getTotal() > 0) {
loadStockList(userId, searchInfoVo.getItems());
newList = searchInfoVo.getItems();
}
// 组装搜索页对象
SearchInfoPage searchInfoPage = new SearchInfoPage();
// 组装数据
Pagination<SearchVo> pagination = PagerFactory.createEmpty();
pagination = PagerFactory.create(pageIndex, pageSize, searchInfoVo.getTotal(), newList);
searchInfoPage.setPagination(pagination);
searchInfoPage.setSubFlag(getIsSubscription(user.getId(), searchText));
model.addAttribute("newList", searchInfoPage);
}
}
return "subscriptionList";
}
@RequestMapping(value = "/my/addSubWord.htm")
@ResponseBody
public Map<String, String> addSubWord(HttpSession session, @RequestParam(value = "channelId", required = false)
String channelId, @RequestParam(value = "keyWord", required = false)
String keyWord, Integer sendTime) {
Map<String, String> result = new HashMap<String, String>();
result.put(Constant.RESULT, Constant.FAIL);
User user = (User) session.getAttribute(Constant.USER);
if (user == null) {
return result;
}
// 分类新闻订阅
if (channelId != null) {
if (subscriptionService.isExistSubChannel(user.getId(), channelId)) {
result.put(Constant.MSG, "该新闻频道已经被订阅!");
return result;
}
Subscription subscription = new Subscription();
subscription.setUserId(user.getId());
subscription.setCreateTime(new Date());
subscription.setSendTime(sendTime);
subscription.setEmail(user.getUserName());
subscription.setChannelId(channelId);
subscriptionService.addSubscription(subscription);
}
// 关键词订阅
else {
if (StringUtils.isEmpty(keyWord)) {
result.put(Constant.MSG, "订阅词为空!");
return result;
}
if (subscriptionService.isExistSubWord(user.getId(), keyWord)) {
result.put(Constant.MSG, "该关键词已被订阅,请更换其他关键词!");
return result;
}
Subscription subscription = new Subscription();
subscription.setKeyWord(keyWord);
subscription.setUserId(user.getId());
subscription.setCreateTime(new Date());
subscription.setSendTime(sendTime);
subscription.setEmail(user.getUserName());
subscriptionService.addSubscription(subscription);
// 即时发送
if (sendTime == 24) {
SendEmailRunnable runnble = new SendEmailRunnable(sendEmailUrl, subscription.getKeyWord(),
subscription.getUserId(), subscription.getEmail());
Thread thread = new Thread(runnble);
thread.start();
}
}
result.put(Constant.RESULT, Constant.SUCCESS);
return result;
}
@RequestMapping(value = "/my/editSubWord.htm")
@ResponseBody
public Map<String, String> editSubWord(HttpSession session, Integer id, Integer sendTime) {
Map<String, String> result = new HashMap<String, String>();
result.put(Constant.RESULT, Constant.FAIL);
if (id == null) {
result.put(Constant.MSG, "订阅Id为空!");
return result;
}
if (sendTime == null) {
result.put(Constant.MSG, "发送时间为空!");
return result;
}
Subscription subscription = subscriptionService.getSubscriptionById(id);
if (subscription != null) {
subscription.setSendTime(sendTime);
subscriptionService.editSubscription(subscription);
}
// 即时发送
if (subscription != null && StringUtils.isEmpty(subscription.getChannelId()) && sendTime == 24) {
SendEmailRunnable runnble = new SendEmailRunnable(sendEmailUrl, subscription.getKeyWord(),
subscription.getUserId(), subscription.getEmail());
Thread thread = new Thread(runnble);
thread.start();
}
result.put(Constant.RESULT, Constant.SUCCESS);
return result;
}
@RequestMapping(value = "/my/delSubWord.htm")
@ResponseBody
public Map<String, String> delSubWord(HttpSession session, String ids) {
Map<String, String> result = new HashMap<String, String>();
result.put(Constant.RESULT, Constant.FAIL);
if (StringUtils.isEmpty(ids)) {
return result;
}
User user = (User) session.getAttribute(Constant.USER);
if (user == null) {
return result;
}
String[] uIds = ids.split(",");
if (null == uIds || uIds.length < 1) {
return result;
}
for (int i = 0; i < uIds.length; i++) {
subscriptionService.deleteSubscriptionById(Integer.parseInt(uIds[i]));
}
result.put(Constant.RESULT, Constant.SUCCESS);
return result;
}
private List<String> getSubscriptionKeyWord() {
List<String> result = new ArrayList<String>();
if (!StringUtils.isEmpty(subscriptionKeyWords)) {
if (subscriptionKeyWords.indexOf(",") != -1) {
String[] words = subscriptionKeyWords.split(",");
for (int i = 0, len = words.length; i < len; i++) {
result.add(words[i]);
}
}
}
return result;
}
private boolean getIsSubscription(int userId, String searchText) {
return subscriptionService.isExistSubWord(userId, searchText);
}
private void loadStockList(Integer userId, List<SearchVo> items) throws Exception {
if (items != null && !items.isEmpty()) {
for (SearchVo vo : items) {
if (userId == null) {
vo.setFavStatus("0");// 未登陆
} else {
Favorite favorite = favoriteService.getFavorite(userId, Integer.parseInt(vo.getId()));
if (favorite != null) {
vo.setFavStatus("1");// 已收藏
} else {
vo.setFavStatus("2");// 未收藏
}
}
List<String> snList = vo.getStock_names();
if (snList != null && !snList.isEmpty()) {
List<StockVo> stockList = new ArrayList<StockVo>();
for (String name : snList) {
if (!StringUtils.isEmpty(name)) {
StockVo stockVo = new StockVo();
stockVo.setName(name);
stockVo.setEncodeName(URLEncoder.encode(name, "UTF-8"));
CrawlerStockBase crawlerStockBase = crawlerStockBaseService.getCrawlerStockBaseByName(name);
if (crawlerStockBase != null) {
stockVo.setSymbol(crawlerStockBase.getSymbol());
}
stockList.add(stockVo);
}
}
vo.setStockList(stockList);
}
}
}
}
}
@Controller
public class NewsController {
@Value("${search.url}")
private String searchUrl;
@Autowired
private NewsService newsService;
@Autowired
private SubscriptionService subscriptionService;
@Autowired
private FavoriteService favoriteService;
@Autowired
private CrawlerStockBaseService crawlerStockBaseService;
@RequestMapping(value = "/news/{id}/newsDetail.htm")
public String newsDetail(HttpSession session, @PathVariable
Integer id, Model model) {
if (id != null) {
News news = newsService.getNewsById(id);
if (news != null) {
model.addAttribute("news", news);
String favStatus = "0";
User user = (User) session.getAttribute(Constant.USER);
if (user != null) {
Favorite favorite = favoriteService.hasFavorite(user.getId(), id);
if (favorite != null) {
favStatus = "1";// 已收藏
model.addAttribute("favId", favorite.getId());
} else {
favStatus = "2";// 未收藏
}
}
model.addAttribute("favStatus", favStatus);
}
}
return "newsDetail";
}
@RequestMapping(value = "/news/{id}/newsDetail_mobile.htm")
public String newsDetail_mobile(@PathVariable
Integer id, Model model) {
if (id != null) {
News news = newsService.getNewsById(id);
if (news != null) {
model.addAttribute("news", news);
}
}
return "newsDetail_mobile";
}
@RequestMapping(value = "/news/searchList.htm")
public String searchList(HttpSession session, String searchText, @RequestParam(value = "s_type", required = false)
String s_type, @RequestParam(value = "pageIndex", required = false)
Integer pageIndex, @RequestParam(value = "pageSize", required = false)
Integer pageSize, Model model) throws Exception {
if (pageIndex == null) {
pageIndex = 1;
}
if (pageSize == null) {
pageSize = 10;
}
User user = (User) session.getAttribute(Constant.USER);
Integer userId = null;
if (user != null) {
userId = user.getId();
}
if (StringUtils.isNotEmpty(searchText)) {
Map<String, Object> requestMap = new HashMap<String, Object>();
if (StringUtils.isNotEmpty(s_type)) {
requestMap.put("t", s_type);
}
requestMap.put("q", searchText);
requestMap.put("n", pageSize);
requestMap.put("p", pageIndex);
String str = HttpServiceUtils.postRequest(searchUrl, requestMap);
SearchInfoVo searchInfoVo = JsonUtil.String2Object(str, SearchInfoVo.class);
if (searchInfoVo != null && searchInfoVo.getRetCode() == 0) {
List<SearchVo> newList = new ArrayList<SearchVo>();
if (searchInfoVo.getTotal() > 0) {
loadStockList(userId, searchInfoVo.getItems());
newList = searchInfoVo.getItems();
}
// 组装搜索页对象
SearchInfoPage searchInfoPage = new SearchInfoPage();
searchInfoPage.setTid(searchInfoVo.getTid());
// 组装数据
Pagination<SearchVo> pagination = PagerFactory.createEmpty();
pagination = PagerFactory.create(pageIndex, pageSize, searchInfoVo.getTotal(), newList);
searchInfoPage.setPagination(pagination);
if (user != null) {
searchInfoPage.setSubFlag(getIsSubscription(user.getId(), searchText));
}
model.addAttribute("newList", searchInfoPage);
}
}
return "searchList";
}
@RequestMapping(value = "/news/guba.htm")
public String guba(HttpSession session, String searchText, @RequestParam(value = "pageIndex", required = false)
Integer pageIndex, @RequestParam(value = "pageSize", required = false)
Integer pageSize, Model model) throws Exception {
if (pageIndex == null) {
pageIndex = 1;
}
if (pageSize == null) {
pageSize = 10;
}
if (StringUtils.isNotEmpty(searchText)) {
Map<String, Object> requestMap = new HashMap<String, Object>();
requestMap.put("t", "02");
requestMap.put("q", searchText);
requestMap.put("n", pageSize);
requestMap.put("p", pageIndex);
String str = HttpServiceUtils.postRequest(searchUrl, requestMap);
SearchInfoVo searchInfoVo = JsonUtil.String2Object(str, SearchInfoVo.class);
if (searchInfoVo != null && searchInfoVo.getRetCode() == 0) {
List<SearchVo> newList = new ArrayList<SearchVo>();
if (searchInfoVo.getTotal() > 0) {
newList = searchInfoVo.getItems();
}
// 组装搜索页对象
SearchInfoPage searchInfoPage = new SearchInfoPage();
searchInfoPage.setTid(searchInfoVo.getTid());
// 组装数据
Pagination<SearchVo> pagination = PagerFactory.createEmpty();
pagination = PagerFactory.create(pageIndex, pageSize, searchInfoVo.getTotal(), newList);
searchInfoPage.setPagination(pagination);
User user = (User) session.getAttribute(Constant.USER);
if (user != null) {
searchInfoPage.setSubFlag(getIsSubscription(user.getId(), searchText));
}
model.addAttribute("newList", searchInfoPage);
}
}
return "guba";
}
private boolean getIsSubscription(int userId, String searchText) {
return subscriptionService.isExistSubWord(userId, searchText);
}
private void loadStockList(Integer userId, List<SearchVo> items) throws Exception {
if (items != null && !items.isEmpty()) {
for (SearchVo vo : items) {
if (userId == null) {
vo.setFavStatus("0");// 未登陆
} else {
Favorite favorite = favoriteService.getFavorite(userId, Integer.parseInt(vo.getId()));
if (favorite != null) {
vo.setFavStatus("1");// 已收藏
} else {
vo.setFavStatus("2");// 未收藏
}
}
List<String> snList = vo.getStock_names();
if (snList != null && !snList.isEmpty()) {
List<StockVo> stockList = new ArrayList<StockVo>();
for (String name : snList) {
if (!StringUtils.isEmpty(name)) {
StockVo stockVo = new StockVo();
stockVo.setName(name);
stockVo.setEncodeName(URLEncoder.encode(name, "UTF-8"));
CrawlerStockBase crawlerStockBase = crawlerStockBaseService.getCrawlerStockBaseByName(name);
if (crawlerStockBase != null) {
stockVo.setSymbol(crawlerStockBase.getSymbol());
}
stockList.add(stockVo);
}
}
vo.setStockList(stockList);
}
}
}
}
}
@Controller
public class RecommendController {
@Autowired
private RecommendService recommendService;
@RequestMapping(value = "/news/finance.htm")
public String recommend(HttpSession session, String publishCode,
@RequestParam(value = "channelID", required = false)
String channelID, Integer pageIndex, Integer pageSize, Model model) throws Exception {
if (pageIndex == null) {
pageIndex = 1;
}
if (pageSize == null) {
pageSize = 10;
}
if (StringUtils.isEmpty(publishCode)) {
publishCode = DatesUtil.getCurrentPublishCode();
}
if (StringUtils.isEmpty(channelID)) {
channelID = "01";
}
Integer userId = null;
User user = (User) session.getAttribute(Constant.USER);
if (user != null) {
userId = user.getId();
}
model.addAttribute("recommendList",
recommendService.findRecommendNew(userId, publishCode, channelID, pageIndex, pageSize));
return "finance";
}
@RequestMapping(value = "/news/technology.htm")
public String technology(HttpSession session, String publishCode,
@RequestParam(value = "channelID", required = false)
String channelID, Integer pageIndex, Integer pageSize, Model model) throws Exception {
if (pageIndex == null) {
pageIndex = 1;
}
if (pageSize == null) {
pageSize = 10;
}
if (StringUtils.isEmpty(publishCode)) {
publishCode = DatesUtil.getCurrentPublishCode();
}
if (StringUtils.isEmpty(channelID)) {
channelID = "02";
}
Integer userId = null;
User user = (User) session.getAttribute(Constant.USER);
if (user != null) {
userId = user.getId();
}
model.addAttribute("recommendList",
recommendService.findRecommendNew(userId, publishCode, channelID, pageIndex, pageSize));
return "technology";
}
@RequestMapping(value = "/news/finance_mobile.htm")
public String recommend_mobile(String publishCode, @RequestParam(value = "channelID", required = false)
String channelID, Integer pageIndex, Integer pageSize, Model model) {
if (pageIndex == null) {
pageIndex = 1;
}
if (pageSize == null) {
pageSize = 5;
}
if (StringUtils.isEmpty(publishCode)) {
publishCode = DatesUtil.getCurrentPublishCode();
}
if (StringUtils.isEmpty(channelID)) {
channelID = "01";
}
Pagination<RecommendVo> pagin = recommendService.findRecommendVo(publishCode, channelID, pageIndex, pageSize);
model.addAttribute("recommendList", pagin);
if (pagin != null && !pagin.getItems().isEmpty()) {
model.addAttribute("main", pagin.getItems().get(0));
}
return "finance_mobile";
}
}
@Controller
public class OpenController extends BaseController {
@Value("${search.url}")
private String searchUrl;
@Value("${sendEmail.url}")
private String sendEmailUrl;
@Autowired
private RecommendService recommendService;
@Autowired
private NewsService newsService;
@Autowired
private SubscriptionService subscriptionService;
private NumberFormat format = NumberFormat.getPercentInstance();// 获取格式化类实例
@RequestMapping(value = "/op/getRecommendList.htm")
@ResponseBody
public Pagination<Recommend> findRecommend(@RequestParam(value = "publishCode", required = false)
String publishCode, @RequestParam(value = "channelID", required = false)
String channelID, @RequestParam(value = "pageIndex", required = false)
Integer pageIndex, @RequestParam(value = "pageSize", required = false)
Integer pageSize) {
if (pageIndex == null) {
pageIndex = 1;
}
if (pageSize == null) {
pageSize = 10;
}
if (StringUtils.isEmpty(publishCode)) {
publishCode = DatesUtil.getCurrentPublishCode();
}
if (StringUtils.isEmpty(channelID)) {
channelID = "01";
}
return recommendService.findRecommend(publishCode, channelID, pageIndex, pageSize);
}
/*
* @RequestMapping(value = "/op/getSubscriptionList.htm")
*
* @ResponseBody public SearchInfoPage findSubscriptionNewsList(String
* searchText, Integer userId, String channelId,
*
* @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
*
* @RequestParam(value = "pageSize", required = false) Integer pageSize)
* throws Exception { if (StringUtils.isEmpty(searchText) || userId == null)
* { return null; } if (pageIndex == null) { pageIndex = 1; } if (pageSize
* == null) { pageSize = 10; } SearchInfoPage searchInfoPage = new
* SearchInfoPage(); Map<String, Object> requestMap = new HashMap<String,
* Object>(); if (!StringUtils.isEmpty(channelId)) { requestMap.put("t",
* channelId); } requestMap.put("q", searchText); requestMap.put("n",
* pageSize); requestMap.put("p", pageIndex); String str =
* HttpServiceUtils.postRequest(searchUrl, requestMap); SearchInfoVo
* searchInfoVo = JsonUtil.String2Object(str, SearchInfoVo.class); if
* (searchInfoVo != null && searchInfoVo.getRetCode() == 0) { List<SearchVo>
* newList = new ArrayList<SearchVo>(); if (searchInfoVo.getTotal() > 0) {
* newList = searchInfoVo.getItems(); }
* searchInfoPage.setTid(searchInfoVo.getTid()); // 组装数据
* Pagination<SearchVo> pagination = PagerFactory.createEmpty(); pagination
* = PagerFactory.create(pageIndex, pageSize, searchInfoVo.getTotal(),
* newList); searchInfoPage.setPagination(pagination);
* searchInfoPage.setSubFlag(getIsSubscription(userId, searchText)); }
* return searchInfoPage; }
*/
@RequestMapping(value = "/op/getSearchList.htm")
@ResponseBody
public SearchInfoPage findSearchList(@RequestParam(value = "searchText", required = false)
String searchText, String channelId, @RequestParam(value = "pageIndex", required = false)
Integer pageIndex, @RequestParam(value = "pageSize", required = false)
Integer pageSize) throws Exception {
if (pageIndex == null) {
pageIndex = 1;
}
if (pageSize == null) {
pageSize = 10;
}
SearchInfoPage searchInfoPage = new SearchInfoPage();
Map<String, Object> requestMap = new HashMap<String, Object>();
if (!StringUtils.isEmpty(channelId)) {
requestMap.put("t", channelId);
}
requestMap.put("q", searchText);
requestMap.put("n", pageSize);
requestMap.put("p", pageIndex);
String str = HttpServiceUtils.postRequest(searchUrl, requestMap);
SearchInfoVo searchInfoVo = JsonUtil.String2Object(str, SearchInfoVo.class);
if (searchInfoVo != null && searchInfoVo.getRetCode() == 0) {
List<SearchVo> newList = new ArrayList<SearchVo>();
if (searchInfoVo.getTotal() > 0) {
newList = searchInfoVo.getItems();
}
searchInfoPage.setTid(searchInfoVo.getTid());
// 组装数据
Pagination<SearchVo> pagination = PagerFactory.createEmpty();
pagination = PagerFactory.create(pageIndex, pageSize, searchInfoVo.getTotal(), newList);
searchInfoPage.setPagination(pagination);
}
return searchInfoPage;
}
@RequestMapping(value = "/op/getDetail.htm")
@ResponseBody
public News getDetail(Integer id) {
if (id == null) {
return null;
}
News news = newsService.getNewsById(id);
return news;
}
/*
* @RequestMapping(value = "/op/getUserSubscriptionList.htm")
*
* @ResponseBody public List<Subscription> findSubscriptionList(Integer
* userId) { if (userId == null) { return null; } return
* subscriptionService.findListSubscriptionByUserId(userId); }
*
* @RequestMapping(value = "/op/addSubWord.htm")
*
* @ResponseBody public Map<String, String> addSubWord(HttpSession session,
*
* @RequestParam(value = "channelId", required = false) String channelId,
*
* @RequestParam(value = "keyWord", required = false) String keyWord,
* Integer sendTime) { Map<String, String> result = new HashMap<String,
* String>(); result.put(Constant.RESULT, Constant.FAIL); User user = (User)
* session.getAttribute(Constant.USER); if (user == null) { return result; }
* // 分类新闻订阅 if (channelId != null) { if
* (subscriptionService.isExistSubChannel(user.getId(), channelId)) {
* result.put(Constant.MSG, "该新闻频道已经被订阅!"); return result; } Subscription
* subscription = new Subscription(); subscription.setUserId(user.getId());
* subscription.setCreateTime(new Date());
* subscription.setSendTime(sendTime);
* subscription.setEmail(user.getUserName());
* subscription.setChannelId(channelId);
* subscriptionService.addSubscription(subscription); } // 关键词订阅 else { if
* (StringUtils.isEmpty(keyWord)) { result.put(Constant.MSG, "订阅词为空!");
* return result; } if (subscriptionService.isExistSubWord(user.getId(),
* keyWord)) { result.put(Constant.MSG, "该关键词已被订阅,请更换其他关键词!"); return
* result; } Subscription subscription = new Subscription();
* subscription.setKeyWord(keyWord); subscription.setUserId(user.getId());
* subscription.setCreateTime(new Date());
* subscription.setSendTime(sendTime);
* subscription.setEmail(user.getUserName());
* subscriptionService.addSubscription(subscription); // 即时发送 if (sendTime
* == 24) { SendEmailRunnable runnble = new SendEmailRunnable(sendEmailUrl,
* subscription.getKeyWord(), subscription.getUserId(),
* subscription.getEmail()); Thread thread = new Thread(runnble);
* thread.start(); } } result.put(Constant.RESULT, Constant.SUCCESS); return
* result; }
*/
/*
* @RequestMapping(value = "/op/editSubWord.htm")
*
* @ResponseBody public Map<String, String> editSubWord(HttpSession session,
* Integer id, Integer sendTime) { Map<String, String> result = new
* HashMap<String, String>(); result.put(Constant.RESULT, Constant.FAIL); if
* (id == null) { result.put(Constant.MSG, "订阅Id为空!"); return result; } if
* (sendTime == null) { result.put(Constant.MSG, "发送时间为空!"); return result;
* } Subscription subscription =
* subscriptionService.getSubscriptionById(id); if (subscription != null) {
* subscription.setSendTime(sendTime);
* subscriptionService.editSubscription(subscription); } // 即时发送 if
* (subscription != null && StringUtils.isEmpty(subscription.getChannelId())
* && sendTime == 24) { SendEmailRunnable runnble = new
* SendEmailRunnable(sendEmailUrl, subscription.getKeyWord(),
* subscription.getUserId(), subscription.getEmail()); Thread thread = new
* Thread(runnble); thread.start(); } result.put(Constant.RESULT,
* Constant.SUCCESS); return result; }
*/
/*
* @RequestMapping(value = "/op/delSubWord.htm")
*
* @ResponseBody public Map<String, String> delSubWord(HttpSession session,
* String ids) { Map<String, String> result = new HashMap<String, String>();
* result.put(Constant.RESULT, Constant.FAIL); if (StringUtils.isEmpty(ids))
* { return result; } User user = (User)
* session.getAttribute(Constant.USER); if (user == null) { return result; }
* String[] uIds = ids.split(","); if (null == uIds || uIds.length < 1) {
* return result; } for (int i = 0; i < uIds.length; i++) {
* subscriptionService.deleteSubscriptionById(Integer.parseInt(uIds[i])); }
* result.put(Constant.RESULT, Constant.SUCCESS); return result; }
*/
@RequestMapping(value = "/op/getStock.htm")
@ResponseBody
public List<StockInfoVo> getStock(String symbol) throws Exception {
// SendURLUtil.sendURL("http://qt.gtimg.cn/q=" + symbol,
// "gb2312");
List<StockInfoVo> list = new ArrayList<StockInfoVo>();
String returnStr = SendURLUtil.sendURL("http://hq.sinajs.cn/list=" + symbol, "gbk");
if (returnStr == null) {
return list;
}
String[] source = returnStr.split(";");
for (int i = 0, len = source.length; i < len; i++) {
if (source[i] != null) {
int start = source[i].indexOf('\"');
String targetString = source[i].substring(start + 1, source[i].length() - 1);
String[] infoStr = targetString.split(",");
if (infoStr.length > 4) {
float mNowPrice = Float.parseFloat(infoStr[3]);
float yestodayPrice = Float.parseFloat(infoStr[2]);
format.setMinimumFractionDigits(2);// 设置小数位
StockInfoVo vo = new StockInfoVo();
vo.setName(infoStr[0]);
vo.setNowPrice(infoStr[3]);
if (mNowPrice == 0.00) {
vo.setPriceRange("0.00%");
} else {
vo.setPriceRange(format.format((mNowPrice - yestodayPrice) / yestodayPrice));
}
list.add(vo);
}
}
}
return list;
}
/*
* private boolean getIsSubscription(int userId, String searchText) { return
* subscriptionService.isExistSubWord(userId, searchText); }
*/
}
@Controller
public class WxController {
@Autowired
private NewsService newsService;
@Autowired
private WxMpService wxMpService;
@Autowired
private AttentionService attentionService;
@RequestMapping(value = "/news/wxServlet.htm")
public String wxServlet(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 微信加密签名
String signature = request.getParameter("signature");
// 时间戳
String timestamp = request.getParameter("timestamp");
// 随机数
String nonce = request.getParameter("nonce");
// 随机字符串
String echostr = request.getParameter("echostr");
PrintWriter out = response.getWriter();
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
out.print(echostr);
}
out.close();
return "wxServlet";
}
@RequestMapping(value = "/news/wx.htm")
public String wx(HttpSession session, String wid, String type, Integer pageIndex, Integer pageSize, Model model)
throws Exception {
if (pageIndex == null) {
pageIndex = 1;
}
if (pageSize == null) {
pageSize = 10;
}
Integer userId = null;
User user = (User) session.getAttribute(Constant.USER);
if (user != null) {
userId = user.getId();
model.addAttribute("leftCjList", wxMpService.findListWxMpByUserIdAndType(userId, "财经"));
model.addAttribute("leftLcList", wxMpService.findListWxMpByUserIdAndType(userId, "理财"));
model.addAttribute("leftKjList", wxMpService.findListWxMpByUserIdAndType(userId, "科技"));
}
model.addAttribute("newList", newsService.findWxNews(userId, wid, type, pageIndex, pageSize));
model.addAttribute("cjList", wxMpService.findListWxMpByType("财经"));
model.addAttribute("lcList", wxMpService.findListWxMpByType("理财"));
model.addAttribute("kjList", wxMpService.findListWxMpByType("科技"));
return "wx";
}
@RequestMapping(value = "/news/addAttention.htm")
@ResponseBody
public Map<String, String> attention(HttpSession session, String wids) {
Map<String, String> result = new HashMap<String, String>();
result.put(Constant.RESULT, Constant.FAIL);
User user = (User) session.getAttribute(Constant.USER);
if (user == null) {
result.put(Constant.MSG, "登陆超时或未登陆!");
return result;
}
if (wids == null) {
result.put(Constant.MSG, "参数错误!");
return result;
}
attentionService.delAttention(user.getId());
String[] wIds = wids.split(",");
if (null == wIds || wIds.length < 1) {
result.put(Constant.MSG, "参数错误!");
return result;
}
List<String> list = Arrays.asList(wIds);
attentionService.addAttention(user.getId(), list);
result.put(Constant.RESULT, Constant.SUCCESS);
return result;
}
@RequestMapping(value = "/my/getAttentionList.htm")
@ResponseBody
public List<Attention> getAttentionList(HttpSession session) {
User user = (User) session.getAttribute(Constant.USER);
if (user == null) {
return null;
}
return attentionService.findAttentionList(user.getId());
}
}
@Controller
public class PushController {
private static final Logger log = LoggerFactory.getLogger(PushController.class);
@Autowired
private FavoriteService favoriteService;
@Autowired
private NewsService newsService;
@Autowired
private MaterialService materialService;
@Autowired
private WxAccountService wxAccountService;
@RequestMapping(value = "/news/pushManager.htm")
public String pushManager(HttpSession session, Model model, Integer pageIndex, Integer pageSize) {
User user = (User) session.getAttribute(Constant.USER);
if (user != null) {
if (pageIndex == null) {
pageIndex = 1;
}
if (pageSize == null) {
pageSize = 6;
}
model.addAttribute("materialList", materialService.findMaterial(user.getId(), pageIndex, pageSize));
}
return "pushManager";
}
@RequestMapping(value = "/my/favorities.htm")
public String favorities(HttpSession session, Model model, Integer pageIndex, Integer pageSize) {
User user = (User) session.getAttribute(Constant.USER);
if (user != null) {
if (pageIndex == null) {
pageIndex = 1;
}
if (pageSize == null) {
pageSize = 10;
}
model.addAttribute("favoritiesList", favoriteService.findFavorite(user.getId(), pageIndex, pageSize));
}
return "favorities";
}
@RequestMapping(value = "/my/addfavorites.htm")
public String addfavorites(String ids, Model model) {
if (!StringUtils.isEmpty(ids)) {
if (ids.indexOf(",") != -1) {
List<News> list = new ArrayList<News>();
String[] org_ids = ids.split(",");
for (int i = 0, len = org_ids.length; i < len; i++) {
if (!StringUtils.isEmpty(org_ids[i])) {
// News news =
// newsService.getNewsById(Integer.parseInt(org_ids[i]));
News news = newsService.getNewsById_s(org_ids[i]);
if (news != null) {
list.add(news);
}
}
}
model.addAttribute("favoriteList", list);
}
}
return "addfavorites";
}
@RequestMapping(value = "/my/addFavorite.htm")
@ResponseBody
public Map<String, String> addFavorite(HttpSession session, String id) {
Map<String, String> result = new HashMap<String, String>();
User user = (User) session.getAttribute(Constant.USER);
result.put(Constant.RESULT, Constant.FAIL);
if (user == null) {
result.put(Constant.MSG, "请登陆再试!");
return result;
}
if (id != null) {
if (favoriteService.hasFavorite(user.getId(), id) != null) {
result.put(Constant.MSG, "该新闻已收藏!");
return result;
}
Favorite favorite = new Favorite();
favorite.setUserId(user.getId());
favorite.setOrgId(id);
favorite.setSortNum(0);
favorite.setCreateTime(new Date());
favoriteService.addFavorite(favorite);
}
result.put(Constant.RESULT, Constant.SUCCESS);
return result;
}
@RequestMapping(value = "/my/delFavorite.htm")
@ResponseBody
public Map<String, String> delFavorite(HttpSession session, String id) {
Map<String, String> result = new HashMap<String, String>();
User user = (User) session.getAttribute(Constant.USER);
result.put(Constant.RESULT, Constant.FAIL);
if (user == null) {
return result;
}
if (id != null) {
favoriteService.deleteFavorite(user.getId(), id);
}
result.put(Constant.RESULT, Constant.SUCCESS);
return result;
}
@RequestMapping(value = "/my/singleGraphic.htm")
public String singleGraphic(String ids, Integer id, Model model) {
if (!StringUtils.isEmpty(ids) && id == null) {
if (ids.indexOf(",") != -1) {
Material material = new Material();
StringBuffer b_summary = new StringBuffer();
StringBuffer b_content = new StringBuffer();
// List<String> img_list = new ArrayList<String>();
List<String> allList = new ArrayList<String>();
Set<String> img_list = new HashSet<String>();
String[] org_ids = ids.split(",");
for (int i = 0, len = org_ids.length; i < len; i++) {
if (!StringUtils.isEmpty(org_ids[i])) {
// News news =
// newsService.getNewsById(Integer.parseInt(org_ids[i]));
News news = newsService.getNewsById_s(org_ids[i]);
if (news != null) {
if (i == 0) {
material.setTitle(news.getTitle());
}
b_summary.append(news.getTitle()).append("\r\n");
b_content
.append("<strong><span style=\"font-size:18px;font-family:宋体;\">" + news.getTitle()
+ "</span></strong>").append(news.getContent()).append("<br />");
List<String> i_list = ImageUtil.getImgUrl(news.getContent());
img_list.addAll(i_list);
}
}
}
allList.addAll(img_list);
material.setSummary(b_summary.toString());
material.setContent(b_content.toString());
model.addAttribute("material", material);
model.addAttribute("imgList", allList);
}
} else if (id != null) {
Material material = materialService.getMaterialById(id);
if (material != null) {
model.addAttribute("material", material);
List<String> img_list = new ArrayList<String>();
img_list.add(material.getImageUrl());
model.addAttribute("imgList", img_list);
}
}
return "singleGraphic";
}
@RequestMapping(value = "/my/multiGraphic.htm")
public String multiGraphic(String ids, Integer id, Model model) throws Exception {
if (!StringUtils.isEmpty(ids) && id == null) {
if (ids.indexOf(",") != -1) {
List<MaterialVo> materialList = new ArrayList<MaterialVo>();
String[] org_ids = ids.split(",");
for (int i = 0, len = org_ids.length; i < len; i++) {
if (!StringUtils.isEmpty(org_ids[i])) {
// News news =
// newsService.getNewsById(Integer.parseInt(org_ids[i]));
News news = newsService.getNewsById_s(org_ids[i]);
if (news != null) {
MaterialVo materialVo = new MaterialVo();
Material material = new Material();
materialVo.setMaterial(material);
material.setTitle(news.getTitle());
StringBuffer b_content = new StringBuffer();
b_content
.append("<strong><span style=\"font-size:18px;font-family:宋体;\">" + news.getTitle()
+ "</span></strong>").append(news.getContent()).append("<br />");
material.setSummary(news.getTitle());
material.setContent(b_content.toString());
List<String> img_list = ImageUtil.getImgUrl(news.getContent());
if (img_list != null && img_list.size() > 0) {
material.setImageUrl(img_list.get(0));
}
materialVo.setImgList(img_list);
materialList.add(materialVo);
}
}
}
model.addAttribute("mList", materialList);
}
} else if (id != null) {
List<MaterialVo> materialList = new ArrayList<MaterialVo>();
List<Material> mList = materialService.getMaterialByPId(id);
for (Material material : mList) {
MaterialVo materialVo = new MaterialVo();
materialVo.setMaterial(material);
List<String> img_list = new ArrayList<String>();
img_list.add(material.getImageUrl());
materialVo.setImgList(img_list);
materialList.add(materialVo);
}
model.addAttribute("mList", materialList);
}
return "multiGraphic";
}
@RequestMapping(value = "/my/getFavoriteList.htm")
@ResponseBody
public Pagination<FavoriteVo> findFavorite(HttpSession session, Integer pageIndex, Integer pageSize) {
User user = (User) session.getAttribute(Constant.USER);
if (user == null) {
return null;
}
if (pageIndex == null) {
pageIndex = 1;
}
if (pageSize == null) {
pageSize = 6;
}
return favoriteService.findFavorite(user.getId(), pageIndex, pageSize);
}
@RequestMapping(value = "/my/delMaterial.htm")
@ResponseBody
public Map<String, String> delMaterial(HttpSession session, Integer id) {
Map<String, String> result = new HashMap<String, String>();
User user = (User) session.getAttribute(Constant.USER);
result.put(Constant.RESULT, Constant.FAIL);
if (user == null) {
return result;
}
if (id != null) {
materialService.deleteMaterialById(id);
}
result.put(Constant.RESULT, Constant.SUCCESS);
return result;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/my/file_manager_json.htm")
@ResponseBody
public String file_manager_json(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
User user = (User) session.getAttribute(Constant.USER);
// 根目录路径,可以指定绝对路径,比如 /var/www/attached/
String rootPath = session.getServletContext().getRealPath("/") + "upload/images/" + user.getId() + "/";
// 根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
String rootUrl = request.getContextPath() + "/upload/images/" + user.getId() + "/";
// 图片扩展名
String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
String dirName = request.getParameter("dir");
if (dirName != null) {
if (!Arrays.<String> asList(new String[] { "image", "flash", "media", "file" }).contains(dirName)) {
return "Invalid Directory name.";
}
// rootPath += dirName + "/";
// rootUrl += dirName + "/";
File saveDirFile = new File(rootPath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
}
// 根据path参数,设置各路径和URL
String path = request.getParameter("path") != null ? request.getParameter("path") : "";
String currentPath = rootPath + path;
String currentUrl = rootUrl + path;
String currentDirPath = path;
String moveupDirPath = "";
if (!"".equals(path)) {
String str = currentDirPath.substring(0, currentDirPath.length() - 1);
moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
}
// 排序形式,name or size or type
String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";
// 不允许使用..移动到上一级目录
if (path.indexOf("..") >= 0) {
return "Access is not allowed.";
}
// 最后一个字符不是/
if (!"".equals(path) && !path.endsWith("/")) {
return "Parameter is not valid.";
}
// 目录不存在或不是目录
File currentPathFile = new File(currentPath);
if (!currentPathFile.isDirectory()) {
return "Directory does not exist.";
}
// 遍历目录取的文件信息
List<Hashtable> fileList = new ArrayList<Hashtable>();
if (currentPathFile.listFiles() != null) {
for (File file : currentPathFile.listFiles()) {
Hashtable<String, Object> hash = new Hashtable<String, Object>();
String fileName = file.getName();
if (file.isDirectory()) {
hash.put("is_dir", true);
hash.put("has_file", (file.listFiles() != null));
hash.put("filesize", 0L);
hash.put("is_photo", false);
hash.put("filetype", "");
} else if (file.isFile()) {
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
hash.put("is_dir", false);
hash.put("has_file", false);
hash.put("filesize", file.length());
hash.put("is_photo", Arrays.<String> asList(fileTypes).contains(fileExt));
hash.put("filetype", fileExt);
}
hash.put("filename", fileName);
hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
fileList.add(hash);
}
}
if ("size".equals(order)) {
Collections.sort(fileList, new SizeComparator());
} else if ("type".equals(order)) {
Collections.sort(fileList, new TypeComparator());
} else {
Collections.sort(fileList, new NameComparator());
}
Gson gson = new Gson();
// JSONObject result = new JSONObject();
Map result = new HashMap();
result.put("moveup_dir_path", moveupDirPath);
result.put("current_dir_path", currentDirPath);
result.put("current_url", currentUrl);
result.put("total_count", fileList.size());
result.put("file_list", fileList);
// response.setContentType("application/json; charset=UTF-8");
// out.println(result.toJSONString());
return gson.toJson(result);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/my/uploadImage.htm")
@ResponseBody
public String uploadImage(@RequestParam(value = "imageFile", required = true)
MultipartFile imageFile, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
Map obj = new HashMap();
obj.put("error", 1);
// 保存
try {
if (!imageFile.isEmpty()) {
User user = (User) session.getAttribute(Constant.USER);
String path = request.getSession().getServletContext()
.getRealPath("/upload/images/" + user.getId() + "/");
// 原图
String fileName = imageFile.getOriginalFilename();
// fileName = URLEncoder.encode(fileName, "UTF-8");
String name = fileName.substring(0, fileName.lastIndexOf("."));
String extensionName = StringUtils.substring(fileName, StringUtils.lastIndexOf(fileName, "."))
.toLowerCase();
name = new Date().getTime() + "";
fileName = name + extensionName;
// 定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", ".gif,.jpg,.jpeg,.png,.bmp");
if (!Arrays.<String> asList(extMap.get("image").split(",")).contains(extensionName)) {
obj.put("message", "File extension is not allowed. \n only accept " + extMap.get("image")
+ " file extension.");
} else {
String reduceName = name + "_" + extensionName;
// String fileName = new Date().getTime()+".jpg";
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
imageFile.transferTo(targetFile);
ImageUtil.imageReduce(targetFile);
String url = request.getContextPath() + "/upload/images/" + user.getId() + "/" + reduceName;
String url1 = request.getContextPath() + "/upload/images/" + user.getId() + "/" + fileName;
obj.put("error", 0);
obj.put("url", url);
obj.put("url1", url1);
}
}
} catch (Exception e) {
log.error("uploadImage", e);
obj.put("message", e.toString());
}
Gson gson = new Gson();
return gson.toJson(obj);
}
@RequestMapping(value = "/my/imageReduce.htm")
@ResponseBody
public String imageReduce(String ctx, String url, HttpSession session) {
String result = null;
User user = (User) session.getAttribute(Constant.USER);
String uploadDir = session.getServletContext().getRealPath("/upload/images/" + user.getId() + "/");
String name = ImageUtil.imageReduceUrl(uploadDir, url);
if (name != null) {
result = ctx + "/upload/images/" + user.getId() + "/" + name;
}
return result;
}
@RequestMapping(value = "/my/sin_saveMaterial.htm")
@ResponseBody
public Map<String, String> sin_saveMaterial(HttpSession session, Material material) {
Map<String, String> result = new HashMap<String, String>();
result.put(Constant.RESULT, Constant.FAIL);
User user = (User) session.getAttribute(Constant.USER);
if ("1".equals(material.getShowCover())) {
String content = ImageUtil.addCoverImg(material.getImageUrl(), material.getContent());
material.setContent(content);
} else {
String content = ImageUtil.removeCoverImg(material.getImageUrl(), material.getContent());
material.setContent(content);
}
material.setCreateTime(new Date());
material.setUserId(user.getId());
material.setSubType("1");
materialService.addMaterial(material);
result.put(Constant.RESULT, Constant.SUCCESS);
return result;
}
@RequestMapping(value = "/my/sin_preview.htm")
@ResponseBody
public Map<String, String> sin_preview(HttpSession session, HttpServletRequest request, Material material)
throws Exception {
Map<String, String> result = new HashMap<String, String>();
result.put(Constant.RESULT, Constant.FAIL);
User user = (User) session.getAttribute(Constant.USER);
if (user == null) {
result.put(Constant.MSG, "登陆超时!");
return result;
}
WxAccount account = wxAccountService.getWxAccountByUserid(user.getId());
if (account == null) {
result.put(Constant.MSG, "尚未配置公众号,请联系管理员!");
return result;
}
WeiXinVo wxVo = null;
String towxname = account.getWid();
String accessToken = (String) OSCacheManage.getInstance().getCache(String.valueOf(user.getId()), 3600);
if (accessToken == null) {
wxVo = WeiXinUtil.getToken(account.getAppId(), account.getSecret());
accessToken = wxVo.getAccess_token();
}
if (accessToken != null) {
OSCacheManage.getInstance().setCache(String.valueOf(user.getId()), accessToken);
File imageFile = ImageUtil.getUrlFile(material.getImageUrl(),
session.getServletContext().getRealPath("/upload/images/" + user.getId() + "/"));
wxVo = WeiXinUtil.uploadImage(accessToken, "image", imageFile);
String image_id = wxVo.getMedia_id();
if (StringUtils.isEmpty(image_id)) {
result.put(Constant.MSG, wxVo.getErrmsg());
} else {
String content = ImageUtil.repalceImgUrl(material.getContent(), session.getServletContext()
.getRealPath("/upload/images/" + user.getId() + "/"), accessToken);
Map<String, String> map = new HashMap<String, String>();
map.put("thumb_media_id", image_id);
map.put("title", material.getTitle());
map.put("content", content);
map.put("digest", material.getSummary());
map.put("show_cover_pic", "0");
Map<String, List<Map<String, String>>> listMap = new HashMap<String, List<Map<String, String>>>();
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(map);
listMap.put("articles", list);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String json = gson.toJson(listMap);// 转换成json数据格式
wxVo = WeiXinUtil.uploadFodder(accessToken, json);
String media_id = wxVo.getMedia_id();
if (StringUtils.isEmpty(media_id)) {
result.put(Constant.MSG, wxVo.getErrmsg());
} else {
JsonObject jObj1 = new JsonObject();
jObj1.addProperty("towxname", towxname);
JsonObject mpnews1 = new JsonObject();
mpnews1.addProperty("media_id", media_id);
jObj1.add("mpnews", mpnews1);
jObj1.addProperty("msgtype", "mpnews");
log.error("userId=" + user.getId() + ",微信名称=" + account.getName() + ",手机预览:" + json);
wxVo = WeiXinUtil.preview(accessToken, jObj1.toString());
if (wxVo != null) {
if ("0".equals(wxVo.getErrcode())) {
result.put(Constant.RESULT, Constant.SUCCESS);
} else {
result.put(Constant.MSG, wxVo.getErrmsg());
}
}
log.error("userId=" + user.getId() + ",微信名称=" + account.getName() + ",手机预览结果:" + gson.toJson(wxVo));
}
}
}
return result;
}
@RequestMapping(value = "/my/sin_sendMsg.htm")
@ResponseBody
public Map<String, String> sin_sendMsg(HttpSession session, HttpServletRequest request, Material material)
throws Exception {
Map<String, String> result = new HashMap<String, String>();
result.put(Constant.RESULT, Constant.FAIL);
User user = (User) session.getAttribute(Constant.USER);
if (user == null) {
result.put(Constant.MSG, "登陆超时!");
return result;
}
WxAccount account = wxAccountService.getWxAccountByUserid(user.getId());
if (account == null) {
result.put(Constant.MSG, "尚未配置公众号,请联系管理员!");
return result;
}
WeiXinVo wxVo = null;
String accessToken = (String) OSCacheManage.getInstance().getCache(String.valueOf(user.getId()), 3600);
if (accessToken == null) {
wxVo = WeiXinUtil.getToken(account.getAppId(), account.getSecret());
accessToken = wxVo.getAccess_token();
}
if (accessToken != null) {
OSCacheManage.getInstance().setCache(String.valueOf(user.getId()), accessToken);
File imageFile = ImageUtil.getUrlFile(material.getImageUrl(),
session.getServletContext().getRealPath("/upload/images/" + user.getId() + "/"));
wxVo = WeiXinUtil.uploadImage(accessToken, "image", imageFile);
String image_id = wxVo.getMedia_id();
if (StringUtils.isEmpty(image_id)) {
result.put(Constant.MSG, wxVo.getErrmsg());
} else {
String content = ImageUtil.repalceImgUrl(material.getContent(), session.getServletContext()
.getRealPath("/upload/images/" + user.getId() + "/"), accessToken);
Map<String, String> map = new HashMap<String, String>();
map.put("thumb_media_id", image_id);
map.put("title", material.getTitle());
map.put("content", content);
map.put("digest", material.getSummary());
map.put("show_cover_pic", "0");
Map<String, List<Map<String, String>>> listMap = new HashMap<String, List<Map<String, String>>>();
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(map);
listMap.put("articles", list);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String json = gson.toJson(listMap);// 转换成json数据格式
wxVo = WeiXinUtil.uploadFodder(accessToken, json);
String media_id = wxVo.getMedia_id();
if (StringUtils.isEmpty(media_id)) {
result.put(Constant.MSG, wxVo.getErrmsg());
} else {
JsonObject jObj = new JsonObject();
JsonObject filter = new JsonObject();
filter.addProperty("is_to_all", true);
// filter.addProperty("group_id", "101");
jObj.add("filter", filter);
JsonObject mpnews = new JsonObject();
mpnews.addProperty("media_id", media_id);
jObj.add("mpnews", mpnews);
jObj.addProperty("msgtype", "mpnews");
log.error("userId=" + user.getId() + ",微信名称=" + account.getName() + ",群发消息:" + json);
WeiXinVo errorVo = WeiXinUtil.sendMsg(accessToken, jObj.toString());
if (errorVo != null) {
if ("0".equals(errorVo.getErrcode())) {
result.put(Constant.RESULT, Constant.SUCCESS);
} else {
result.put(Constant.MSG, errorVo.getErrmsg());
}
}
log.error("userId=" + user.getId() + ",微信名称=" + account.getName() + ",群发消息结果:"
+ gson.toJson(errorVo));
}
}
}
return result;
}
@RequestMapping(value = "/my/mul_saveMaterial.htm")
@ResponseBody
public Map<String, String> mul_saveMaterial(HttpSession session, String mlistStr, String delIds) throws Exception {
Map<String, String> result = new HashMap<String, String>();
result.put(Constant.RESULT, Constant.FAIL);
List<Material> mlist = JsonUtil.String2List(mlistStr, Material.class);
User user = (User) session.getAttribute(Constant.USER);
if (mlist == null || mlist.isEmpty()) {
return result;
}
int pid = 0;
for (int i = 0, len = mlist.size(); i < len; i++) {
Material material = mlist.get(i);
if ("1".equals(material.getShowCover())) {
String content = ImageUtil.addCoverImg(material.getImageUrl(), material.getContent());
material.setContent(content);
} else {
String content = ImageUtil.removeCoverImg(material.getImageUrl(), material.getContent());
material.setContent(content);
}
material.setCreateTime(new Date());
material.setUserId(user.getId());
material.setSubType("2");
if (i == 0) {
Material material_0 = materialService.addMaterial(material);
pid = material_0.getId();
} else {
material.setParentId(pid);
materialService.addMaterial(material);
}
}
List<String> delList = JsonUtil.String2List(delIds, String.class);
for (String id : delList) {
materialService.deleteMaterialById(Integer.parseInt(id));
}
result.put(Constant.RESULT, Constant.SUCCESS);
return result;
}
@RequestMapping(value = "/my/mul_preview.htm")
@ResponseBody
public Map<String, String> mul_preview(HttpSession session, HttpServletRequest request, String mlistStr)
throws Exception {
Map<String, String> result = new HashMap<String, String>();
result.put(Constant.RESULT, Constant.FAIL);
try {
User user = (User) session.getAttribute(Constant.USER);
if (user == null) {
result.put(Constant.MSG, "登陆超时!");
return result;
}
WxAccount account = wxAccountService.getWxAccountByUserid(user.getId());
if (account == null) {
result.put(Constant.MSG, "尚未配置公众号,请联系管理员!");
return result;
}
List<Material> mlist = JsonUtil.String2List(mlistStr, Material.class);
WeiXinVo wxVo = null;
String towxname = account.getWid();
String accessToken = (String) OSCacheManage.getInstance().getCache(String.valueOf(user.getId()), 3600);
if (accessToken == null) {
wxVo = WeiXinUtil.getToken(account.getAppId(), account.getSecret());
accessToken = wxVo.getAccess_token();
}
if (accessToken != null) {
OSCacheManage.getInstance().setCache(String.valueOf(user.getId()), accessToken);
List<String> image_id_list = new ArrayList<String>();
for (Material material : mlist) {
File imageFile = ImageUtil.getUrlFile(material.getImageUrl(), session.getServletContext()
.getRealPath("/upload/images/" + user.getId() + "/"));
wxVo = WeiXinUtil.uploadImage(accessToken, "image", imageFile);
String image_id = wxVo.getMedia_id();
if (StringUtils.isEmpty(image_id)) {
result.put(Constant.MSG, wxVo.getErrmsg());
return result;
} else {
image_id_list.add(image_id);
}
}
Map<String, List<Map<String, String>>> listMap = new HashMap<String, List<Map<String, String>>>();
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
for (int i = 0, len = image_id_list.size(); i < len; i++) {
String content = ImageUtil.repalceImgUrl(mlist.get(i).getContent(), session.getServletContext()
.getRealPath("/upload/images/" + user.getId() + "/"), accessToken);
Map<String, String> map = new HashMap<String, String>();
map.put("thumb_media_id", image_id_list.get(i));
map.put("title", mlist.get(i).getTitle());
map.put("content", content);
map.put("digest", mlist.get(i).getSummary());
map.put("show_cover_pic", "0");
list.add(map);
}
listMap.put("articles", list);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String json = gson.toJson(listMap);// 转换成json数据格式
wxVo = WeiXinUtil.uploadFodder(accessToken, json);
String media_id = wxVo.getMedia_id();
if (StringUtils.isEmpty(media_id)) {
result.put(Constant.MSG, wxVo.getErrmsg());
return result;
} else {
JsonObject jObj1 = new JsonObject();
jObj1.addProperty("towxname", towxname);
JsonObject mpnews1 = new JsonObject();
mpnews1.addProperty("media_id", media_id);
jObj1.add("mpnews", mpnews1);
jObj1.addProperty("msgtype", "mpnews");
log.error("userId=" + user.getId() + ",微信名称=" + account.getName() + ",手机预览:" + json);
wxVo = WeiXinUtil.preview(accessToken, jObj1.toString());
if (wxVo != null) {
if ("0".equals(wxVo.getErrcode())) {
result.put(Constant.RESULT, Constant.SUCCESS);
} else {
result.put(Constant.MSG, wxVo.getErrmsg());
}
}
log.error("userId=" + user.getId() + ",微信名称=" + account.getName() + ",手机预览结果:" + gson.toJson(wxVo));
}
}
} catch (Exception e) {
log.error("mul_preview", e);
throw e;
}
return result;
}
@RequestMapping(value = "/my/mul_sendMsg.htm")
@ResponseBody
public Map<String, String> mul_sendMsg(HttpSession session, HttpServletRequest request, String mlistStr)
throws Exception {
Map<String, String> result = new HashMap<String, String>();
result.put(Constant.RESULT, Constant.FAIL);
try {
User user = (User) session.getAttribute(Constant.USER);
if (user == null) {
result.put(Constant.MSG, "登陆超时!");
return result;
}
WxAccount account = wxAccountService.getWxAccountByUserid(user.getId());
if (account == null) {
result.put(Constant.MSG, "尚未配置公众号,请联系管理员!");
return result;
}
List<Material> mlist = JsonUtil.String2List(mlistStr, Material.class);
WeiXinVo wxVo = null;
String accessToken = (String) OSCacheManage.getInstance().getCache(String.valueOf(user.getId()), 3600);
if (accessToken == null) {
wxVo = WeiXinUtil.getToken(account.getAppId(), account.getSecret());
accessToken = wxVo.getAccess_token();
}
if (accessToken != null) {
OSCacheManage.getInstance().setCache(String.valueOf(user.getId()), accessToken);
List<String> image_id_list = new ArrayList<String>();
for (Material material : mlist) {
File imageFile = ImageUtil.getUrlFile(material.getImageUrl(), session.getServletContext()
.getRealPath("/upload/images/" + user.getId() + "/"));
wxVo = WeiXinUtil.uploadImage(accessToken, "image", imageFile);
String image_id = wxVo.getMedia_id();
if (StringUtils.isEmpty(image_id)) {
result.put(Constant.MSG, wxVo.getErrmsg());
return result;
} else {
image_id_list.add(image_id);
}
}
Map<String, List<Map<String, String>>> listMap = new HashMap<String, List<Map<String, String>>>();
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
for (int i = 0, len = image_id_list.size(); i < len; i++) {
String content = ImageUtil.repalceImgUrl(mlist.get(i).getContent(), session.getServletContext()
.getRealPath("/upload/images/" + user.getId() + "/"), accessToken);
Map<String, String> map = new HashMap<String, String>();
map.put("thumb_media_id", image_id_list.get(i));
map.put("title", mlist.get(i).getTitle());
map.put("content", content);
map.put("digest", mlist.get(i).getSummary());
map.put("show_cover_pic", "0");
list.add(map);
}
listMap.put("articles", list);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String json = gson.toJson(listMap);// 转换成json数据格式
wxVo = WeiXinUtil.uploadFodder(accessToken, json);
String media_id = wxVo.getMedia_id();
if (StringUtils.isEmpty(media_id)) {
result.put(Constant.MSG, wxVo.getErrmsg());
return result;
} else {
JsonObject jObj = new JsonObject();
JsonObject filter = new JsonObject();
filter.addProperty("is_to_all", true);
// filter.addProperty("group_id", "101");
jObj.add("filter", filter);
JsonObject mpnews = new JsonObject();
mpnews.addProperty("media_id", media_id);
jObj.add("mpnews", mpnews);
jObj.addProperty("msgtype", "mpnews");
log.error("userId=" + user.getId() + ",微信名称=" + account.getName() + ",群发消息:" + json);
WeiXinVo errorVo = WeiXinUtil.sendMsg(accessToken, jObj.toString());
if (errorVo != null) {
if ("0".equals(errorVo.getErrcode())) {
result.put(Constant.RESULT, Constant.SUCCESS);
} else {
result.put(Constant.MSG, errorVo.getErrmsg());
}
}
log.error("userId=" + user.getId() + ",微信名称=" + account.getName() + ",群发消息结果:"
+ gson.toJson(errorVo));
}
}
} catch (Exception e) {
log.error("mul_sendMsg", e);
throw e;
}
return result;
}
}