lists = mongo.getDatabaseNames();
DB db = mongo.getDB("mongoLida");
DBCollection collection = db.getCollection("sensor");
System.out.println(collection.count());
}
private static MongoClientOptions getConfOptions() {
return new MongoClientOptions.Builder().socketKeepAlive(true) // 是否保持长链接
.connectTimeout(5000) // 链接超时时间
.socketTimeout(5000) // read数据超时时间
.readPreference(ReadPreference.primary()) // 最近优先策略
.autoConnectRetry(false) // 是否重试机制
.connectionsPerHost(30) // 每个地址最大请求数
.maxWaitTime(1000 * 60 * 2) // 长链接的最大等待时间
.threadsAllowedToBlockForConnectionMultiplier(50) // 一个socket最大的等待请求数
.writeConcern(WriteConcern.NORMAL).build();
}
}
================================================
FILE: src/main/java/com/lida/mongo/util/MyX509TrustManager.java
================================================
package com.lida.mongo.util;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* ֤�����ι�����������https����
*/
public class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
================================================
FILE: src/main/java/com/lida/mongo/util/QQUtils.java
================================================
package com.lida.mongo.util;
import com.lida.mongo.qq.model.QQUserInfo;
import jdk.nashorn.internal.runtime.GlobalConstants;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by stevenfen on 2016/12/22.
*/
public class QQUtils {
public static String appId = "101375254";
public static String appSecret = "xxx";
public static String baseUrl = "https://graph.qq.com";
protected static final String URL_GET_USERINFO = baseUrl
+ "/user/get_user_info?access_token=%s&oauth_consumer_key=%s&openid=%s";
protected static final long ACCESS_TIMEOUT = 15;
protected static final String DEF_APP_TOKEN_EXPIRE = "3h";
private static Logger log = LoggerFactory.getLogger(QQUtils.class);
/**
* 获取用户信息
*
*
* http://wiki.connect.qq.com/get_user_info
*
*
* 调用地址:
* https://graph.qq.com/user/get_user_info
* 参数
* access_token=*************&
* oauth_consumer_key=12345&
* openid
*
* 返回结果如下:
* {
* "ret": 0,
* "msg": "",
* "is_lost": 0,
* "nickname": "小吞",
* "gender": "女",
* "province": "广东",
* "city": "广州",
* "year": "1993",
* "figureurl": "http://qzapp.qlogo.cn/qzapp/101207268/982C9FEADAF7B242C5069B8F390784BF/30",
* "figureurl_1": "http://qzapp.qlogo.cn/qzapp/101207268/982C9FEADAF7B242C5069B8F390784BF/50",
* "figureurl_2": "http://qzapp.qlogo.cn/qzapp/101207268/982C9FEADAF7B242C5069B8F390784BF/100",
* "figureurl_qq_1": "http://q.qlogo.cn/qqapp/101207268/982C9FEADAF7B242C5069B8F390784BF/40",
* "figureurl_qq_2": "http://q.qlogo.cn/qqapp/101207268/982C9FEADAF7B242C5069B8F390784BF/100",
* "is_yellow_vip": "0",
* "vip": "0",
* "yellow_vip_level": "0",
* "level": "0",
* "is_yellow_year_vip": "0"
* }
*
*
* @param accessToken
* @return
*/
public static QQUserInfo getUserInfo(String accessToken, String openid) {
if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(openid)) {
return null;
}
String url = String.format(URL_GET_USERINFO, accessToken, appId, openid);
String resultString = HttpClientUtils.httpGet(url);
log.debug("[sso-qq]get userinfo. use url '%s'", url);
QQUserInfo userinfo = JsonUtil.fromJson(resultString, QQUserInfo.class);
if (userinfo == null ) {
log.debug("[sso-qq]get userinfo failed, with result of '%s'", resultString);
return null;
}
log.debug("[sso-qq]get userinfo success, with result of '%s'", resultString);
return userinfo;
}
}
================================================
FILE: src/main/java/com/lida/mongo/util/SignUtil.java
================================================
package com.lida.mongo.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/**
* ����У�鹤����
*/
public class SignUtil {
private static String token = "co3oopVScm6zzoQWb04_Nlss9r04Ag4B8GfBUrbbvgFbxNvXK15WXqNEFjIHO07obMyya_tHkwTw7NJekr-hhMn_dTnVPGN7pMg0oZGcsXh6iBQhoFYUF8cGPKdbtRqYEVYbAGAOFI";
/**
* ��֤ǩ��
*
* @param signature
* @param timestamp
* @param nonce
* @return
*/
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[]{token, timestamp, nonce};
Arrays.sort(arr);
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
content = null;
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}
/**
* ���ֽ�����ת��Ϊʮ�������ַ���
*
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* ���ֽ�ת��Ϊʮ�������ַ���
*
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
}
================================================
FILE: src/main/java/com/lida/mongo/util/StringUtil.java
================================================
package com.lida.mongo.util;
import com.lida.mongo.sensor.entity.Sensor;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by lenovo on 2016/12/6.
*/
public class StringUtil {
private static final String format = "yyyy-MM-dd HH:mm:ss";
public static Date string2Date(String dateStr) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date=sdf.parse(dateStr);
return date;
}
public static void judgeField(String nodeMap, Double value, Sensor sensor){
if(nodeMap.equals("sensor1")){
sensor.setSensor1(value);
}
else if(nodeMap.equals("sensor2")){
sensor.setSensor2(value);
}
else if(nodeMap.equals("sensor3")){
sensor.setSensor3(value);
}
else if(nodeMap.equals("sensor4")){
sensor.setSensor4(value);
}
else if(nodeMap.equals("sensor5")){
sensor.setSensor5(value);
}
else if(nodeMap.equals("sensor6")){
sensor.setSensor6(value);
}
else if(nodeMap.equals("sensor7")){
sensor.setSensor7(value);
}
else if(nodeMap.equals("sensor8")){
sensor.setSensor8(value);
}
else if(nodeMap.equals("sensor9")){
sensor.setSensor9(value);
}
else if(nodeMap.equals("sensor10")){
sensor.setSensor10(value);
}
else if(nodeMap.equals("sensor11")){
sensor.setSensor11(value);
}
else if(nodeMap.equals("sensor12")){
sensor.setSensor12(value);
}
else if(nodeMap.equals("sensor13")){
sensor.setSensor13(value);
}
else if(nodeMap.equals("sensor14")){
sensor.setSensor14(value);
}
else if(nodeMap.equals("sensor15")){
sensor.setSensor15(value);
}
else if(nodeMap.equals("sensor16")){
sensor.setSensor16(value);
}
else if(nodeMap.equals("sensor17")){
sensor.setSensor17(value);
}
else if(nodeMap.equals("sensor18")){
sensor.setSensor18(value);
}
else if(nodeMap.equals("sensor19")){
sensor.setSensor19(value);
}
else if(nodeMap.equals("sensor20")){
sensor.setSensor20(value);
}
}
/**
* 计算输入日期后的一个小时的时间
* @param date
* @return
*/
public static Date plusOneHour(Date date){
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, 1);
return calendar.getTime();
}
}
================================================
FILE: src/main/java/com/lida/mongo/util/WeixinUtil.java
================================================
package com.lida.mongo.util;
import com.lida.mongo.weixin.model.AccessToken;
import com.lida.mongo.weixin.model.Menu;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
/**
* ????????????????
*/
public class WeixinUtil {
// private static Logger log = LoggerFactory.getLogger(WeixinUtil.class);
/**
* ????https?????????
*
* @param requestUrl ??????
* @param requestMethod ???????GET??POST??
* @param outputStr ????????
* @return JSONObject(???JSONObject.get(key)???????json??????????)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// ????SSLContext??????????????????????????????
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// ??????SSLContext???????SSLSocketFactory????
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// ???????????GET/POST??
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// ??????????????
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// ?????????????????????
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// ???????????????????????
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// ??????
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
System.out.println("Weixin server connection timed out.");
} catch (Exception e) {
System.out.println("https request error:{}" + e);
}
return jsonObject;
}
// ???access_token????????GET?? ??200????/??
public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
/**
* ???access_token
*
* @param appid ??
* @param appsecret ???
* @return
*/
public static AccessToken getAccessToken(String appid, String appsecret) {
AccessToken accessToken = null;
String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
// ?????????
if (null != jsonObject) {
try {
accessToken = new AccessToken();
accessToken.setToken(jsonObject.getString("access_token"));
accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
System.setProperty("javax.net.debug", "ssl,handshake");
} catch (JSONException e) {
accessToken = null;
// ???token???
System.out.println("???token??? errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + jsonObject.getString("errmsg"));
}
}
return accessToken;
}
// ?????????POST?? ??100????/??
public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
/**
* ???????
*
* @param menu ??????
* @param accessToken ????access_token
* @return 0???????????????????
*/
public static int createMenu(Menu menu, String accessToken) {
int result = 0;
// ???????????url
String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);
// ??????????????json?????
String jsonMenu = JSONObject.fromObject(menu).toString();
// ????????????
JSONObject jsonObject = httpRequest(url, "POST", jsonMenu);
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
result = jsonObject.getInt("errcode");
System.out.println("?????????? errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + jsonObject.getString("errmsg"));
}
}
return result;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/controller/WeChatController.java
================================================
package com.lida.mongo.weixin.controller;
import com.lida.mongo.weixin.service.CoreService;
import com.lida.mongo.util.SignUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* Created by stevenfen on 2016/11/12.
*/
@Controller
@RequestMapping(value = "wechat")
public class WeChatController {
@Resource
private CoreService coreService;
@RequestMapping(method = RequestMethod.GET)
public void doget(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
// 微信加密签名
String signature = request.getParameter("signature");
// 时间戳
String timestamp = request.getParameter("timestamp");
// 随机数
String nonce = request.getParameter("nonce");
// 随机字符串
String echostr = request.getParameter("echostr");
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
out.print(echostr);
} else {
System.out.println("不是微信服务器发来的请求!");
}
out.flush();
out.close();
}
@RequestMapping(method = {RequestMethod.POST})
public void dopose(HttpServletRequest request, HttpServletResponse response) throws Exception {
/* 消息的接收、处理、响应 */
// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 调用核心业务类接收消息、处理消息
String respMessage = coreService.processRequest(request, response);
// 响应消息
PrintWriter out = response.getWriter();
out.print(respMessage);
out.close();
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/message/req/BaseMessage.java
================================================
package com.lida.mongo.weixin.message.req;
/**
* Ϣࣨͨû -> ʺţ
*/
public class BaseMessage {
// ź
private String ToUserName;
// ͷʺţһOpenID
private String FromUserName;
// Ϣʱ ͣ
private long CreateTime;
// Ϣͣtext/image/location/link
private String MsgType;
// Ϣid64λ
private long MsgId;
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public long getCreateTime() {
return CreateTime;
}
public void setCreateTime(long createTime) {
CreateTime = createTime;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
public long getMsgId() {
return MsgId;
}
public void setMsgId(long msgId) {
MsgId = msgId;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/message/req/ImageMessage.java
================================================
package com.lida.mongo.weixin.message.req;
/**
* ͼƬϢ
*/
public class ImageMessage extends BaseMessage {
// ͼƬ
private String PicUrl;
public String getPicUrl() {
return PicUrl;
}
public void setPicUrl(String picUrl) {
PicUrl = picUrl;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/message/req/LinkMessage.java
================================================
package com.lida.mongo.weixin.message.req;
/**
* Ϣ
*/
public class LinkMessage extends BaseMessage {
// Ϣ
private String Title;
// Ϣ
private String Description;
// Ϣ
private String Url;
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
Url = url;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/message/req/TextMessage.java
================================================
package com.lida.mongo.weixin.message.req;
/**
* ıϢ
*/
public class TextMessage extends BaseMessage {
// Ϣ
private String Content;
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/message/req/VoiceMessage.java
================================================
package com.lida.mongo.weixin.message.req;
/**
* ƵϢ
*/
public class VoiceMessage extends BaseMessage {
// ýID
private String MediaId;
// ʽ
private String Format;
public String getMediaId() {
return MediaId;
}
public void setMediaId(String mediaId) {
MediaId = mediaId;
}
public String getFormat() {
return Format;
}
public void setFormat(String format) {
Format = format;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/message/resp/Article.java
================================================
package com.lida.mongo.weixin.message.resp;
/**
* ͼmodel
*/
public class Article {
// ͼϢ
private String Title;
// ͼϢ
private String Description;
// ͼƬӣ֧JPGPNGʽϺõЧΪͼ640*320Сͼ80*80ͼƬӵҪ뿪дĻеUrlһ
private String PicUrl;
// ͼϢת
private String Url;
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return null == Description ? "" : Description;
}
public void setDescription(String description) {
Description = description;
}
public String getPicUrl() {
return null == PicUrl ? "" : PicUrl;
}
public void setPicUrl(String picUrl) {
PicUrl = picUrl;
}
public String getUrl() {
return null == Url ? "" : Url;
}
public void setUrl(String url) {
Url = url;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/message/resp/BaseMessage.java
================================================
package com.lida.mongo.weixin.message.resp;
/**
* ��Ϣ���ࣨ�����ʺ� -> ��ͨ�û���
*/
public class BaseMessage {
// ���շ��ʺţ��յ���OpenID��
private String ToUserName;
// �������ź�
private String FromUserName;
// ��Ϣ����ʱ�� �����ͣ�
private long CreateTime;
// ��Ϣ���ͣ�text/music/news��
private String MsgType;
// λ0x0001����־ʱ���DZ���յ�����Ϣ
private int FuncFlag;
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public long getCreateTime() {
return CreateTime;
}
public void setCreateTime(long createTime) {
CreateTime = createTime;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
public int getFuncFlag() {
return FuncFlag;
}
public void setFuncFlag(int funcFlag) {
FuncFlag = funcFlag;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/message/resp/Music.java
================================================
package com.lida.mongo.weixin.message.resp;
/**
* model
*/
public class Music {
// ֱ
private String Title;
//
private String Description;
//
private String MusicUrl;
// ӣWIFIʹøӲ
private String HQMusicUrl;
// ͼýidͨϴýļõid
private String ThumbMediaId;
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getMusicUrl() {
return MusicUrl;
}
public void setMusicUrl(String musicUrl) {
MusicUrl = musicUrl;
}
public String getHQMusicUrl() {
return HQMusicUrl;
}
public void setHQMusicUrl(String musicUrl) {
HQMusicUrl = musicUrl;
}
public String getThumbMediaId() {
return ThumbMediaId;
}
public void setThumbMediaId(String thumbMediaId) {
ThumbMediaId = thumbMediaId;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/message/resp/MusicMessage.java
================================================
package com.lida.mongo.weixin.message.resp;
/**
* ������Ϣ
*/
public class MusicMessage extends BaseMessage {
// ����
private com.lida.mongo.weixin.message.resp.Music Music;
public com.lida.mongo.weixin.message.resp.Music getMusic() {
return Music;
}
public void setMusic(com.lida.mongo.weixin.message.resp.Music music) {
Music = music;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/message/resp/NewsMessage.java
================================================
package com.lida.mongo.weixin.message.resp;
import java.util.List;
/**
* �ı���Ϣ
*/
public class NewsMessage extends BaseMessage {
// ͼ����Ϣ����������Ϊ10������
private int ArticleCount;
// ����ͼ����Ϣ��Ϣ��Ĭ�ϵ�һ��itemΪ��ͼ
private List Articles;
public int getArticleCount() {
return ArticleCount;
}
public void setArticleCount(int articleCount) {
ArticleCount = articleCount;
}
public List getArticles() {
return Articles;
}
public void setArticles(List articles) {
Articles = articles;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/message/resp/TextMessage.java
================================================
package com.lida.mongo.weixin.message.resp;
/**
* ıϢ
*/
public class TextMessage extends BaseMessage {
// ظϢ
private String Content;
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/model/AccessToken.java
================================================
package com.lida.mongo.weixin.model;
/**
* ��ͨ�ýӿ�ƾ֤
*/
public class AccessToken {
// ��ȡ����ƾ֤
private String token;
// ƾ֤��Чʱ�䣬��λ����
private int expiresIn;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/model/BaiduPlace.java
================================================
package com.lida.mongo.weixin.model;
/**
* ��ַ��Ϣ
*
* @author liufeng
* @date 2013-03-16
*/
public class BaiduPlace implements Comparable {
// ����
private String name;
// ��ϸ��ַ
private String address;
// ����
private String lng;
// �
private String lat;
// ��ϵ�绰
private String telephone;
// ����
private int distance;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public int compareTo(BaiduPlace baiduPlace) {
return this.distance - baiduPlace.getDistance();
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/model/Button.java
================================================
package com.lida.mongo.weixin.model;
/**
* ťĻ
*/
public class Button {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/model/CommonButton.java
================================================
package com.lida.mongo.weixin.model;
/**
* ͨťӰť
*/
public class CommonButton extends Button {
private String type;
private String key;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/model/ComplexButton.java
================================================
package com.lida.mongo.weixin.model;
/**
* ���Ӱ�ť������ť��
*/
public class ComplexButton extends Button {
private Button[] sub_button;
public Button[] getSub_button() {
return sub_button;
}
public void setSub_button(Button[] sub_button) {
this.sub_button = sub_button;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/model/Menu.java
================================================
package com.lida.mongo.weixin.model;
/**
* �˵�
*/
public class Menu {
private Button[] button;
public Button[] getButton() {
return button;
}
public void setButton(Button[] button) {
this.button = button;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/model/SNSUserInfo.java
================================================
package com.lida.mongo.weixin.model;
import java.util.List;
/**
* ͨ����ҳ��Ȩ��ȡ���û���Ϣ
*/
public class SNSUserInfo {
// �û���ʶ
private String openId;
// �û��dz�
private String nickname;
// �Ա�1�����ԣ�2��Ů�ԣ�0��δ֪��
private int sex;
// ����
private String country;
// ʡ��
private String province;
// ����
private String city;
// �û�ͷ������
private String headImgUrl;
// �û���Ȩ��Ϣ
private List privilegeList;
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getHeadImgUrl() {
return headImgUrl;
}
public void setHeadImgUrl(String headImgUrl) {
this.headImgUrl = headImgUrl;
}
public List getPrivilegeList() {
return privilegeList;
}
public void setPrivilegeList(List privilegeList) {
this.privilegeList = privilegeList;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/model/UserLocation.java
================================================
package com.lida.mongo.weixin.model;
/**
* �û�����λ��model
*/
public class UserLocation {
private String openId;
private String lng;
private String lat;
private String bd09Lng;
private String bd09Lat;
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getBd09Lng() {
return bd09Lng;
}
public void setBd09Lng(String bd09Lng) {
this.bd09Lng = bd09Lng;
}
public String getBd09Lat() {
return bd09Lat;
}
public void setBd09Lat(String bd09Lat) {
this.bd09Lat = bd09Lat;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/model/ViewButton.java
================================================
package com.lida.mongo.weixin.model;
/**
* view���͵IJ˵�
*/
public class ViewButton extends Button {
private String type;
private String url;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/model/WeixinOauth2Token.java
================================================
package com.lida.mongo.weixin.model;
/**
* ��ҳ��Ȩ��Ϣ
*/
public class WeixinOauth2Token {
// ��ҳ��Ȩ�ӿڵ���ƾ֤
private String accessToken;
// ƾ֤��Чʱ��
private int expiresIn;
// ����ˢ��ƾ֤
private String refreshToken;
// �û���ʶ
private String openId;
// �û���Ȩ������
private String scope;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/model/WeixinUserInfo.java
================================================
package com.lida.mongo.weixin.model;
/**
* ûĻϢ
*/
public class WeixinUserInfo {
// ûıʶ
private String openId;
// ע״̬1ǹע0δעδעʱȡϢ
private int subscribe;
// ûעʱ䣬Ϊʱûιעȡעʱ
private String subscribeTime;
// dz
private String nickname;
// ûԱ1ԣ2Ůԣ0δ֪
private int sex;
// ûڹ
private String country;
// ûʡ
private String province;
// ûڳ
private String city;
// ûԣΪzh_CN
private String language;
// ûͷ
private String headImgUrl;
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public int getSubscribe() {
return subscribe;
}
public void setSubscribe(int subscribe) {
this.subscribe = subscribe;
}
public String getSubscribeTime() {
return subscribeTime;
}
public void setSubscribeTime(String subscribeTime) {
this.subscribeTime = subscribeTime;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getHeadImgUrl() {
return headImgUrl;
}
public void setHeadImgUrl(String headImgUrl) {
this.headImgUrl = headImgUrl;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/service/CoreService.java
================================================
package com.lida.mongo.weixin.service;
import com.lida.mongo.weixin.message.resp.TextMessage;
import com.lida.mongo.util.MessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
/**
* ķ
*/
@Repository("CoreService")
public class CoreService {
private static Logger log = LoggerFactory.getLogger(CoreService.class);
private static String emoji(int codePoint) {
return String.valueOf(Character.toChars(codePoint));
}
/**
* ŷ
*
* @param request
* @return
*/
public String processRequest(HttpServletRequest request, HttpServletResponse response) {
// ĬϷصıϢ
String respMessage = null;
try {
String respContent = null;
Map requestMap = MessageUtil.parseXml(request);
String fromUserName = requestMap.get("FromUserName");
String toUserName = requestMap.get("ToUserName");
String msgType = requestMap.get("MsgType");
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
textMessage.setFuncFlag(0);
String openid = requestMap.get("FromUserName");
String Content = requestMap.get("Content");
if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
if ("1".equals(Content)) {
respContent = "ûɶ,İ";
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
// // ͼϢ
// NewsMessage newsMessage = new NewsMessage();
// newsMessage.setToUserName(fromUserName);
// newsMessage.setFromUserName(toUserName);
// newsMessage.setCreateTime(new Date().getTime());
// newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
// newsMessage.setFuncFlag(0);
//
// //1
// List articleList = new ArrayList();
// Article article1 = new Article();
// article1.setTitle("С");
// article1.setDescription("СϷ");
// article1.setPicUrl("http://resource.duopao.com/sg/image/20140221170627.jpg");
// article1.setUrl("http://www.duopao.com/games/info?game_code=g20140212153040377809");
// //2
// Article article2 = new Article();
// article2.setTitle("");
// article2.setDescription("СϷ");
// article2.setPicUrl("http://resource.duopao.com/sg/image/20140120233041.jpg");
// article2.setUrl("http://www.duopao.com/games/info?game_code=g20140120233048400063");
//
// articleList.add(article1);
// articleList.add(article2);
// newsMessage.setArticleCount(articleList.size());
// newsMessage.setArticles(articleList);
// respMessage = MessageUtil.newsMessageToXml(newsMessage);
} else if ("2".equals(Content)) {
respContent = MessageUtil.youxi();
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
} else if ("".equals(Content) || "?".equals(Content)) {
respContent = MessageUtil.getMainMenu();
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
} else {
respContent = "";
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}
}
// ͼƬϢ
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
String MediaId = requestMap.get("MediaId");
respContent = "ͼƬַǣ" + MediaId;
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}
// λϢ
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
}
// Ϣ
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
respContent = "˵в";
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}
// ƵϢ
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
respContent = "˵в";
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}
// ¼
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
// ¼
String eventType = requestMap.get("Event");
//
if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
respContent = emoji(0x1F334) + "ллעСС" + MessageUtil.getMainMenu();
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}
// Զ˵¼
else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
String eventKey = requestMap.get("EventKey");
if (eventKey.equals("11")) {
respContent = emoji(0x274C) + "ǰûа˻ֱӻظҵûа";
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
} else if (eventKey.equals("12")) {
} else if (eventKey.equals("13")) {
} else if (eventKey.equals("14")) {
} else if (eventKey.equals("21")) {
} else if (eventKey.equals("22")) {
} else if (eventKey.equals("23")) {
} else if (eventKey.equals("24")) {
} else if (eventKey.equals("31")) {
} else if (eventKey.equals("32")) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return respMessage;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/service/TemplateMes.java
================================================
package com.lida.mongo.weixin.service;
import com.lida.mongo.weixin.model.AccessToken;
import com.lida.mongo.util.HttpClientUtils;
import com.lida.mongo.util.WeixinUtil;
import java.util.Map;
/**
* ģϢ
*
* @author Administrator
*/
public class TemplateMes {
String appId = "wx247b80e8e951fe79";
// ûΨһƾ֤Կ
String appSecret = "4fc4112c0abac60c04997c8ac4d87b92";
// ýӿڻȡaccess_token
AccessToken at = WeixinUtil.getAccessToken(appId, appSecret);
// ¶֪ͨ
private static String NEWORDERS = "9x4PdTRa_FehBFX2HCQHMXAGRshlFj5AFg6zUe3MAA4";
// ̶
private static String ORDERSSHIPMENTS = "9x4PdTRa_FehBFX2HCQHMXAGRshlFj5AFg6zUe3MAA4";
// Earnings
private static String EARNINGS = "n5BDnJ787UBXuYdBVhZsGdcf-yv51kyz0roptFdC3S8";
// Ʒȱ stockout
private static String GOODSSTOCKOUT = "Kfk7pITiatD9GiR84Hi99NU5jAFZ6ttBhI23elmOuIQ";
private static String MESSAGE_TYPE_NEWORDERS = "neworders";
private static String MESSAGE_TYPE_ORDERSSHIPMENTS = "ordersshipments";
private static String MESSAGE_TYPE_EARNINGS = "earnings";
private static String MESSAGE_TYPE_GOODSSTOCKOUT = "goodsstockout";
public String sendWXMes(String type, Map mesinfo)
throws Exception {
String jsoninfo = null;
if (MESSAGE_TYPE_NEWORDERS.equals(type.trim())) {
// ֧ɹ֪ͨ
jsoninfo = TemplateMes.sendCaptcha(mesinfo);
System.out.println(jsoninfo);
} else if (MESSAGE_TYPE_ORDERSSHIPMENTS.equals(type.trim())) {
//
jsoninfo = TemplateMes.sendRebate(mesinfo);
System.out.println(jsoninfo);
} else if (MESSAGE_TYPE_EARNINGS.equals(type.trim())) {
//
jsoninfo = TemplateMes.sendgoodcode(mesinfo);
System.out.println(jsoninfo);
} else if (MESSAGE_TYPE_GOODSSTOCKOUT.equals(type.trim())) {
//
jsoninfo = TemplateMes.sendgoodsstockout(mesinfo);
System.out.println(jsoninfo);
}
String strUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + at.getToken();
System.out.println(at.getToken());
return HttpClientUtils.postJSON(strUrl, jsoninfo);
}
// ¶֪ͨ
private static String sendCaptcha(Map mesinfo) {
String jsoninfo = "{\"template_id\": \"" + NEWORDERS + "\",\"topcolor\": \"#FF0000\",\"touser\": \"" + mesinfo.get("openid") + "\",\"url\": \"" + mesinfo.get("url") + "\", "
+ "\"data\":"
+ "{\"first\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("first") + "\" },"
+ "\"orderno\": {\"color\": \"#173177\",\"value\":\"" + mesinfo.get("orderno") + "\"}, "
+ "\"refundno\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("refundno") + "\"},"
+ "\"refundproduct\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("refundproduct") + "\"},"
+ "\"remark\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("remark") + "\" }}}";
return jsoninfo;
}
// ̶
private static String sendRebate(Map mesinfo) {
String jsoninfo = "{\"template_id\": \"" + ORDERSSHIPMENTS + "\",\"topcolor\": \"#FF0000\",\"touser\": \"" + mesinfo.get("openid") + "\",\"url\": \"" + mesinfo.get("url") + "\", "
+ "\"data\":"
+ "{\"first\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("first") + "\" },"
+ "\"orderno\": {\"color\": \"#173177\",\"value\":\"" + mesinfo.get("orderno") + "\"}, "
+ "\"refundno\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("refundno") + "\"},"
+ "\"refundproduct\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("refundproduct") + "\"},"
+ "\"remark\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("remark") + "\" }}}";
return jsoninfo;
}
//
private static String sendgoodcode(Map mesinfo) {
String jsoninfo = "{\"template_id\": \"" + EARNINGS + "\",\"topcolor\": \"#FF0000\",\"touser\": \"" + mesinfo.get("openid") + "\",\"url\": \"" + mesinfo.get("url") + "\", "
+ "\"data\":"
+ "{\"first\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("first") + "\" },"
+ "\"keyword1\": {\"color\": \"#173177\",\"value\":\"" + mesinfo.get("keyword1") + "\"}, "
+ "\"keyword2\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("keyword2") + "\"},"
+ "\"keyword3\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("keyword3") + "\"},"
+ "\"keyword4\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("keyword4") + "\"},"
+ "\"remark\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("remark") + "\" }}}";
return jsoninfo;
}
//Ʒȱ
private static String sendgoodsstockout(Map mesinfo) {
String jsoninfo = "{\"template_id\": \"" + GOODSSTOCKOUT + "\",\"topcolor\": \"#FF0000\",\"touser\": \"" + mesinfo.get("openid") + "\",\"url\": \"" + mesinfo.get("url") + "\", "
+ "\"data\":"
+ "{\"first\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("first") + "\" },"
+ "\"keyword1\": {\"color\": \"#173177\",\"value\":\"" + mesinfo.get("keyword1") + "\"}, "
+ "\"keyword2\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("keyword2") + "\"},"
+ "\"remark\": {\"color\": \"#173177\",\"value\": \"" + mesinfo.get("remark") + "\" }}}";
return jsoninfo;
}
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/service/TemplateMesService.java
================================================
package com.lida.mongo.weixin.service;
public class TemplateMesService {
/*
*//**
* ¶ģϢ
*//*
public void neworders(String order_sn){
//ȡϢ
YlOrderInfo ylOrderInfo=ylOrderInfoDao.neworder(order_sn);
//ȡҵԱϢ
List list=yeEtWxBindDao.getopenid(ylOrderInfo.getService_id());
String goodsnumber=String.valueOf(ylOrderInfo.getGoods_number());
System.out.println(goodsnumber);
//ʱת
String addtime=yeEtWxBindDao.TimeStamp2Date(ylOrderInfo.getAdd_time());
for(int i=0;i mesinfo = new HashMap();
mesinfo.put("openid", "oETn-sqq2T92ncxeAR_Xvdd12L68");//openid oETn-sqq2T92ncxeAR_Xvdd12L68
mesinfo.put("url", "http://m.ysh365.com");//Ժתӵַ
mesinfo.put("first", "ã̳յһ¶ȴ");
mesinfo.put("orderno", order_sn);//
mesinfo.put("refundno",goodsnumber);//Ʒ
mesinfo.put("refundproduct", ylOrderInfo.getOrder_amount()+"Ԫ");//Ʒ
mesinfo.put("remark", "µʱ:"+addtime+","+"µ磬СƽһʱΪ");
try {
String res= templateMes.sendWXMes("neworders", mesinfo);
System.out.println(res);
} catch (Exception e) {
e.printStackTrace();
}
}
}
*//**
* ̷
*//*
public void ordersshipments(String order_sn) {
Map mesinfo = new HashMap();
//ȡӶϢ
YeOrderInfo yeOrderInfo=yeOrderInfoDao.getyeordersn(order_sn);
//ѯĻԱ
List list=yeEtWxBindDao.getopenid(yeOrderInfo.getSupply_id());
//ʱת
String addtime=yeEtWxBindDao.TimeStamp2Date(yeOrderInfo.getAdd_time());
for(int i=0;i list=yeEtWxBindDao.getopenid(yeOrderInfo.getSupply_id());
//ʱת
String addtime=yeEtWxBindDao.TimeStamp2Date(yeOrderInfo.getAdd_time());
for(int i=0;i mesinfo = new HashMap();
mesinfo.put("openid", "oETn-sqq2T92ncxeAR_Xvdd12L68");//openid
mesinfo.put("url", "http://m.ysh365.com");//Ժתӵַ
mesinfo.put("first", "û,һ涩");
mesinfo.put("keyword1", order_sn);//
mesinfo.put("keyword2", yeOrderInfo.getOrder_amount()+"");//ѽ
mesinfo.put("keyword3", addtime);//֧ʱ
mesinfo.put("keyword4", "");//
mesinfo.put("remark", "µ~~ֱԣСƽһʱΪ");
try {
String res= templateMes.sendWXMes("earnings", mesinfo);
System.out.println(res);
} catch (Exception e) {
e.printStackTrace();
}
}
}
*//**
* ƷȱԤ
*//*
public void goodsstockout(int product_id) {
Map mesinfo = new HashMap();
YeEtSupplyProducts yeEtSupplyProducts=yeEtSupplyProductsDao.stock(product_id);
mesinfo.put("openid", "oETn-sqq2T92ncxeAR_Xvdd12L68");//openid
mesinfo.put("url", "http://m.ysh365.com");//Ժתӵַ
mesinfo.put("first", "Ĺ̻Ա,һƷ汨");
mesinfo.put("keyword1", yeEtSupplyProducts.getGoods_name());//Ʒ
mesinfo.put("keyword2", "ʣ"+yeEtSupplyProducts.getStock());//Ч
mesinfo.put("remark", "뼰ʱӿ,µ~~ֱԣСƽһʱΪ");
try {
String res= templateMes.sendWXMes("goodsstockout", mesinfo);
System.out.println(res);
} catch (Exception e) {
e.printStackTrace();
}
}
*/
}
================================================
FILE: src/main/java/com/lida/mongo/weixin/service/WeatherService.java
================================================
package com.lida.mongo.weixin.service;
import com.lida.mongo.util.HttpRequestUtil;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WeatherService {
public static String urlEncodeGBK(String source) {
String result = source;
try {
result = java.net.URLEncoder.encode(source, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* ??????????XML?????????
*
* @param source
* @return
*/
public static String getWeatherXml(String source, int day) {
String dst = null;
// ?????????
String requestUrl = "http://php.weather.sina.com.cn/xml.php?city={keyWord}&password=DJOYnieT8234jlsK&day=" + day;
// ?????q???????urlEncode utf-8????
requestUrl = requestUrl.replace("{keyWord}", HttpRequestUtil.urlEncode(source, "GBK"));
dst = HttpRequestUtil.httpRequest(requestUrl);
return dst;
}
/**
* ????????????????????????????????
*
* @param source
* @return
*/
public static String getWeatherInfo(String source) {
StringBuffer buffer = new StringBuffer();
buffer.append(source).append(" ??????????????????????\n\n");
for (int i = 0; i < 3; i++) {
String weatherXml = getWeatherXml(source, i);
if (null == weatherXml || "".equals(weatherXml))
return "";
String status1 = "";
String direction1 = "";
String temperature1 = "";
String temperature2 = "";
String savedate_weather = "";
String ssd_l = "";
String yd_s = "";
Pattern p = Pattern.compile("(.*)()(.*?)()(.*)");
Matcher m = p.matcher(weatherXml);
if (m.matches())
status1 = m.group(3);
if (null == status1 || "".endsWith(status1))
return "";
p = Pattern.compile("(.*)()(.*?)()(.*)");
m = p.matcher(weatherXml);
if (m.matches())
direction1 = m.group(3);
p = Pattern.compile("(.*)()(.*?)()(.*)");
m = p.matcher(weatherXml);
if (m.matches())
temperature1 = m.group(3);
p = Pattern.compile("(.*)()(.*?)()(.*)");
m = p.matcher(weatherXml);
if (m.matches())
temperature2 = m.group(3);
p = Pattern.compile("(.*)()(.*?)()(.*)");
m = p.matcher(weatherXml);
if (m.matches())
savedate_weather = m.group(3);
p = Pattern.compile("(.*)()(.*?)()(.*)");
m = p.matcher(weatherXml);
if (m.matches())
ssd_l = m.group(3);
p = Pattern.compile("(.*)()(.*?)()(.*)");
m = p.matcher(weatherXml);
if (m.matches())
yd_s = m.group(3);
buffer.append(savedate_weather).append("\n").append(status1).append(" ").append(direction1).append(" ").append(temperature2)
.append("??-").append(temperature1).append("?? ").append(ssd_l).append("\n").append("????????").append(yd_s).append("\n\n");
}
return (null == buffer ? "" : buffer.toString());
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(getWeatherInfo("当家花旦"));
}
}
================================================
FILE: src/main/java/light/mvc/controller/base/BaseController.java
================================================
package light.mvc.controller.base;
import light.mvc.utils.StringEscapeEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
@RequestMapping("/base")
public class BaseController {
protected int page = 1;// 当前页
protected int rows = 10;// 每页显示记录数
protected String sort;// 排序字段
protected String order = "asc";// asc/desc
protected String ids;// 主键集合,逗号分割
@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
/**
* 自动转换日期类型的字段格式
*/
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
/**
* 防止XSS攻击
*/
binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
}
/**
* 用户跳转JSP页面
*
* 此方法不考虑权限控制
*
* @param folder
* 路径
* @param jspName
* JSP名称(不加后缀)
* @return 指定JSP页面
*/
@RequestMapping("/{folder}/{jspName}")
public String redirectJsp(@PathVariable String folder, @PathVariable String jspName) {
return "/" + folder + "/" + jspName;
}
}
================================================
FILE: src/main/java/light/mvc/controller/manual/EFManualCategoryController.java
================================================
package light.mvc.controller.manual;
import light.mvc.controller.base.BaseController;
import light.mvc.pageModel.base.Grid;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.base.Tree;
import light.mvc.pageModel.manual.EFExpertList;
import light.mvc.pageModel.manual.EFmanualCategory;
import light.mvc.pageModel.sys.User;
import light.mvc.service.manual.EFManualCategoryServiceI;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
@RequestMapping("/manualCategory")
public class EFManualCategoryController extends BaseController{
@Autowired
private EFManualCategoryServiceI categoryService;
@RequestMapping("/getPage")
public String categoryPage(HttpServletRequest request) {
List rootList = categoryService.getByPid((long)0);
request.setAttribute("rootList", rootList);
return "/eumode/manual/category";
}
@RequestMapping("/dataGrid")
@ResponseBody
public Grid dataGrid(EFmanualCategory category, PageFilter ph) {
// spring自动将参数注入到ph对象中
Grid grid = new Grid();
grid.setRows(categoryService.dataGrid(category, ph));
grid.setTotal(categoryService.count(category, ph));
return grid;
}
@RequestMapping("/treeGrid")
@ResponseBody
public List treeGrid(EFmanualCategory category, PageFilter ph) {
// spring自动将参数注入到ph对象中
return categoryService.treeGrid(category);
}
@RequestMapping("/getAllManualTree")
@ResponseBody
public List getAllManualTree() {
return categoryService.allTree();
}
@RequestMapping("/getManualTreeByCode")
@ResponseBody
public List getManualTreeByCode(HttpServletRequest request,String categoryRoot) {
if(categoryRoot==null)
{
categoryRoot="";
}
return categoryService.getTreeByCode(categoryRoot);
}
@ResponseBody
@RequestMapping("/getExpertByCategory")
public List getExpertByCategory(Long id)
{
EFExpertList expertList =categoryService.getExpertList(id);
return expertList.getList();
}
@RequestMapping("/delete")
@ResponseBody
public Json delete(String ids,HttpServletRequest request) {
JSONArray jsonIds;
Json j = new Json();
try {
jsonIds = new JSONArray(ids);
for (int i = 0; i < jsonIds.length(); i++) {
long id = jsonIds.getLong(i);
categoryService.delete(id,request);
}
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/addPage")
public String addPage(HttpServletRequest request,String categoryRoot) {
request.setAttribute("categoryRoot", categoryRoot);
return "/eumode/manual/categoryAdd";
}
@RequestMapping("/editPage")
public String getEditPage(HttpServletRequest request,Long id,String categoryRoot) {
EFmanualCategory category = categoryService.get(id);
request.setAttribute("category", category);
request.setAttribute("categoryRoot", categoryRoot);
return "/eumode/manual/categoryEdit";
}
@RequestMapping("/edit")
@ResponseBody
public Json edit(EFmanualCategory nobj) {
Json j = new Json();
try {
categoryService.edit(nobj);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/add")
@ResponseBody
public Json add(EFmanualCategory nobj) {
Json j = new Json();
try {
categoryService.add(nobj);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/getRootCategory")
@ResponseBody
public Json getRootCategory() {
Json j = new Json();
try {
List rootList=categoryService.getByPid((long)0);
j.setObj(rootList);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
}
================================================
FILE: src/main/java/light/mvc/controller/manual/EFManualContentController.java
================================================
package light.mvc.controller.manual;
import light.mvc.controller.base.BaseController;
import light.mvc.pageModel.base.Grid;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.manual.EFmanualCategory;
import light.mvc.pageModel.manual.EFmanualContent;
import light.mvc.pageModel.manual.EFmanualKeyword;
import light.mvc.pageModel.sys.EFResourceMeta;
import light.mvc.service.manual.EFManualCategoryServiceI;
import light.mvc.service.manual.EFManualContentServiceI;
import light.mvc.service.manual.EFManualKeywordServiceI;
import light.mvc.service.sys.DictionaryServiceI;
import light.mvc.service.sys.ResourceMetaServiceI;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/manualContent")
public class EFManualContentController extends BaseController{
@Autowired
private EFManualContentServiceI contentService;
@Autowired
private EFManualCategoryServiceI categoryService;
@Autowired
private EFManualKeywordServiceI keywordService;
@Autowired
private DictionaryServiceI dictService;
@Autowired
private ResourceMetaServiceI resourceMetaService;
@RequestMapping("/getPage")
public String get_news_page() {
return "/eumode/manual/manual";
}
@RequestMapping("/dataGrid")
@ResponseBody
public Grid data_grid(EFmanualContent content, PageFilter ph) {
// spring自动将参数注入到ph对象中
Grid grid = new Grid();
grid.setRows(contentService.dataGrid(content, ph));
grid.setTotal(contentService.count(content, ph));
return grid;
}
@RequestMapping("/delete")
@ResponseBody
public Json delete(String ids,HttpServletRequest request) {
JSONArray jsonIds;
Json j = new Json();
try {
jsonIds = new JSONArray(ids);
for (int i = 0; i < jsonIds.length(); i++) {
long id = jsonIds.getLong(i);
EFmanualKeyword kw = new EFmanualKeyword();
kw.setManualContentID(id);
List keywordlist = keywordService.getAllKeyword(kw);
for(EFmanualKeyword mk : keywordlist){
keywordService.delete(mk.getAutoID());
}
List attachmentlist = resourceMetaService.get(id, dictService.getDictionary("ResourceMetaType", "Knowledge").getId());
if(attachmentlist != null && attachmentlist.size() > 0){
for(EFResourceMeta rm : attachmentlist){
resourceMetaService.delete(rm.getAutoID());
}
}
contentService.delete(id);
}
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/addPage")//知识库添加
public String addPage(HttpServletRequest request) {
request.setAttribute("categoryRoot", "Variety");
return "/eumode/manual/manualAdd";
}
@RequestMapping("/addVarietyPage")//知识库添加
public String addVarietyPage(HttpServletRequest request) {
request.setAttribute("categoryRoot", "Variety");
return "/eumode/manual/manualAdd";
}
@RequestMapping("/addIndustryPage")//知识库添加
public String addIndustryPage(HttpServletRequest request) {
request.setAttribute("categoryRoot", "Industry");
return "/eumode/manual/manualAdd";
}
@RequestMapping("/addAchievementPage")//知识库添加
public String addAchievementPage(HttpServletRequest request) {
request.setAttribute("categoryRoot", "Achievement");
return "/eumode/manual/manualAdd";
}
@RequestMapping("/addTechnologyPage")//知识库添加
public String addTechnologyPage(HttpServletRequest request) {
request.setAttribute("categoryRoot", "Technology");
return "/eumode/manual/manualAdd";
}
@RequestMapping("/detailPage")//知识库详情
public String viewDetailPage(Long id, HttpServletRequest request) {
EFmanualKeyword kw = new EFmanualKeyword();
kw.setManualContentID(id);
List keywordlist = keywordService.getAllKeyword(kw);
EFmanualContent content = contentService.get(id);
EFmanualCategory mc = categoryService.get(content.getManualCategoryID());
List mcList = new ArrayList();
while(mc != null){
mcList.add(mc);
if(mc.getParentID() != null && mc.getParentID() > 0){
mc = categoryService.get(mc.getParentID());
}
else{
mc = null;
}
}
if(mcList.size() > 0){
String categoryList = "";
for(EFmanualCategory category : mcList){
categoryList += category.getCategoryName() + "<--";
}
categoryList = categoryList.substring(0, categoryList.length() - 3);
request.setAttribute("categoryList", categoryList);
}
if(content != null){
request.setAttribute("manualContent", content);
}
if(keywordlist != null && keywordlist.size() > 0){
String keyworddesc = "";
for(EFmanualKeyword mk : keywordlist){
keyworddesc += mk.getKeyword() + ",";
}
keyworddesc = keyworddesc.substring(0, keyworddesc.length() - 1);
request.setAttribute("keywordList", keyworddesc);
}
if(content.getFilePath() != null && content.getFilePath().length() > 0){
List attachmentlist = resourceMetaService.get(content.getAutoID(), dictService.getDictionary("ResourceMetaType", "Knowledge").getId());
request.setAttribute("attachmentList", attachmentlist);
}
return "/eumode/manual/manualDetail";
}
@RequestMapping("/add")
@ResponseBody
public Json add(EFmanualContent nobj) {
//System.out.println("addnews");
Json j = new Json();
try {
nobj.setCategoryCode(categoryService.get(nobj.getManualCategoryID()).getCategoryCode());
Long manualID = null;
if(nobj.getAttachmentContent() != null && nobj.getAttachmentContent().length() > 0){
List rmlist = new ArrayList();
String filenamelist = "";
String[] attachmentList = nobj.getAttachmentContent().split(";");
for(String attachment : attachmentList)
{
if(attachment.length() == 0)
continue;
String[] arrayList = attachment.split("\\^");
String attachmentName = arrayList[0];
String attachmentPath = arrayList[1];
filenamelist += attachmentName + ";";
EFResourceMeta rm = new EFResourceMeta();
rm.setType(dictService.getDictionary("ResourceMetaType", "Knowledge").getId());
rm.setMetaPath(attachmentPath);
rm.setMetaDescription(attachmentName);
rmlist.add(rm);
}
if(filenamelist.length() > 0){
filenamelist = filenamelist.substring(0, filenamelist.length() - 1);
}
nobj.setFilePath(filenamelist);
nobj.setContent("");
manualID = contentService.add(nobj);
if(manualID > 0 && rmlist.size() > 0){
for(EFResourceMeta rm : rmlist){
rm.setMetaID(manualID);
resourceMetaService.add(rm);
}
}
}
else if(nobj.getPageContent() != null && nobj.getPageContent().length() > 0){
nobj.setContent(java.net.URLDecoder.decode(nobj.getPageContent(), "UTF-8"));
manualID=contentService.add(nobj);
}
if(manualID != null && manualID > 0)
{
if(nobj.getKeywordList()!=null&&nobj.getKeywordList().length()>0)
{
String[] keywordList= nobj.getKeywordList().split(",");
for(String keyword: keywordList)
{
EFmanualKeyword mk = new EFmanualKeyword();
mk.setCategoryCode(nobj.getCategoryCode());
mk.setCategoryID(nobj.getManualCategoryID());
mk.setKeyword(keyword);
mk.setManualContentID(manualID);
keywordService.add(mk);
}
}
/*
if(nobj.getAttachmentContent() != null && nobj.getAttachmentContent().length() > 0){
String[] attachmentList = nobj.getAttachmentContent().split(";");
for(String attachment : attachmentList)
{
if(attachment.length() == 0)
continue;
String[] arrayList = attachment.split("\\^");
String attachmentName = arrayList[0];
String attachmentPath = arrayList[1];
EFResourceMeta rm = new EFResourceMeta();
rm.setType(dictService.getDictionary("ResourceMetaType", "NewsInformation").getId());
rm.setMetaID(manualID);
rm.setMetaPath(attachmentPath);
rm.setMetaDescription(attachmentName);
resourceMetaService.add(rm);
}
}
*/
}
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
//允许上传的文件后缀
private static String fileExt = "jpg,jpeg,bmp,gif,png,pdf";
//上传文件的大小限制,10M
private static Long maxSize = 10485760L;
// 0:不建目录 1:按天存入目录 2:按月存入目录 3:按扩展名存目录 建议使用按天存
private static String dirType = "1";
//上传文件存储目录
private static String baseAttachmentDir = "/uploadfile/manual_attachment/";
/*
* 上传文件操作
* @param request, response
* @return
* */
@RequestMapping("/getUploadFile")
@ResponseBody
public void getUploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/html; charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
String err = "";
String newFileName = "";
//System.out.println("up");
if ("application/octet-stream".equals(request.getContentType())) { //HTML 5 上传
try {
String dispoString = request.getHeader("Content-Disposition");
int iFindStart = dispoString.indexOf("name=\"")+6;
int iFindEnd = dispoString.indexOf("\"", iFindStart);
iFindStart = dispoString.indexOf("filename=\"")+10;
iFindEnd = dispoString.indexOf("\"", iFindStart);
String sFileName = dispoString.substring(iFindStart, iFindEnd);
int i = request.getContentLength();
byte buffer[] = new byte[i];
int j = 0;
while(j < i) { //获取表单的上传文件
int k = request.getInputStream().read(buffer, j, i-j);
j += k;
}
if (buffer.length == 0) { //文件是否为空
printInfo(response, "上传文件不能为空", "");
return;
}
if (maxSize > 0 && buffer.length > maxSize) { //检查文件大小
printInfo(response, "上传文件的大小超出限制", "");
return;
}
String filepathString = getSaveFilePath(sFileName, request, response);
if ("不允许上传此类型的文件".equals(filepathString)) return; //检查文件类型
//System.out.println("newFileName:" + request.getSession().getServletContext().getRealPath("") + filepathString);
OutputStream out=new BufferedOutputStream(new FileOutputStream(request.getSession().getServletContext().getRealPath("") + filepathString,true));
out.write(buffer);
out.close();
newFileName = request.getContextPath() + filepathString;
} catch (Exception ex) {
System.out.println(ex.getMessage());
newFileName = "";
err = "错误: " + ex.getMessage();
}
}
else{
Boolean mulipart = ServletFileUpload.isMultipartContent(request);
if(!mulipart)
{
printInfo(response, "上传格式错误", "");
return;
}
//以下部分供上传附件使用
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List fileList = multipartRequest.getFiles("Filedata");
try {
for (MultipartFile mf : fileList) {
if(mf.isEmpty()){
continue;
}
CommonsMultipartFile cf= (CommonsMultipartFile)mf;
DiskFileItem fi = (DiskFileItem)cf.getFileItem();
String fileNameLong = fi.getName(); //获取文件上传路径名称
fileNameLong = fileNameLong.replaceAll("^", "");
if (mf.getSize() == 0) { //文件是否为空
printInfo(response, "上传文件不能为空", "");
return;
}
if (maxSize > 0 && mf.getSize() > maxSize) { //检查文件大小
printInfo(response, "上传文件的大小超出限制", "");
return;
}
String filepathString = getSaveFilePath(fileNameLong, request, response);
if ("不允许上传此类型的文件".equals(filepathString)) return; //检查文件类型
OutputStream out=new BufferedOutputStream(new FileOutputStream(request.getSession().getServletContext().getRealPath("") + filepathString,true));
out.write(mf.getBytes());
out.close();
newFileName += fileNameLong + "^" + request.getContextPath() + filepathString + ";";
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
newFileName = "";
err = "错误: " + ex.getMessage();
}
}
printInfo(response, err, newFileName);
}
private String getSaveFilePath(String sFileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
/*获取文件扩展名*/
/*索引加1的效果是只取xxx.jpg的jpg*/
String extensionName = sFileName.substring(sFileName.lastIndexOf(".") + 1);
extensionName = extensionName.toLowerCase();
//System.out.println("extensionName:" + extensionName);
/*检查文件类型*/
if (("," + fileExt.toLowerCase() + ",").indexOf("," + extensionName + ",") < 0){
printInfo(response, "不允许上传此类型的文件", "");
return "不允许上传此类型的文件";
}
//0:不建目录, 1:按天存入目录, 2:按月存入目录, 3:按扩展名存目录.建议使用按天存.
String fileFolder = "";
if (dirType.equalsIgnoreCase("1"))
fileFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
if (dirType.equalsIgnoreCase("2"))
fileFolder = new SimpleDateFormat("yyyyMM").format(new Date());
if (dirType.equalsIgnoreCase("3"))
fileFolder = extensionName;
/*文件存储的相对路径*/
String saveDirPath = "";
saveDirPath = baseAttachmentDir + fileFolder + "/";
//System.out.println("saveDirPath:" + saveDirPath);
/*文件存储在容器中的绝对路径*/
String saveFilePath = request.getSession().getServletContext().getRealPath("") + saveDirPath;
//System.out.println("saveFilePath:" + saveFilePath);
/*构建文件目录以及目录文件*/
File fileDir = new File(saveFilePath);
if (!fileDir.exists()) {fileDir.mkdirs();}
/*重命名文件*/
String filename = UUID.randomUUID().toString();
return saveDirPath + filename + "." + extensionName;
}
/**
* 使用I/O流输出 json格式的数据
* @param response
* @param err
* @param newFileName
* @throws IOException
*/
private void printInfo(HttpServletResponse response, String err, String newFileName) throws IOException {
PrintWriter out = response.getWriter();
//String filename = newFileName.substring(newFileName.lastIndexOf("/") + 1);
out.println("{\"err\":\"" + err + "\",\"msg\":\"" + newFileName + "\"}");
out.flush();
out.close();
}
}
================================================
FILE: src/main/java/light/mvc/controller/news/EFCategoryController.java
================================================
package light.mvc.controller.news;
import light.mvc.controller.base.BaseController;
import light.mvc.pageModel.base.Grid;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.news.EFCategory;
import light.mvc.pageModel.sys.Dictionary;
import light.mvc.service.news.EFCategoryServiceI;
import light.mvc.service.sys.DictionaryServiceI;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
@RequestMapping("/category")
public class EFCategoryController extends BaseController{
@Autowired
private EFCategoryServiceI categoryService;
@Autowired
private DictionaryServiceI dictService;
/**
* 跳转到列表页面
* @return
*/
@RequestMapping("/getPage")
public String categoryPage(HttpServletRequest request) {
List typeList = dictService.combox("NewsCategoryType");
request.setAttribute("typeList", typeList);
return "/eumode/news/category";
}
/**
* 获取列表数据
* @param category
* @param ph
* @return
*/
@RequestMapping("/dataGrid")
@ResponseBody
public Grid dataGrid(EFCategory category, PageFilter ph) {
// spring自动将参数注入到ph对象中
Grid grid = new Grid();
List list = categoryService.dataGrid(category, ph);
for(EFCategory t : list){
t.setTypeDesc(dictService.get(t.getType()).getText());
}
grid.setRows(list);
grid.setTotal(categoryService.count(category, ph));
return grid;
}
@RequestMapping("/delete")
@ResponseBody
public Json delete(String ids, HttpServletRequest request) {
JSONArray jsonIds;
Json j = new Json();
try {
jsonIds = new JSONArray(ids);
for (int i = 0; i < jsonIds.length(); i++) {
long id = jsonIds.getLong(i);
categoryService.delete(id,request);
}
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
/**
* 跳转到新增页面
* @param request
* @return
*/
@RequestMapping("/addPage")
public String addPage(HttpServletRequest request) {
List typeList = dictService.combox("NewsCategoryType");
request.setAttribute("typeList", typeList);
return "/eumode/news/categoryAdd";
}
/**
* 新增操作
* @param nobj
* @return
*/
@RequestMapping("/add")
@ResponseBody
public Json add(EFCategory category) {
Json j = new Json();
try {
categoryService.add(category);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
/**
* 跳转到编辑页面
* @param request
* @param id
* @return
*/
@RequestMapping("/editPage")
public String editPage(HttpServletRequest request, Long id) {
EFCategory category = categoryService.get(id);
request.setAttribute("category", category);
List typeList = dictService.combox("NewsCategoryType");
request.setAttribute("typeList", typeList);
return "/eumode/news/categoryEdit";
}
/**
* 更新操作
* @param category
* @return
*/
@RequestMapping("/edit")
@ResponseBody
public Json update(EFCategory category) {
Json j = new Json();
try {
categoryService.edit(category);
j.setSuccess(true);
j.setMsg("编辑成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
}
================================================
FILE: src/main/java/light/mvc/controller/news/EFNewsController.java
================================================
package light.mvc.controller.news;
import light.mvc.controller.base.BaseController;
import light.mvc.pageModel.base.Grid;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.base.SessionInfo;
import light.mvc.pageModel.news.EFCategory;
import light.mvc.pageModel.news.EFNews;
import light.mvc.pageModel.sys.EFResourceMeta;
import light.mvc.service.news.EFCategoryServiceI;
import light.mvc.service.news.EFNewsServiceI;
import light.mvc.service.sys.DictionaryServiceI;
import light.mvc.service.sys.ResourceMetaServiceI;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/news")
public class EFNewsController extends BaseController{
@Autowired
private EFNewsServiceI newsService;
@Autowired
private EFCategoryServiceI categoryService;
@Autowired
private DictionaryServiceI dictService;
@Autowired
private ResourceMetaServiceI resourceMetaService;
/**
* 跳转到列表页面
* @return
*/
@RequestMapping("/newsPage")
public String get_news_page(HttpServletRequest request) {
request.setAttribute("categoryTypeID", dictService.getDictionary("NewsCategoryType", "News").getId());
request.setAttribute("categoryList", getCategoryByTypeId(dictService.getDictionary("NewsCategoryType", "News").getId()));
return "/eumode/news/news";
}
@RequestMapping("/informationPage")
public String get_information_page(HttpServletRequest request) {
request.setAttribute("categoryTypeID", dictService.getDictionary("NewsCategoryType", "Information").getId());
request.setAttribute("categoryList", getCategoryByTypeId(dictService.getDictionary("NewsCategoryType", "Information").getId()));
return "/eumode/news/news";
}
@RequestMapping("/reportPage")
public String get_report_page(HttpServletRequest request) {
request.setAttribute("categoryTypeID", dictService.getDictionary("NewsCategoryType", "Report").getId());
request.setAttribute("categoryList", getCategoryByTypeId(dictService.getDictionary("NewsCategoryType", "Report").getId()));
return "/eumode/news/news";
}
@RequestMapping("/baseConstructionPage")
public String get_baseConstruction(HttpServletRequest request) {
request.setAttribute("categoryTypeID", dictService.getDictionary("NewsCategoryType", "BaseConstruction").getId());
request.setAttribute("categoryList", getCategoryByTypeId(dictService.getDictionary("NewsCategoryType", "BaseConstruction").getId()));
return "/eumode/news/news";
}
private List getCategoryByTypeId(Long id){
EFCategory c = new EFCategory();
c.setType(id);
List categoryList = categoryService.getAllData(c);
return categoryList;
}
/**
* 获取列表数据
* @param news
* @param ph
* @return
*/
@RequestMapping("/dataGrid")
@ResponseBody
public Grid data_grid(EFNews news, Integer selectPersonal, PageFilter ph,HttpServletRequest request) {
Grid grid = new Grid();
SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute("sessionInfo");
news.setPersonalID(sessionInfo.getId()); //默认只搜索出本人添加的记录
if(selectPersonal != null && selectPersonal == 1){
//搜出全部人添加的记录
news.setPersonalID(null);
}
List list = newsService.dataGrid(news, ph);
for(EFNews t : list){
t.setStatusDesc(dictService.get(t.getStatus()).getText());
t.setCategoryName(categoryService.get(t.getCategoryID()).getCategoryName());
}
grid.setRows(list);
grid.setTotal(newsService.count(news,ph));
return grid;
}
/**
* 删除操作
* @param ids
* @param request
* @return
*/
@RequestMapping("/delete")
@ResponseBody
public Json delete(String ids,HttpServletRequest request) {
JSONArray jsonIds;
Json j = new Json();
try {
jsonIds = new JSONArray(ids);
for (int i = 0; i < jsonIds.length(); i++) {
long id = jsonIds.getLong(i);
newsService.delete(id);
//删除相关附件
EFResourceMeta rm = new EFResourceMeta();
rm.setType(dictService.getDictionary("ResourceMetaType", "NewsInformation").getId());
rm.setMetaID(id);
List list = resourceMetaService.dataGrid(rm);
for(EFResourceMeta t : list){
resourceMetaService.delete(t.getAutoID());
}
}
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
/**
* 删除附件操作
* @param ids
* @param request
* @return
*/
@RequestMapping("/deleteAttachment")
@ResponseBody
public Json deleteAttachment(String id, String newsid, HttpServletRequest request){
Json j = new Json();
try {
//删除相关附件
EFResourceMeta rm = resourceMetaService.get(Long.parseLong(id));
if(rm.getType()==dictService.getDictionary("ResourceMetaType", "NewsInformation").getId()
&& rm.getMetaID() == Long.parseLong(newsid)){
resourceMetaService.delete(rm.getAutoID());
j.setMsg("删除附件成功!");
j.setSuccess(true);
}
else{
j.setMsg("没有权限删除该附件!");
}
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
/**
* 跳转到新增页面
* @param request
* @return
*/
@RequestMapping("/addPage")
public String addPage(Long categoryTypeID, HttpServletRequest request) {
EFCategory c = new EFCategory();
c.setType(categoryTypeID);
List categories = categoryService.getAllData(c);
for(EFCategory t:categories){
t.setTypeDesc(dictService.get(t.getType()).getText());
}
request.setAttribute("categories", categories);
if(categoryTypeID == dictService.getDictionary("NewsCategoryType", "Information").getId()){
//通知公告才允许上传附件
request.setAttribute("allowAttachment", true);
}
return "/eumode/news/newsAdd";
}
/**
* 新增操作
* @param nobj
* @return
*/
@RequestMapping("/add")
@ResponseBody
public Json add(EFNews news, HttpServletRequest request) {
Json j = new Json();
//添加额外信息
SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute("sessionInfo");
news.setPersonalID(sessionInfo.getId());//发布者ID
news.setAuthor(sessionInfo.getName());//作者
news.setReadCount(0);//浏览次数默认为0
news.setStatus(dictService.getDictionary("NewsContentStatus", "Edit").getId());//17:编辑 | 18:发布
try {
String fileName = generateTmpArticleFileName(sessionInfo.getId().toString(),request);
String saveFilePath = request.getSession().getServletContext().getRealPath("");
writeContentToFile(news.getPageContent(), saveFilePath + fileName);
news.setContent(fileName);
Long newsId = newsService.add(news);
if(newsId != null)
{
if(news.getAttachmentContent() != null && news.getAttachmentContent().length() > 0){
String[] attachmentList = news.getAttachmentContent().split(";");
for(String attachment : attachmentList)
{
if(attachment.length() == 0)
continue;
String[] arrayList = attachment.split("\\^");
String attachmentName = arrayList[0];
String attachmentPath = arrayList[1];
EFResourceMeta rm = new EFResourceMeta();
rm.setType(dictService.getDictionary("ResourceMetaType", "NewsInformation").getId());
rm.setMetaID(newsId);
rm.setMetaPath(attachmentPath);
rm.setMetaDescription(attachmentName);
resourceMetaService.add(rm);
}
}
}
j.setSuccess(true);
j.setMsg("保存成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
/**
* 跳转到详细页面
* @param id
* @return
*/
@RequestMapping("detailPage")
public String detailPage(Long id, HttpServletRequest request){
EFNews news = newsService.get(id);
if(news != null)
{
String saveFilePath = request.getSession().getServletContext().getRealPath("");
String fileName = news.getContent();
try
{
news.setPageContent(readContentFromFile(saveFilePath + fileName));
}catch(Exception ex){
}
request.setAttribute("news", news);
EFCategory category = categoryService.get(news.getCategoryID());
request.setAttribute("category", category);
EFResourceMeta rm = new EFResourceMeta();
rm.setType(dictService.getDictionary("ResourceMetaType", "NewsInformation").getId());
rm.setMetaID(id);
List list = resourceMetaService.dataGrid(rm);
if(list.size() > 0)
{
request.setAttribute("attachmentList", list);
}
return "/eumode/news/newsDetail";
}
else
{
List categories = categoryService.getAllData(null);
request.setAttribute("categories", categories);
return "/eumode/news/newsAdd";
}
}
/**
* 跳转到编辑页面
* @param id
* @return
*/
@RequestMapping("editPage")
public String editPage(Long id, HttpServletRequest request){
EFNews news = newsService.get(id);
if(news != null)
{
EFCategory category = categoryService.get(news.getCategoryID());
EFCategory c = new EFCategory();
c.setType(category.getType());
List categories = categoryService.getAllData(c);
for(EFCategory t:categories){
t.setTypeDesc(dictService.get(t.getType()).getText());
}
request.setAttribute("categories", categories);
if(category.getType() == dictService.getDictionary("NewsCategoryType", "Information").getId()){
//通知公告才允许上传附件
request.setAttribute("allowAttachment", true);
EFResourceMeta rm = new EFResourceMeta();
rm.setType(dictService.getDictionary("ResourceMetaType", "NewsInformation").getId());
rm.setMetaID(id);
List list = resourceMetaService.dataGrid(rm);
if(list.size() > 0)
{
request.setAttribute("attachmentList", list);
}
}
String saveFilePath = request.getSession().getServletContext().getRealPath("");
String fileName = news.getContent();
try
{
news.setPageContent(readContentFromFile(saveFilePath + fileName));
}catch(Exception ex){
}
request.setAttribute("news", news);
request.setAttribute("cate", category);
return "/eumode/news/newsEdit";
}
else
{
return "/eumode/news/newsAdd";
}
}
/**
* 更新操作
* @param nobj
* @return
*/
@RequestMapping("/edit")
@ResponseBody
public Json edit(EFNews news, HttpServletRequest request) {
Json j = new Json();
SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute("sessionInfo");
EFNews oldnews = newsService.get(news.getAutoID());
try {
String fileName = oldnews.getContent();
String saveFilePath = request.getSession().getServletContext().getRealPath("");
writeContentToFile(news.getPageContent(), saveFilePath + fileName);
news.setContent(oldnews.getContent());
newsService.edit(news);
if(news.getAttachmentContent() != null && news.getAttachmentContent().length() > 0){
String[] attachmentList = news.getAttachmentContent().split(";");
for(String attachment : attachmentList)
{
if(attachment.length() == 0)
continue;
String[] arrayList = attachment.split("\\^");
String attachmentName = arrayList[0];
String attachmentPath = arrayList[1];
EFResourceMeta rm = new EFResourceMeta();
rm.setType(dictService.getDictionary("ResourceMetaType", "NewsInformation").getId());
rm.setMetaID(news.getAutoID());
rm.setMetaPath(attachmentPath);
rm.setMetaDescription(attachmentName);
resourceMetaService.add(rm);
}
}
j.setSuccess(true);
j.setMsg("编辑成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/publish")
@ResponseBody
public Json publish(Long id, HttpServletRequest request){
Json j = new Json();
Long publishFlagVal = dictService.getDictionary("NewsContentStatus", "Publish").getId();
try {
String saveFilePath = request.getSession().getServletContext().getRealPath("");
EFNews news = newsService.get(id);
String fileName = news.getContent();
String pageContent = readContentFromFile(saveFilePath + fileName);
pageContent = java.net.URLDecoder.decode(pageContent, "UTF-8");
String template = "%s%s";
pageContent = String.format(template, news.getTitle(), pageContent);
String webFileName = "";
if(news.getWebPath() == null || news.getWebPath().length() == 0){
webFileName = generateWebSitePath(request);
}
else{
webFileName = news.getWebPath();
}
writeContentToFile(pageContent, saveFilePath + webFileName);
news.setWebPath(webFileName);
news.setStatus(publishFlagVal);
newsService.publish(news);
j.setSuccess(true);
j.setMsg("发布成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/unPublish")
@ResponseBody
public Json unPublish(Long id){
Json j = new Json();
Long unPublishFlagVal = dictService.getDictionary("NewsContentStatus", "Edit").getId();
EFNews news = newsService.get(id);
try {
news.setStatus(unPublishFlagVal);
newsService.unPublish(news);
j.setSuccess(true);
j.setMsg("撤回成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
//允许上传的文件后缀
private static String fileExt = "jpg,jpeg,bmp,gif,png,doc,docx,xls,xlsx,pdf";
//上传文件的大小限制,5M
private static Long maxSize = 5242880L;
// 0:不建目录 1:按天存入目录 2:按月存入目录 3:按扩展名存目录 建议使用按天存
private static String dirType = "1";
//上传文件存储目录
private static String baseImageDir = "/uploadfile/article_image/";
//上传文件存储目录
private static String baseAttachmentDir = "/uploadfile/article_attachment/";
/*
* 上传文件操作
* @param request, response
* @return
* */
@RequestMapping("/getUploadFile")
@ResponseBody
public void getUploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/html; charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
String err = "";
String newFileName = "";
if ("application/octet-stream".equals(request.getContentType())) { //HTML 5 上传
try {
String dispoString = request.getHeader("Content-Disposition");
int iFindStart = dispoString.indexOf("name=\"")+6;
int iFindEnd = dispoString.indexOf("\"", iFindStart);
iFindStart = dispoString.indexOf("filename=\"")+10;
iFindEnd = dispoString.indexOf("\"", iFindStart);
String sFileName = dispoString.substring(iFindStart, iFindEnd);
int i = request.getContentLength();
byte buffer[] = new byte[i];
int j = 0;
while(j < i) { //获取表单的上传文件
int k = request.getInputStream().read(buffer, j, i-j);
j += k;
}
if (buffer.length == 0) { //文件是否为空
printInfo(response, "上传文件不能为空", "");
return;
}
if (maxSize > 0 && buffer.length > maxSize) { //检查文件大小
printInfo(response, "上传文件的大小超出限制", "");
return;
}
String filepathString = getSaveFilePath(sFileName, request, response, 1);
if ("不允许上传此类型的文件".equals(filepathString)) return; //检查文件类型
//System.out.println("newFileName:" + request.getSession().getServletContext().getRealPath("") + filepathString);
OutputStream out=new BufferedOutputStream(new FileOutputStream(request.getSession().getServletContext().getRealPath("") + filepathString,true));
out.write(buffer);
out.close();
newFileName = request.getContextPath() + filepathString;
} catch (Exception ex) {
System.out.println(ex.getMessage());
newFileName = "";
err = "错误: " + ex.getMessage();
}
}
else{
Boolean mulipart = ServletFileUpload.isMultipartContent(request);
if(!mulipart)
{
printInfo(response, "上传格式错误", "");
return;
}
//以下部分供上传附件使用
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List fileList = multipartRequest.getFiles("Filedata");
try {
for (MultipartFile mf : fileList) {
if(mf.isEmpty()){
continue;
}
CommonsMultipartFile cf= (CommonsMultipartFile)mf;
DiskFileItem fi = (DiskFileItem)cf.getFileItem();
String fileNameLong = fi.getName(); //获取文件上传路径名称
fileNameLong = fileNameLong.replaceAll("^", "");
if (mf.getSize() == 0) { //文件是否为空
printInfo(response, "上传文件不能为空", "");
return;
}
if (maxSize > 0 && mf.getSize() > maxSize) { //检查文件大小
printInfo(response, "上传文件的大小超出限制", "");
return;
}
String filepathString = getSaveFilePath(fileNameLong, request, response, 2);
if ("不允许上传此类型的文件".equals(filepathString)) return; //检查文件类型
OutputStream out=new BufferedOutputStream(new FileOutputStream(request.getSession().getServletContext().getRealPath("") + filepathString,true));
out.write(mf.getBytes());
out.close();
newFileName += fileNameLong + "^" + request.getContextPath() + filepathString + ";";
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
newFileName = "";
err = "错误: " + ex.getMessage();
}
}
printInfo(response, err, newFileName);
}
private String getSaveFilePath(String sFileName, HttpServletRequest request, HttpServletResponse response, int type) throws IOException {
/*获取文件扩展名*/
/*索引加1的效果是只取xxx.jpg的jpg*/
String extensionName = sFileName.substring(sFileName.lastIndexOf(".") + 1);
extensionName = extensionName.toLowerCase();
//System.out.println("extensionName:" + extensionName);
/*检查文件类型*/
if (("," + fileExt.toLowerCase() + ",").indexOf("," + extensionName + ",") < 0){
printInfo(response, "不允许上传此类型的文件", "");
return "不允许上传此类型的文件";
}
//0:不建目录, 1:按天存入目录, 2:按月存入目录, 3:按扩展名存目录.建议使用按天存.
String fileFolder = "";
if (dirType.equalsIgnoreCase("1"))
fileFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
if (dirType.equalsIgnoreCase("2"))
fileFolder = new SimpleDateFormat("yyyyMM").format(new Date());
if (dirType.equalsIgnoreCase("3"))
fileFolder = extensionName;
/*文件存储的相对路径*/
String saveDirPath = "";
if(type == 1){
//文章中的图片
saveDirPath = baseImageDir + fileFolder + "/";
}
else if(type == 2){
//文章中的附件
saveDirPath = baseAttachmentDir + fileFolder + "/";
}
//System.out.println("saveDirPath:" + saveDirPath);
/*文件存储在容器中的绝对路径*/
String saveFilePath = request.getSession().getServletContext().getRealPath("") + saveDirPath;
//System.out.println("saveFilePath:" + saveFilePath);
/*构建文件目录以及目录文件*/
File fileDir = new File(saveFilePath);
if (!fileDir.exists()) {fileDir.mkdirs();}
/*重命名文件*/
String filename = UUID.randomUUID().toString();
return saveDirPath + filename + "." + extensionName;
}
/**
* 使用I/O流输出 json格式的数据
* @param response
* @param err
* @param newFileName
* @throws IOException
*/
private void printInfo(HttpServletResponse response, String err, String newFileName) throws IOException {
PrintWriter out = response.getWriter();
//String filename = newFileName.substring(newFileName.lastIndexOf("/") + 1);
out.println("{\"err\":\"" + err + "\",\"msg\":\"" + newFileName + "\"}");
out.flush();
out.close();
}
//未发布的新闻公告文件
private static String tmpArticleDir = "/tmpArticle/";
private static String tmpArticleExt = ".tmparticle";
/**
* 创建临时文件名称
*/
private String generateTmpArticleFileName(String authorid, HttpServletRequest request)
{
String fileFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
/*文件存储的相对路径*/
String saveDirPath = tmpArticleDir + authorid + "/" + fileFolder + "/";
String saveFilePath = request.getSession().getServletContext().getRealPath("") + saveDirPath;
/*构建文件目录以及目录文件*/
File fileDir = new File(saveFilePath);
if (!fileDir.exists()) {fileDir.mkdirs();}
/*重命名文件*/
String filename = UUID.randomUUID().toString();
return saveDirPath + filename + tmpArticleExt;
}
/**
* 将字符串写入文件
* @param 绝对路径
*/
private void writeContentToFile(String content, String fileName) throws IOException
{
try
{
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileName),"UTF-8");
osw.write(content);
osw.close();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* 从文件读取字符串
* @param 绝对路径
*/
private String readContentFromFile(String fileName) throws IOException
{
String content = "";
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
String data = null;
while((data = br.readLine())!=null)
{
content += data;
}
return content;
}
//发布的新闻公告文件
private static String webSitePath = "/Article/";
/**
* 创建html文件名
*/
private String generateWebSitePath(HttpServletRequest request)
{
String fileFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
/*文件存储的相对路径*/
String saveDirPath = webSitePath + fileFolder + "/";
String saveFilePath = request.getSession().getServletContext().getRealPath("") + saveDirPath;
/*构建文件目录以及目录文件*/
File fileDir = new File(saveFilePath);
if (!fileDir.exists()) {fileDir.mkdirs();}
/*重命名文件*/
String filename = new SimpleDateFormat("hhmmssSSS").format(new Date());
return saveDirPath + filename + ".html";
}
}
================================================
FILE: src/main/java/light/mvc/controller/sensor/apiSensorController.java
================================================
package light.mvc.controller.sensor;
import light.mvc.framework.constant.GlobalConstant;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.sensor.Sensor;
import light.mvc.pageModel.sensor.Station;
import light.mvc.pageModel.sensor.monitoringNode;
import light.mvc.service.sensor.monitoringNodeServiceI;
import light.mvc.service.sensor.pestSensorServiceI;
import light.mvc.service.sensor.stationServiceI;
import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping("/sensorUpdate")
public class apiSensorController {
@Autowired
private monitoringNodeServiceI moniService;
@Autowired
private stationServiceI stationS;
@Autowired
private pestSensorServiceI Service;
@RequestMapping("/updateStation")
@ResponseBody
public Json Update(Long stationId) {
Json j = new Json();
try {
Station station = stationS.get(stationId);
if(station.getType()!=61)
{
j.setSuccess(true);
j.setMsg("该节点无需更新");
return j;
}
Date startUpdateDate = station.getSensorDateUpdate();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String startDateStr=dateFormat.format(startUpdateDate);
startDateStr=startDateStr.replace(' ', 'T');
String[] cookiesByLogin=getCookieByLogin(station.getLoginName(),station.getPassword());
for(String cookieStr:cookiesByLogin)
{
String[] coookieInfo=cookStringToItemString(cookieStr);
String getStationDateURL=GlobalConstant.caipoStationDateURL+"?serial="+station.getSerialNum().toString()+"&group=0&limit=100&verb=FromDate&dtfirst=";
String getData=getStationInfo(getStationDateURL+startDateStr,coookieInfo);
JSONObject jsonObj = new JSONObject(getData);
Long serialNum=jsonObj.getLong("serial_number");
if(!serialNum.equals(station.getSerialNum()))
{
continue;
}
JSONArray array = jsonObj.getJSONArray("data");
monitoringNode node = new monitoringNode();
node.setStation(stationId);
List nodeList= moniService.dataGrid(node, null);
Service.insertApi(array, station,nodeList);
Sensor sLast = Service.getLastSensor(station.getSerialNum());
Date lastDate = new Date(sLast.getCreateDate().getTime()+1000);
stationS.updateSensorLastTime(lastDate,stationId);
}
j.setSuccess(true);
j.setMsg("更新成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
public String[] getCookieByLogin(String loginName, String password)
{
String[] cookieStr= null;
String loginURL= GlobalConstant.caipoLoginURL+"?"+GlobalConstant.caipoLoginName+loginName+"&"+GlobalConstant.caipoPasswork+password;
BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
try {
HttpGet httpget = new HttpGet(loginURL);
CloseableHttpResponse response1 = httpclient.execute(httpget);
try {
HttpEntity entity = response1.getEntity();
EntityUtils.consume(entity);
List cookies = cookieStore.getCookies();
cookieStr=new String[cookies.size()];
if (cookies.isEmpty()) {
System.out.println("cookie is None");
} else {
for (int i = 0; i < cookies.size(); i++) {
cookieStr[i]=new String(cookies.get(i).toString() );
System.out.println("\n( getCookieByLogin(String loginURL) )in cookie i="+i+" "+ cookieStr[i]);
}
}
}catch(Exception e){
System.out.println(e);
}finally {
try {
response1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}catch(Exception e){
System.out.println(e);
} finally {
try {
httpclient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return cookieStr;
}
public static String[] cookStringToItemString(String cookieStr){
String temp[]=cookieStr.split("]");
String dest[]=new String[ temp.length ];
for(int i=0; i monitoringNode = moniService.dataGrid(data, ph);
for(monitoringNode m : monitoringNode){
model.addAttribute(m.getMap(),m.getName());
}
return "/eumode/MoniNode/MoniNodeList";
}
@RequestMapping("/dataGrid")
@ResponseBody
public Grid dataGrid(monitoringNode data, PageFilter ph) {
// spring自动将参数注入到ph对象中
Grid grid = new Grid();
grid.setRows(moniService.dataGrid(data, ph));
grid.setTotal(moniService.count(data, ph));
return grid;
}
@RequestMapping("/getnodeinfo")
@ResponseBody
public List getNodeInfo(@RequestBody JSONObject monitoringNode){
monitoringNode data = new monitoringNode();
data.setStation(monitoringNode.getLong("station"));
PageFilter ph = new PageFilter();
ph.setPage(1);
ph.setSort("type");
ph.setRows(50);
ph.setOrder("asc");
List monitoringNodeList = moniService.dataGrid(data, ph);
return monitoringNodeList;
}
@RequestMapping("/delete")
@ResponseBody
public Json delete(String ids,HttpServletRequest request) {
JSONArray jsonIds;
Json j = new Json();
try {
jsonIds = new JSONArray(ids);
for (int i = 0; i < jsonIds.length(); i++) {
long id = jsonIds.getLong(i);
moniService.delete(id);
}
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/addPage")
public String addPage() {
return "/eumode/MoniNode/MoniNodeAdd";
}
@RequestMapping("/add")
@ResponseBody
public Json add(monitoringNode nobj) {
Json j = new Json();
try {
moniService.add(nobj);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
/*
@RequestMapping("/getMoniNodeInfo")
public String getNodeInfo(HttpServletResponse response,HttpServletRequest request)
{
long nid=Integer.parseInt(request.getParameter("idString"));
monitoringNode n=moniService.get(nid);
request.setAttribute("moniNode_info", n);
List data= pestDataService.getAlldataFromNodeId(nid);
request.setAttribute("node_data", data);
return "/admin/pestMoniNode/MoniNodeInfo";
}
@RequestMapping("/getMoniNodeLocation")
public void getNodeLocation(HttpServletResponse response) throws JSONException//暂时使用该方法
{
List moniN = moniService.getAllData();
PrintWriter out = null;
response.setContentType("text/json");
response.setCharacterEncoding("UTF-8");
JSONArray jsonArray = new JSONArray();
for(int i=0;i moniNodeList = null;
if(data.getStation()!=null&&data.getStation()!=0)
{
Station s = stationS.get(data.getStation());
data.setSerialNum(s.getSerialNum());
// monitoringNode node =new monitoringNode();
// node.setStation(data.getStation());
// moniNodeList =moniService.dataGrid(node, ph);
}
// request.setAttribute("moniNodeList", moniNodeList);
grid.setRows(Service.dataGrid(data, ph));
grid.setTotal(Service.count(data, ph));
return grid;
}
@RequestMapping("/delete")
@ResponseBody
public Json delete(String ids,HttpServletRequest request) {
JSONArray jsonIds;
Json j = new Json();
try {
jsonIds = new JSONArray(ids);
for (int i = 0; i < jsonIds.length(); i++) {
long id = jsonIds.getLong(i);
Service.delete(id,request);
}
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/addPage")
public String addPage() {
return "/eumode/news/newsAdd";
}
@RequestMapping("/add")
@ResponseBody
public Json add(Sensor nobj) {
Json j = new Json();
try {
Service.add(nobj);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/getSearchPage")
public String getSearchPage() {
return "/eumode/sensor/sensorSearch";
}
@RequestMapping("/search")
@ResponseBody
public Json search(Object nobj) {
Json j = new Json();
try {
//Service.add(nobj);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
}
================================================
FILE: src/main/java/light/mvc/controller/sensor/stationController.java
================================================
package light.mvc.controller.sensor;
import light.mvc.controller.base.BaseController;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.Tree;
import light.mvc.pageModel.sensor.Station;
import light.mvc.service.base.ServiceException;
import light.mvc.service.sensor.stationServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping("/station")
public class stationController extends BaseController{
@Autowired
private stationServiceI stationS;
@RequestMapping("/getPage")
public String getPage() {
return "/eumode/station/station";
}
@RequestMapping("/treeGrid")
@ResponseBody
public List treeGrid()
{
return stationS.treeGrid();
}
@RequestMapping("/tree")
@ResponseBody
public List tree(HttpSession session) {
return stationS.tree();
}
@RequestMapping("/addPage")
public String addPage() {
return "/eumode/station/stationAdd";
}
@RequestMapping("/add")
@ResponseBody
public Json add(Station station) {
Json j = new Json();
try {
stationS.add(station);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/get")
@ResponseBody
public Station get(Long id) {
return stationS.get(id);
}
@RequestMapping("/editPage")
public String editPage(HttpServletRequest request,Long id) {
Station o = stationS.get(id);
request.setAttribute("station", o);
return "/eumode/station/pestMoniNodeEdit";
}
@RequestMapping("/edit")
@ResponseBody
public Json edit(Station org) throws InterruptedException {
Json j = new Json();
try {
stationS.edit(org);
j.setSuccess(true);
j.setMsg("编辑成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/delete")
@ResponseBody
public Json delete(Long id) {
Json j = new Json();
try {
stationS.delete(id);
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (ServiceException e) {
j.setMsg(e.getMessage());
}
return j;
}
}
================================================
FILE: src/main/java/light/mvc/controller/sys/DictionaryController.java
================================================
package light.mvc.controller.sys;
import light.mvc.controller.base.BaseController;
import light.mvc.framework.constant.GlobalConstant;
import light.mvc.pageModel.base.Grid;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.sys.Dictionary;
import light.mvc.service.sys.DictionaryServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
@RequestMapping("/dictionary")
public class DictionaryController extends BaseController {
@Autowired
private DictionaryServiceI dictionaryService;
@RequestMapping("/manager")
public String manager() {
return "/eumode/sys/dictionary";
}
@RequestMapping("/combox")
@ResponseBody
public List combox(String code) {
return dictionaryService.combox(code);
}
@RequestMapping("/dataGrid")
@ResponseBody
public Grid dataGrid(Dictionary dictionary, PageFilter ph) {
Grid grid = new Grid();
grid.setRows(dictionaryService.dataGrid(dictionary, ph));
grid.setTotal(dictionaryService.count(dictionary, ph));
return grid;
}
@RequestMapping("/addPage")
public String addPage(HttpServletRequest request) {
request.setAttribute("stateList", GlobalConstant.statelist);
return "/eumode/sys/dictionaryAdd";
}
@RequestMapping("/add")
@ResponseBody
public Json add(Dictionary dictionary) {
Json j = new Json();
Dictionary dic = dictionaryService.checkUnique(dictionary);
if(dic==null){
try {
dictionaryService.add(dictionary);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
}else{
j.setMsg("编码不能重复");
}
return j;
}
@RequestMapping("/delete")
@ResponseBody
public Json delete(Long id) {
Json j = new Json();
try {
dictionaryService.delete(id);
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/get")
@ResponseBody
public Dictionary get(Long id) {
return dictionaryService.get(id);
}
@RequestMapping("/editPage")
public String editPage(HttpServletRequest request,Long id) {
Dictionary dic = dictionaryService.get(id);
request.setAttribute("dictionary", dic);
request.setAttribute("stateList", GlobalConstant.statelist);
return "/eumode/sys/dictionaryEdit";
}
@RequestMapping("/edit")
@ResponseBody
public Json edit(Dictionary dictionary) {
Json j = new Json();
try {
dictionaryService.edit(dictionary);
j.setSuccess(true);
j.setMsg("编辑成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
}
================================================
FILE: src/main/java/light/mvc/controller/sys/DictionarytypeController.java
================================================
package light.mvc.controller.sys;
import light.mvc.controller.base.BaseController;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.Tree;
import light.mvc.pageModel.sys.Dictionarytype;
import light.mvc.service.sys.DictionarytypeServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping("/dictionarytype")
public class DictionarytypeController extends BaseController {
@Autowired
private DictionarytypeServiceI dictionarytypeService;
@RequestMapping("/tree")
@ResponseBody
public List tree(HttpSession session) {
return dictionarytypeService.tree();
}
@RequestMapping("/add")
@ResponseBody
public Json add(Dictionarytype dictionarytype) {
Json j = new Json();
try {
dictionarytypeService.add(dictionarytype);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/delete")
@ResponseBody
public Json delete(Long id) {
Json j = new Json();
dictionarytypeService.delete(id);
j.setMsg("删除成功!");
j.setSuccess(true);
return j;
}
@RequestMapping("/get")
@ResponseBody
public Dictionarytype get(Long id) {
return dictionarytypeService.get(id);
}
@RequestMapping("/edit")
@ResponseBody
public Json edit(Dictionarytype dictionarytype) {
Json j = new Json();
try {
dictionarytypeService.edit(dictionarytype);
j.setSuccess(true);
j.setMsg("编辑成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
}
================================================
FILE: src/main/java/light/mvc/controller/sys/IndexController.java
================================================
package light.mvc.controller.sys;
import light.mvc.controller.base.BaseController;
import light.mvc.framework.constant.GlobalConstant;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.SessionInfo;
import light.mvc.pageModel.sys.User;
import light.mvc.service.sys.ResourceServiceI;
import light.mvc.service.sys.UserServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/admin")
public class IndexController extends BaseController {
@Autowired
private UserServiceI userService;
@Autowired
private ResourceServiceI resourceService;
@RequestMapping("/index")
public String index(HttpServletRequest request) {
SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(GlobalConstant.SESSION_INFO_ADMIN);
request.setAttribute("sessionInfo", sessionInfo);
if ((sessionInfo != null) && (sessionInfo.getId() != null)) {
return "/eumode/index";
}
request.setAttribute("originUrl", "/admin/index");
return "/eumode/login";
}
@ResponseBody
@RequestMapping("/login")
public Json login(User user, HttpSession session) {
Json j = new Json();
User sysuser = userService.login(user);
if (sysuser != null) {
j.setSuccess(true);
j.setMsg("登陆成功!");
SessionInfo sessionInfo = new SessionInfo();
sessionInfo.setId(sysuser.getAutoID());
sessionInfo.setLoginname(sysuser.getLoginName());
sessionInfo.setName(sysuser.getRealName());
// user.setIp(IpUtil.getIpAddr(getRequest()));
sessionInfo.setResourceList(userService.resourceList(sysuser.getAutoID()));
sessionInfo.setResourceAllList(resourceService.resourceAllList());
session.setAttribute(GlobalConstant.SESSION_INFO_ADMIN, sessionInfo);
sessionInfo.setSessionId(session.getId());
// 获取管理员的role类型name属性,回传给客户端进行分类,这里我们认为每个管理员的role类型都只有一个
sessionInfo.setRoleType(sysuser.getRoleNames());
j.setObj(sessionInfo);
} else {
j.setMsg("用户名或密码错误!");
}
return j;
}
@ResponseBody
@RequestMapping("/logout")
public Json logout(HttpSession session) {
Json j = new Json();
if (session != null) {
session.invalidate();
}
j.setSuccess(true);
j.setMsg("注销成功!");
return j;
}
}
================================================
FILE: src/main/java/light/mvc/controller/sys/OrganizationController.java
================================================
package light.mvc.controller.sys;
import light.mvc.controller.base.BaseController;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.Tree;
import light.mvc.pageModel.sys.Organization;
import light.mvc.service.base.ServiceException;
import light.mvc.service.sys.OrganizationServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping("/organization")
public class OrganizationController extends BaseController {
@Autowired
private OrganizationServiceI organizationService;
@RequestMapping("/manager")
public String manager() {
return "/eumode/sys/organization";
}
@RequestMapping("/treeGrid")
@ResponseBody
public List treeGrid() {
return organizationService.treeGrid();
}
@RequestMapping("/tree")
@ResponseBody
public List tree(HttpSession session) {
return organizationService.tree();
}
@RequestMapping("/addPage")
public String addPage() {
return "/eumode/sys/organizationAdd";
}
@RequestMapping("/add")
@ResponseBody
public Json add(Organization organization) {
Json j = new Json();
try {
organizationService.add(organization);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/get")
@ResponseBody
public Organization get(Long id) {
return organizationService.get(id);
}
@RequestMapping("/editPage")
public String editPage(HttpServletRequest request,Long id) {
Organization o = organizationService.get(id);
request.setAttribute("organization", o);
return "/eumode/sys/organizationEdit";
}
@RequestMapping("/edit")
@ResponseBody
public Json edit(Organization org) throws InterruptedException {
Json j = new Json();
try {
organizationService.edit(org);
j.setSuccess(true);
j.setMsg("编辑成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/delete")
@ResponseBody
public Json delete(Long id) {
Json j = new Json();
try {
organizationService.delete(id);
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (ServiceException e) {
j.setMsg(e.getMessage());
}
return j;
}
}
================================================
FILE: src/main/java/light/mvc/controller/sys/PictureCheckCode.java
================================================
package light.mvc.controller.sys;
import light.mvc.controller.base.BaseController;
import light.mvc.framework.constant.GlobalConstant;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.SessionInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@Controller
@RequestMapping("/baseUtil")
public class PictureCheckCode extends BaseController{
private static final long serialVersionUID = 1L;
/*该方法主要作用是获得随机生成的颜色*/
public Color getRandColor(int s,int e){
Random random=new Random ();
if(s>255) s=255;
if(e>255) e=255;
int r,g,b;
r=s+random.nextInt(e-s); //随机生成RGB颜色中的r值
g=s+random.nextInt(e-s); //随机生成RGB颜色中的g值
b=s+random.nextInt(e-s); //随机生成RGB颜色中的b值
return new Color(r,g,b);
}
@RequestMapping("/getCheckCode")
@ResponseBody
public void getCheckCode(HttpSession session,HttpServletRequest request, HttpServletResponse response) throws IOException {
SessionInfo sessionInfo = (SessionInfo) session.getAttribute(GlobalConstant.SESSION_INFO_ADMIN);
//设置不缓存图片
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
//指定生成的响应图片,一定不能缺少这句话,否则错误.
response.setContentType("image/jpeg");
int width=86,height=22; //指定生成验证码的宽度和高度
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 生成随机类
Random random = new Random();
// 设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 设定字体
g.setFont(new Font("Times New Roman", Font.PLAIN, 24));
// 画边框
g.setColor(getRandColor(160, 200));
g.drawRect(0, 0, width - 1, height - 1);
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
// 取随机产生的认证码(4位数字)
String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(rand, 13 * i + 14, 20);
}
// 将认证码存入SESSION
session.setAttribute("vcode", sRand);
System.out.println(sRand);
// 图象生效
g.dispose();
// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
}
@RequestMapping("/CheckCode")
@ResponseBody
public Json checkCode(HttpSession session,String ValidateCode)
{
Json j = new Json();
String code =(String) session.getAttribute("vcode");
if(ValidateCode.equals(code))
{
j.setSuccess(true);
}
else
{
j.setSuccess(false);
}
return j;
}
}
================================================
FILE: src/main/java/light/mvc/controller/sys/ResourceController.java
================================================
package light.mvc.controller.sys;
import light.mvc.controller.base.BaseController;
import light.mvc.framework.constant.GlobalConstant;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.SessionInfo;
import light.mvc.pageModel.base.Tree;
import light.mvc.pageModel.sys.Resource;
import light.mvc.service.sys.ResourceServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping("/resource")
public class ResourceController extends BaseController {
@Autowired
private ResourceServiceI resourceService;
@RequestMapping("/manager")
public String manager() {
return "/eumode/sys/resource";
}
@RequestMapping("/tree")
@ResponseBody
public List tree(HttpSession session) {
SessionInfo sessionInfo = (SessionInfo) session.getAttribute(GlobalConstant.SESSION_INFO_ADMIN);
return resourceService.tree(sessionInfo);
}
@RequestMapping("/allTree")
@ResponseBody
public List allTree(boolean flag) {//true获取全部资源,false只获取菜单资源
return resourceService.allTree(flag);
}
@RequestMapping("/treeGrid")
@ResponseBody
public List treeGrid() {
return resourceService.treeGrid();
}
@RequestMapping("/get")
@ResponseBody
public Resource get(Long id) {
return resourceService.get(id);
}
@RequestMapping("/editPage")
public String editPage(HttpServletRequest request,Long id) {
Resource r = resourceService.get(id);
request.setAttribute("resource", r);
return "/eumode/sys/resourceEdit";
}
@RequestMapping("/edit")
@ResponseBody
public Json edit(Resource resource) throws InterruptedException {
Json j = new Json();
try {
resourceService.edit(resource);
j.setSuccess(true);
j.setMsg("编辑成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/delete")
@ResponseBody
public Json delete(Long id) {
Json j = new Json();
try {
resourceService.delete(id);
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/addPage")
public String addPage() {
return "/eumode/sys/resourceAdd";
}
@RequestMapping("/add")
@ResponseBody
public Json add(Resource resource) {
Json j = new Json();
try {
resourceService.add(resource);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
}
================================================
FILE: src/main/java/light/mvc/controller/sys/RoleController.java
================================================
package light.mvc.controller.sys;
import light.mvc.controller.base.BaseController;
import light.mvc.pageModel.base.Grid;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.base.Tree;
import light.mvc.pageModel.sys.Role;
import light.mvc.service.sys.RoleServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {
@Autowired
private RoleServiceI roleService;
@RequestMapping("/manager")
public String manager() {
return "/eumode/sys/role";
}
@RequestMapping("/dataGrid")
@ResponseBody
public Grid dataGrid(Role role, PageFilter ph) {
// spring自动将参数注入到ph对象中
Grid grid = new Grid();
grid.setRows(roleService.dataGrid(role, ph));
grid.setTotal(roleService.count(role, ph));
return grid;
}
@RequestMapping("/tree")
@ResponseBody
public List tree() {
return roleService.tree();
}
@RequestMapping("/addPage")
public String addPage() {
return "/eumode/sys/roleAdd";
}
@RequestMapping("/add")
@ResponseBody
public Json add(Role role) {
Json j = new Json();
try {
roleService.add(role);
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/delete")
@ResponseBody
public Json delete(Long id) {
Json j = new Json();
try {
roleService.delete(id);
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/get")
@ResponseBody
public Role get(Long id) {
return roleService.get(id);
}
@RequestMapping("/editPage")
public String editPage(HttpServletRequest request, Long id) {
Role r = roleService.get(id);
request.setAttribute("role", r);
return "/eumode/sys/roleEdit";
}
@RequestMapping("/edit")
@ResponseBody
public Json edit(Role role) {
Json j = new Json();
try {
if(role.getIsdefault()==1)
{
Role r2=new Role();
r2.setIsdefault(1);
PageFilter ph = new PageFilter();
if(roleService.count(r2, ph)>0)
{
j.setSuccess(false);
j.setMsg("不能存在多于2个默认角色");
return j;
}
}
roleService.edit(role);
j.setSuccess(true);
j.setMsg("编辑成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/grantPage")
public String grantPage(HttpServletRequest request, Long id) {
Role r = roleService.get(id);
request.setAttribute("role", r);
return "/eumode/sys/roleGrant";
}
@RequestMapping("/grant")
@ResponseBody
public Json grant(Role role) {
Json j = new Json();
try {
roleService.grant(role);
j.setMsg("授权成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
}
================================================
FILE: src/main/java/light/mvc/controller/sys/UserController.java
================================================
package light.mvc.controller.sys;
import com.alibaba.fastjson.JSON;
import light.mvc.controller.base.BaseController;
import light.mvc.framework.constant.GlobalConstant;
import light.mvc.pageModel.base.Grid;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.base.SessionInfo;
import light.mvc.pageModel.sys.EFResourceMeta;
import light.mvc.pageModel.sys.User;
import light.mvc.service.base.ServiceException;
import light.mvc.service.sys.DictionaryServiceI;
import light.mvc.service.sys.ResourceMetaServiceI;
import light.mvc.service.sys.UserServiceI;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
@Autowired
private UserServiceI userService;
@Autowired
private DictionaryServiceI dictionaryService;
@Autowired
private ResourceMetaServiceI resourceMetaService;
@RequestMapping("/manager")
public String manager(HttpServletRequest request) {
request.setAttribute("usertypeJson", JSON.toJSONString(dictionaryService.combox("usertype")));
return "/eumode/sys/user";
}
@RequestMapping("/dataGrid")
@ResponseBody
public Grid dataGrid(User user, PageFilter ph) {
Grid grid = new Grid();
grid.setRows(userService.dataGrid(user, ph));
grid.setTotal(userService.count(user, ph));
return grid;
}
@RequestMapping("/editPwdPage")
public String editPwdPage(HttpServletRequest request) {
return "/eumode/sys/userEditPwd";
}
@RequestMapping("/editUserPwd")
@ResponseBody
public Json editUserPwd(HttpServletRequest request,String oldPwd, String pwd) {
SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute(GlobalConstant.SESSION_INFO_ADMIN);
Json j = new Json();
try {
if(userService.editUserPwd(sessionInfo, oldPwd, pwd)){
j.setSuccess(true);
j.setMsg("密码修改成功!");
}else{
j.setSuccess(false);
j.setMsg("原密码输入错误!");
}
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/addPage")
public String addPage(HttpServletRequest request) {
request.setAttribute("sexList", GlobalConstant.sexlist);
request.setAttribute("needPublishList", GlobalConstant.needPublishList);
return "/eumode/sys/userAdd";
}
@RequestMapping("/add")
@ResponseBody
public Json add(User user) {
Json j = new Json();
User u = userService.getByLoginName(user);
if(u!=null){
j.setMsg("用户名已存在!");
}else{
try {
Long personalid = userService.add(user);
if(personalid != null && personalid > 0){
if(user.getImagePath() != null && user.getImagePath().length() > 0){
String[] arrayList = user.getImagePath().split("\\^");
String imageName = arrayList[0];
String imagePath = arrayList[1];
EFResourceMeta rm = new EFResourceMeta();
rm.setType(dictionaryService.getDictionary("ResourceMetaType", "Expert").getId());
rm.setMetaID(personalid);
rm.setMetaPath(imagePath);
rm.setMetaDescription(imageName);
resourceMetaService.add(rm);
}
}
j.setSuccess(true);
j.setMsg("添加成功!");
} catch (Exception e) {
j.setMsg(e.getMessage());
}
}
return j;
}
@RequestMapping("/get")
@ResponseBody
public User get(Long id) {
return userService.get(id);
}
@RequestMapping("/delete")
@ResponseBody
public Json delete(Long id) {
Json j = new Json();
try {
userService.delete(id);
j.setMsg("删除成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/editPage")
public String editPage(HttpServletRequest request, Long id) {
User u = userService.get(id);
request.setAttribute("user", u);
request.setAttribute("sexList", GlobalConstant.sexlist);
request.setAttribute("needPublishList", GlobalConstant.needPublishList);
List rmList = resourceMetaService.get(u.getAutoID(), dictionaryService.getDictionary("ResourceMetaType", "Expert").getId());
if(rmList != null && rmList.size() > 0){
u.setImagePath(rmList.get(0).getMetaPath());
}
return "/eumode/sys/userEdit";
}
@RequestMapping("/edit")
@ResponseBody
public Json edit(User user) {
Json j = new Json();
try {
userService.edit(user);
if(user.getImagePath() != null && user.getImagePath().length() > 0){
String[] arrayList = user.getImagePath().split("\\^");
String imageName = arrayList[0];
String imagePath = arrayList[1];
List rmList = resourceMetaService.get(user.getAutoID(), dictionaryService.getDictionary("ResourceMetaType", "Expert").getId());
if(rmList != null && rmList.size() > 0){
//更换图片
EFResourceMeta rm = rmList.get(0);
rm.setMetaPath(imagePath);
rm.setMetaDescription(imageName);
resourceMetaService.edit(rm);
}
else{
//新增图片
EFResourceMeta rm = new EFResourceMeta();
rm.setType(dictionaryService.getDictionary("ResourceMetaType", "Expert").getId());
rm.setMetaID(user.getAutoID());
rm.setMetaPath(imagePath);
rm.setMetaDescription(imageName);
resourceMetaService.add(rm);
}
}
j.setSuccess(true);
j.setMsg("编辑成功!");
} catch (ServiceException e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/getExpertByManual")
@ResponseBody
public Json getExpertByManual(User user)
{
Json j= new Json();
try{
userService.setManual(user);
j.setMsg("授权成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
@RequestMapping("/manualPage")
public String manualPage(HttpServletRequest request, Long id)
{
User u = userService.get(id);
request.setAttribute("user", u);
return "/eumode/sys/userManual";
}
@RequestMapping("/setManual")
@ResponseBody
public Json setManual(User user)
{
Json j= new Json();
try{
userService.setManual(user);
j.setMsg("授权成功!");
j.setSuccess(true);
} catch (Exception e) {
j.setMsg(e.getMessage());
}
return j;
}
//允许上传的文件后缀
private static String fileExt = "jpg,jpeg,bmp,gif,png";
//上传文件的大小限制,5M
private static Long maxSize = 5242880L;
// 0:不建目录 1:按天存入目录 2:按月存入目录 3:按扩展名存目录 建议使用按天存
private static String dirType = "0";
//上传文件存储目录
private static String userImageDir = "/uploadfile/user_image/";
/*
* 上传文件操作
* @param request, response
* @return
* */
@RequestMapping("/getUploadFile")
@ResponseBody
public void getUploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/html; charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
String err = "";
String newFileName = "";
if ("application/octet-stream".equals(request.getContentType())) { //HTML 5 上传
try {
String dispoString = request.getHeader("Content-Disposition");
int iFindStart = dispoString.indexOf("name=\"")+6;
int iFindEnd = dispoString.indexOf("\"", iFindStart);
iFindStart = dispoString.indexOf("filename=\"")+10;
iFindEnd = dispoString.indexOf("\"", iFindStart);
String sFileName = dispoString.substring(iFindStart, iFindEnd);
int i = request.getContentLength();
byte buffer[] = new byte[i];
int j = 0;
while(j < i) { //获取表单的上传文件
int k = request.getInputStream().read(buffer, j, i-j);
j += k;
}
if (buffer.length == 0) { //文件是否为空
printInfo(response, "上传文件不能为空", "");
return;
}
if (maxSize > 0 && buffer.length > maxSize) { //检查文件大小
printInfo(response, "上传文件的大小超出限制", "");
return;
}
String filepathString = getSaveFilePath(sFileName, request, response);
if ("不允许上传此类型的文件".equals(filepathString)) return; //检查文件类型
//System.out.println("newFileName:" + request.getSession().getServletContext().getRealPath("") + filepathString);
OutputStream out=new BufferedOutputStream(new FileOutputStream(request.getSession().getServletContext().getRealPath("") + filepathString,true));
out.write(buffer);
out.close();
newFileName = request.getContextPath() + filepathString;
} catch (Exception ex) {
System.out.println(ex.getMessage());
newFileName = "";
err = "错误: " + ex.getMessage();
}
}
else{
Boolean mulipart = ServletFileUpload.isMultipartContent(request);
if(!mulipart)
{
printInfo(response, "上传格式错误", "");
return;
}
//以下部分供上传附件使用
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List fileList = multipartRequest.getFiles("Filedata");
try {
for (MultipartFile mf : fileList) {
if(mf.isEmpty()){
continue;
}
CommonsMultipartFile cf= (CommonsMultipartFile)mf;
DiskFileItem fi = (DiskFileItem)cf.getFileItem();
String fileNameLong = fi.getName(); //获取文件上传路径名称
fileNameLong = fileNameLong.replaceAll("^", "");
if (mf.getSize() == 0) { //文件是否为空
printInfo(response, "上传文件不能为空", "");
return;
}
if (maxSize > 0 && mf.getSize() > maxSize) { //检查文件大小
printInfo(response, "上传文件的大小超出限制", "");
return;
}
String filepathString = getSaveFilePath(fileNameLong, request, response);
if ("不允许上传此类型的文件".equals(filepathString)) return; //检查文件类型
OutputStream out=new BufferedOutputStream(new FileOutputStream(request.getSession().getServletContext().getRealPath("") + filepathString,true));
out.write(mf.getBytes());
out.close();
newFileName += fileNameLong + "^" + request.getContextPath() + filepathString + ";";
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
newFileName = "";
err = "错误: " + ex.getMessage();
}
}
printInfo(response, err, newFileName);
}
private String getSaveFilePath(String sFileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
/*获取文件扩展名*/
/*索引加1的效果是只取xxx.jpg的jpg*/
String extensionName = sFileName.substring(sFileName.lastIndexOf(".") + 1);
extensionName = extensionName.toLowerCase();
//System.out.println("extensionName:" + extensionName);
/*检查文件类型*/
if (("," + fileExt.toLowerCase() + ",").indexOf("," + extensionName + ",") < 0){
printInfo(response, "不允许上传此类型的文件", "");
return "不允许上传此类型的文件";
}
//0:不建目录, 1:按天存入目录, 2:按月存入目录, 3:按扩展名存目录.建议使用按天存.
String fileFolder = "";
if (dirType.equalsIgnoreCase("1"))
fileFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
if (dirType.equalsIgnoreCase("2"))
fileFolder = new SimpleDateFormat("yyyyMM").format(new Date());
if (dirType.equalsIgnoreCase("3"))
fileFolder = extensionName;
/*文件存储的相对路径*/
String saveDirPath = userImageDir + fileFolder + "/";
//System.out.println("saveDirPath:" + saveDirPath);
/*文件存储在容器中的绝对路径*/
String saveFilePath = request.getSession().getServletContext().getRealPath("") + saveDirPath;
//System.out.println("saveFilePath:" + saveFilePath);
/*构建文件目录以及目录文件*/
File fileDir = new File(saveFilePath);
if (!fileDir.exists()) {fileDir.mkdirs();}
/*重命名文件*/
String filename = UUID.randomUUID().toString();
return saveDirPath + filename + "." + extensionName;
}
/**
* 使用I/O流输出 json格式的数据
* @param response
* @param err
* @param newFileName
* @throws IOException
*/
private void printInfo(HttpServletResponse response, String err, String newFileName) throws IOException {
PrintWriter out = response.getWriter();
//String filename = newFileName.substring(newFileName.lastIndexOf("/") + 1);
out.println("{\"err\":\"" + err + "\",\"msg\":\"" + newFileName + "\"}");
out.flush();
out.close();
}
}
================================================
FILE: src/main/java/light/mvc/dao/BaseDaoI.java
================================================
package light.mvc.dao;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
public interface BaseDaoI {
public Serializable save(T o);
public void delete(T o);
public void update(T o);
public void saveOrUpdate(T o);
public T get(Class c, Serializable id);
public T get(String hql);
public T get(String hql, Map params);
public List find(String hql);
public List find(String hql, Map params);
public List find(String hql, int page, int rows);
public List find(String hql, Map params, int page, int rows);
public Long count(String hql);
public Long count(String hql, Map params);
public int executeHql(String hql);
public int executeHql(String hql, Map params);
public List