Use Hibernate framework to operate pojo instance, bye bye SQL strings :)

This commit is contained in:
Sola
2015-12-05 01:34:13 +08:00
parent 8d9b8da42f
commit 60b4d9e23e
23 changed files with 494 additions and 334 deletions

View File

@@ -1,8 +1,8 @@
<!DOCTYPE html><html><head><title>Authorize</title><meta charset='utf-8'><link href='https://dn-maxiang.qbox.me/res-min/themes/marxico.css' rel='stylesheet'></head><body><div id='preview-contents' class='note-content'>
<div id="wmd-preview" class="preview-content"></div>
<div id="wmd-preview-section-1791" class="wmd-preview-section preview-content">
<div id="wmd-preview-section-1" class="wmd-preview-section preview-content">
</div><div id="wmd-preview-section-1806" class="wmd-preview-section preview-content">
</div><div id="wmd-preview-section-2" class="wmd-preview-section preview-content">
<h1 id="authorize">Authorize</h1>
@@ -12,35 +12,51 @@
<li><a href="#url">URL</a></li>
<li><a href="#method">Method</a></li>
<li><a href="#parameters">Parameters</a></li>
<li><a href="#response">Response</a><ul>
<li><a href="#format">Format</a></li>
<li><a href="#response-code">Response Code</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#signature">Signature</a></li>
</ul>
</div>
</div>
</div></div><div id="wmd-preview-section-1793" class="wmd-preview-section preview-content">
</div>
</div><div id="wmd-preview-section-329" class="wmd-preview-section preview-content">
<h2 id="url">URL</h2>
<p><a href="http://sola.love/ww/api/authorize" target="_blank">http://sola.love/ww/api/authorize</a></p>
<hr>
</div><div id="wmd-preview-section-1794" class="wmd-preview-section preview-content">
<p><a href="http://sola.love/ww/api/authorize" target="_blank">http://sola.love/ww/api/authorize</a></p></div><div id="wmd-preview-section-312" class="wmd-preview-section preview-content">
<h2 id="method">Method</h2>
<p>POST</p>
<hr>
</div><div id="wmd-preview-section-1795" class="wmd-preview-section preview-content">
<p>POST</p></div><div id="wmd-preview-section-304" class="wmd-preview-section preview-content">
<h2 id="parameters">Parameters</h2>
<hr>
<ul><li><code>wechat</code> Wechat ID</li>
</ul>
</ul></div><div id="wmd-preview-section-278" class="wmd-preview-section preview-content">
</div><div id="wmd-preview-section-1838" class="wmd-preview-section preview-content">
<h2 id="response">Response</h2>
<h2 id="response-code">Response Code</h2>
<hr></div><div id="wmd-preview-section-225" class="wmd-preview-section preview-content">
<h3 id="format">Format</h3>
<p>JSON</p>
</div><div id="wmd-preview-section-271" class="wmd-preview-section preview-content">
<h3 id="response-code">Response Code</h3>
<ul><li>Success <br>
<ul>
@@ -48,11 +64,12 @@
<li>Error <br>
<ul>
<li><code>-1</code> PARAMETER_REQUIRED</li>
<li><code>-9</code> AUTHORIZE_FAILED</li></ul></li>
<li><code>-9</code> AUTHORIZE_FAILED</li>
<li><code>-21</code> REQUEST_EXPIRED</li></ul></li>
</ul>
<hr></div><div id="wmd-preview-section-1797" class="wmd-preview-section preview-content">
<hr></div><div id="wmd-preview-section-371" class="wmd-preview-section preview-content">
<h1 id="signature">Signature</h1>
<p>Created by Sola on 2/15/2015</p></div><div id="wmd-preview-section-footnotes" class="preview-content"></div></div></body></html>
<p>Created by Sola on 12/3/2015</p></div><div id="wmd-preview-section-footnotes" class="preview-content"></div></div></body></html>

View File

@@ -1,24 +1,36 @@
<!DOCTYPE html><html><head><title>绑定微信请求</title><meta charset='utf-8'><link href='https://dn-maxiang.qbox.me/res-min/themes/marxico.css' rel='stylesheet'></head><body><div id='preview-contents' class='note-content'>
<!DOCTYPE html><html><head><title>绑定微信请求 V1.3</title><meta charset='utf-8'><link href='https://dn-maxiang.qbox.me/res-min/themes/marxico.css' rel='stylesheet'></head><body><div id='preview-contents' class='note-content'>
<div id="wmd-preview" class="preview-content"></div>
<div id="wmd-preview-section-5" class="wmd-preview-section preview-content">
<div id="wmd-preview-section-1" class="wmd-preview-section preview-content">
</div><div id="wmd-preview-section-27" class="wmd-preview-section preview-content">
</div><div id="wmd-preview-section-36" class="wmd-preview-section preview-content">
<h1 id="绑定微信请求">绑定微信请求</h1>
<h1 id="绑定微信请求-v13">绑定微信请求 V1.3</h1>
</div><div id="wmd-preview-section-58" class="wmd-preview-section preview-content">
<blockquote>
<p>Edition : (1.3)2015/12/04 </p>
</blockquote>
<h2 id="url">URL</h2>
</div><div id="wmd-preview-section-37" class="wmd-preview-section preview-content">
<p><a href="http://sola.love" target="_blank">http://sola.love</a></p></div><div id="wmd-preview-section-94" class="wmd-preview-section preview-content">
<h2 id="绑定">绑定</h2>
<h2 id="method">Method</h2>
<hr>
</div><div id="wmd-preview-section-38" class="wmd-preview-section preview-content">
<h3 id="url">URL</h3>
<p><a href="http://sola.love" target="_blank">http://sola.love</a></p>
</div><div id="wmd-preview-section-39" class="wmd-preview-section preview-content">
<h3 id="method">Method</h3>
<p>POST</p>
</div><div id="wmd-preview-section-633" class="wmd-preview-section preview-content">
</div><div id="wmd-preview-section-40" class="wmd-preview-section preview-content">
<h2 id="params">Params</h2>
<h3 id="params">Params</h3>
<ul><li><code>wechatid</code> <strong>string</strong> 用户微信ID</li>
<li><code>name</code> <strong>string</strong> 姓名</li>
@@ -28,11 +40,25 @@
<li><code>block</code> <strong>integer</strong> 片区代码</li>
<li><code>room</code> <strong>integer</strong> 宿舍房号 </li>
<li><code>phone</code> <strong>string</strong> 手机号码</li>
</ul></div><div id="wmd-preview-section-657" class="wmd-preview-section preview-content">
</ul>
<h2 id="more">More</h2></div><div id="wmd-preview-section-2016" class="wmd-preview-section preview-content">
</div><div id="wmd-preview-section-41" class="wmd-preview-section preview-content">
<h3 id="片区代码">片区代码</h3>
<h3 id="more">More</h3>
</div><div id="wmd-preview-section-42" class="wmd-preview-section preview-content">
<h4 id="isp代码">ISP代码</h4>
<ul><li>电信 <code>1</code></li>
<li>联通 <code>2</code></li>
<li>移动 <code>3</code></li>
<li>其他 <code>4</code></li>
</ul>
</div><div id="wmd-preview-section-43" class="wmd-preview-section preview-content">
<h4 id="片区代码">片区代码</h4>
<ul><li>岐头生活区 <br>
<ul>
@@ -71,12 +97,55 @@
<ul>
<li>20栋 <code>60</code></li>
<li>21栋 <code>61</code></li></ul></li>
</ul></div><div id="wmd-preview-section-2112" class="wmd-preview-section preview-content">
</ul>
</div><div id="wmd-preview-section-44" class="wmd-preview-section preview-content">
<h2 id="绑定结果页">绑定结果页</h2>
<hr>
</div><div id="wmd-preview-section-45" class="wmd-preview-section preview-content">
<h3 id="url-1">URL</h3>
<p><a href="http://topaz.sinaapp.com/nm/result.html" target="_blank">http://topaz.sinaapp.com/nm/result.html</a></p>
</div><div id="wmd-preview-section-46" class="wmd-preview-section preview-content">
<h3 id="method-1">Method</h3>
<p>GET</p>
</div><div id="wmd-preview-section-47" class="wmd-preview-section preview-content">
<h3 id="params-1">Params</h3>
<ul><li><code>type</code> <strong>integer</strong> 绑定结果类型</li>
<li><code>msg</code> <strong>string</strong> 绑定结果说明</li>
</ul>
</div><div id="wmd-preview-section-48" class="wmd-preview-section preview-content">
<h3 id="more-1">More</h3>
</div><div id="wmd-preview-section-49" class="wmd-preview-section preview-content">
<h4 id="结果类型">结果类型</h4>
<ul><li>失败 <code>0</code></li>
<li>成功 <code>1</code></li>
<li><del>警告 <code>-1</code></del>(<em>不推荐使用</em>)</li>
</ul>
</div><div id="wmd-preview-section-50" class="wmd-preview-section preview-content">
<h2 id="author">Author</h2>
<p>LiuYue(hangxingliu)</p></div><div id="wmd-preview-section-2175" class="wmd-preview-section preview-content">
<p>LiuYue(hangxingliu)</p>
</div><div id="wmd-preview-section-51" class="wmd-preview-section preview-content">
<h2 id="date">Date</h2>
<p>2015/11/28</p></div><div id="wmd-preview-section-footnotes" class="preview-content"></div></div></body></html>
<p>2015/12/04</p></div><div id="wmd-preview-section-footnotes" class="preview-content"></div></div></body></html>

23
pom.xml
View File

@@ -28,6 +28,7 @@
</configuration>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
@@ -96,7 +97,25 @@
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
</dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.0.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency></dependencies>
</project>

View File

@@ -1,7 +1,5 @@
package love.sola.netsupport;
import love.sola.netsupport.config.Settings;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
@@ -16,10 +14,9 @@ import java.io.PrintWriter;
* Don't modify this source without my agreement
* ***********************************************
*/
@WebServlet(name = "Index",urlPatterns = "/",loadOnStartup = 1)
@WebServlet(name = "Index",urlPatterns = "/index",loadOnStartup = 1)
public class Index extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

View File

@@ -3,6 +3,7 @@ package love.sola.netsupport.api;
import com.google.gson.Gson;
import love.sola.netsupport.config.Settings;
import love.sola.netsupport.sql.SQLCore;
import love.sola.netsupport.util.JsonP;
import love.sola.netsupport.wechat.Command;
import javax.servlet.ServletException;
@@ -15,8 +16,6 @@ import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static love.sola.netsupport.config.Lang.lang;
/**
* ***********************************************
* Created by Sola on 2015/12/2.
@@ -32,16 +31,21 @@ public class Authorize extends HttpServlet {
public static Map<String, Command> fetchedCommand = new ConcurrentHashMap<>();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.addHeader("Content-type", "text/json;charset=utf-8");
PrintWriter out = response.getWriter();
String wechat = request.getParameter("wechat");
out.println(gson.toJson(authorize(wechat)));
String json = gson.toJson(authorize(request));
out.println(JsonP.parse(request, json));
out.close();
}
private Response authorize(String wechat) {
private Response authorize(HttpServletRequest request) {
String wechat = request.getParameter("wechat");
if (wechat == null) {
return new Response(Response.ResponseCode.PARAMETER_REQUIRED);
}
@@ -50,28 +54,20 @@ public class Authorize extends HttpServlet {
if (l == null || c == null) {
return new Response(Response.ResponseCode.AUTHORIZE_FAILED);
}
if (l < System.currentTimeMillis() - Settings.I.User_Command_Timeout) {
return new Response(Response.ResponseCode.AUTHORIZE_FAILED);
if (l < System.currentTimeMillis() - Settings.I.User_Command_Timeout * 1000) {
return new Response(Response.ResponseCode.REQUEST_EXPIRED);
}
switch (c) {
case REGISTER:
Register.authorized.put(wechat, System.currentTimeMillis());
break;
case QUERY:
request.getSession(true).setAttribute("wechat", wechat);
request.getSession(true).setAttribute("wechat", wechat);
default:
return new Response(Response.ResponseCode.AUTHORIZE_FAILED);
}
return new Response(Response.ResponseCode.OK);
}
@SuppressWarnings("Duplicates")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.addHeader("Content-type", "text/plain;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(lang("Illegal_Request"));
out.close();
}
}

View File

@@ -4,6 +4,7 @@ import com.google.gson.Gson;
import love.sola.netsupport.pojo.User;
import love.sola.netsupport.sql.SQLCore;
import love.sola.netsupport.sql.TableUser;
import love.sola.netsupport.util.JsonP;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
@@ -39,28 +40,34 @@ public class GetUser extends HttpServlet {
response.setCharacterEncoding("utf-8");
response.addHeader("Content-type", "text/json;charset=utf-8");
PrintWriter out = response.getWriter();
String json = gson.toJson(query(request));
out.println(JsonP.parse(request, json));
out.close();
}
private Response query(HttpServletRequest request) {
String id = request.getParameter("id");
String name = request.getParameter("name");
if ((id == null || id.isEmpty()) && (name == null || name.isEmpty())) {
out.println(gson.toJson(new Response(Response.ResponseCode.PARAMETER_REQUIRED)));
} else if (id != null) {
return new Response(Response.ResponseCode.PARAMETER_REQUIRED);
}
if (id != null) {
try {
User u = TableUser.getUserById(Long.parseLong(id));
if (u == null)
out.println(gson.toJson(new Response(Response.ResponseCode.USER_NOT_FOUND)));
return new Response(Response.ResponseCode.USER_NOT_FOUND);
else
out.println(gson.toJson(new Response(Response.ResponseCode.OK, u)));
return new Response(Response.ResponseCode.OK, u);
} catch (NumberFormatException e) {
out.println(gson.toJson(new Response(Response.ResponseCode.ILLEGAL_PARAMETER)));
return new Response(Response.ResponseCode.ILLEGAL_PARAMETER);
}
} else {
User u = TableUser.getUserByName(name);
if (u == null)
out.println(gson.toJson(new Response(Response.ResponseCode.USER_NOT_FOUND)));
return new Response(Response.ResponseCode.USER_NOT_FOUND);
else
out.println(gson.toJson(new Response(Response.ResponseCode.OK, u)));
return new Response(Response.ResponseCode.OK, u);
}
out.close();
}
}

View File

@@ -0,0 +1,44 @@
package love.sola.netsupport.api;
import love.sola.netsupport.sql.SQLCore;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* ***********************************************
* Created by Sola on 2015/12/4.
* Don't modify this source without my agreement
* ***********************************************
*/
@WebServlet(name = "QueryTicket", urlPatterns = "/api/queryticket", loadOnStartup = 23)
public class QueryTicket extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.addHeader("Content-type", "text/json;charset=utf-8");
PrintWriter out = response.getWriter();
}
private Response query(HttpServletRequest request) {
try (Session s = SQLCore.sf.openSession()) {
// TODO: 2015/12/5 TICKET QUERY
} catch (HibernateException e) {
}
return null;
}
}

View File

@@ -12,7 +12,6 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -32,27 +31,31 @@ public class Register extends HttpServlet {
public static final String STUDENT_ID_REGEX = "^(2010|2012|2013|2014|2015)[0-9]{9}$";
public static final String PHONE_NUMBER_REGEX = "^1[34578][0-9]{9}$";
public static final String REDIRECT_PAGE = "http://topaz.sinaapp.com/nm/result.html?";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.addHeader("Content-type", "text/plain;charset=utf-8");
PrintWriter out = response.getWriter();
ISP isp = checkISP(request.getParameter("isp"));
Block block = checkBlock(request.getParameter("block"));
out.println(
register(
checkStudentId(request.getParameter("sid")),
request.getParameter("name"),
isp,
checkNetAccount(request.getParameter("username"), isp),
block,
checkRoom(request.getParameter("room"), block),
checkPhoneNumber(request.getParameter("phone")),
checkWechat(request.getParameter("wechatid"))
String result = register(
checkStudentId(request.getParameter("sid")),
request.getParameter("name"),
isp,
checkNetAccount(request.getParameter("username"), isp),
block,
checkRoom(request.getParameter("room"), block),
checkPhoneNumber(request.getParameter("phone")),
checkWechat(request.getParameter("wechatid"))
);
response.sendRedirect(
response.encodeRedirectURL(REDIRECT_PAGE +
"msg=" + result + "" +
"&type=" + (result.equals("Register_Success") ? 1 : 0)
)
);
out.close();
}
@SuppressWarnings("Duplicates")
@@ -60,31 +63,35 @@ public class Register extends HttpServlet {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.addHeader("Content-type", "text/plain;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(lang("Illegal_Request"));
out.close();
response.sendRedirect(
response.encodeRedirectURL(REDIRECT_PAGE +
"msg=" + lang("Illegal_Request") +
"&type=-1"
)
);
}
private String register(long sid, String name, ISP isp, String netAccount, Block block, int room, long phone, String wechat) {
if (wechat == null) return lang("Illegal_Request");
if (sid == -1) return lang("Invalid_Student_Id");
if (name == null) return lang("Invalid_Name");
if (isp == null) return lang("Invalid_ISP");
if (netAccount == null) return lang("Invalid_Account");
if (block == null) return lang("Invalid_Block");
if (room == -1) return lang("Invalid_Room");
if (phone == -1) return lang("Invalid_Phone_Number");
if (wechat == null) return "Illegal_Request";
if (sid == -1) return "Invalid_Student_Id";
if (name == null) return "Invalid_Name";
if (isp == null) return "Invalid_ISP";
if (netAccount == null) return "Invalid_Account";
if (block == null) return "Invalid_Block";
if (room == -1) return "Invalid_Room";
if (phone == -1) return "Invalid_Phone_Number";
User user = TableUser.getUserById(sid);
if (user == null) return lang("Invalid_Student_Id");
if (!user.getName().equals(name)) return lang("Invalid_Name");
if (user.getWechatId() != null) return lang("User_Already_Registered");
if (user == null) return "Invalid_Student_Id";
if (!user.getName().equals(name)) return "Invalid_Name";
if (user.getWechatId() != null) return "User_Already_Registered";
user.setIsp(isp);
user.setNetAccount(netAccount);
user.setBlock(block);
user.setRoom(room);
user.setPhone(phone);
user.setWechatId(wechat);
return lang("Register_Success");
TableUser.updateUser(user);
return "Register_Success";
}
@@ -150,7 +157,7 @@ public class Register extends HttpServlet {
private String checkWechat(String wechat) {
if (wechat == null) return null;
Long l = authorized.remove(wechat);
return l == null ? null : l < System.currentTimeMillis() - Settings.I.User_Register_Timeout ? null : wechat;
return l == null ? null : l < System.currentTimeMillis() - Settings.I.User_Register_Timeout * 1000 ? null : wechat;
}
}

View File

@@ -38,6 +38,7 @@ public class Response {
ILLEGAL_PARAMETER(-2),
AUTHORIZE_FAILED(-9),
USER_NOT_FOUND(-11),
REQUEST_EXPIRED(-21),
;
private static final Map<Integer, ResponseCode> ID_MAP = new HashMap<>();

View File

@@ -0,0 +1,25 @@
package love.sola.netsupport.enums;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class BlockConverter implements AttributeConverter<Block, Integer> {
@Override
public Integer convertToDatabaseColumn(Block attribute) {
if (attribute == null) {
return null;
}
return attribute.id;
}
@Override
public Block convertToEntityAttribute(Integer dbData) {
if (dbData == null) {
return null;
}
return Block.fromId(dbData);
}
}

View File

@@ -0,0 +1,25 @@
package love.sola.netsupport.enums;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class ISPConverter implements AttributeConverter<ISP, Integer> {
@Override
public Integer convertToDatabaseColumn(ISP attribute) {
if (attribute == null) {
return null;
}
return attribute.id;
}
@Override
public ISP convertToEntityAttribute(Integer dbData) {
if (dbData == null) {
return null;
}
return ISP.fromId(dbData);
}
}

View File

@@ -0,0 +1,38 @@
package love.sola.netsupport.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.Date;
/**
* ***********************************************
* Created by Sola on 2015/12/2.
* Don't modify this source without my agreement
* ***********************************************
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "tickets")
public class Ticket {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne(optional = false)
@JoinColumn(name = "sid")
private User user;
private String description;
private Date submitTime;
private String remark;
private Date updateTime;
@ManyToOne(optional = true)
@JoinColumn(name = "opsid")
private User operator;
private int status;
}

View File

@@ -2,8 +2,13 @@ package love.sola.netsupport.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import love.sola.netsupport.enums.Block;
import love.sola.netsupport.enums.BlockConverter;
import love.sola.netsupport.enums.ISP;
import love.sola.netsupport.enums.ISPConverter;
import javax.persistence.*;
/**
* ***********************************************
@@ -13,15 +18,25 @@ import love.sola.netsupport.enums.ISP;
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "users")
public class User {
private final long id;
private final String name;
@Id
@Column(name = "id", updatable = false, nullable = false)
private long id;
@Column(name = "name", updatable = false, nullable = false)
private String name;
@Convert(converter = ISPConverter.class)
private ISP isp;
@Column(name = "netaccount")
private String netAccount;
@Column(name = "wechat")
private String wechatId;
@Convert(converter = BlockConverter.class)
private Block block;
private int room;
private long phone;
private Integer room;
private Long phone;
}

View File

@@ -1,6 +1,10 @@
package love.sola.netsupport.sql;
import com.google.gson.Gson;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import javax.naming.InitialContext;
import javax.sql.DataSource;
@@ -15,12 +19,17 @@ public class SQLCore {
public static DataSource ds;
public static Gson gson = new Gson();
public static SessionFactory sf;
public static ServiceRegistry sr;
static {
try {
InitialContext ic = new InitialContext();
ds = (DataSource) ic.lookup("java:comp/env/jdbc/netsupport");
ds.setLoginTimeout(3);
sr = new StandardServiceRegistryBuilder().configure().build();
sf = new MetadataSources(sr).buildMetadata().buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}

View File

@@ -1,19 +1,9 @@
package love.sola.netsupport.sql;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import love.sola.netsupport.config.Settings;
import love.sola.netsupport.enums.Block;
import love.sola.netsupport.enums.ISP;
import love.sola.netsupport.pojo.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
/**
* ***********************************************
@@ -33,160 +23,44 @@ public class TableUser extends SQLCore {
public static final String COLUMN_ROOM = "room";
public static final String COLUMN_PHONE = "phone";
public static User getUserById(long id) {
if (id < 0) return null;
try {
return cache_id.get(id);
} catch (ExecutionException e) {
return null;
try (Session s = sf.openSession()) {
return s.get(User.class, id);
} catch (HibernateException e) {
e.printStackTrace();
}
return null;
}
public static User getUserByWechat(String wechat) {
if (wechat == null) return null;
try {
return cache_wechat.get(wechat);
} catch (ExecutionException e) {
return null;
try (Session s = sf.openSession()) {
return (User) s.createCriteria(User.class).add(Restrictions.eq(COLUMN_WECHAT, wechat)).uniqueResult();
} catch (HibernateException e) {
e.printStackTrace();
}
return null;
}
public static User getUserByName(String name) {
if (name == null) return null;
User u = getUserByName0(name);
if (u != null) {
cache_id.put(u.getId(), u);
if (u.getWechatId()!=null) cache_wechat.put(u.getWechatId(), u);
try (Session s = sf.openSession()) {
return (User) s.createCriteria(User.class).add(Restrictions.eq(COLUMN_NAME, name)).uniqueResult();
} catch (HibernateException e) {
e.printStackTrace();
}
return u;
return null;
}
public static int updateUser(User user) {
int r = updateUser0(user);
if (r > 0) {
cache_id.put(user.getId(), user);
if (user.getWechatId() != null) cache_wechat.put(user.getWechatId(), user);
}
return r;
}
private static LoadingCache<Long, User> cache_id = CacheBuilder.newBuilder()
.concurrencyLevel(4)
.maximumSize(2048)
.expireAfterAccess(Settings.I.User_Caching_Time, TimeUnit.SECONDS)
.build(new IdLoader());
private static LoadingCache<String, User> cache_wechat = CacheBuilder.newBuilder()
.concurrencyLevel(4)
.maximumSize(2048)
.expireAfterAccess(Settings.I.User_Caching_Time, TimeUnit.SECONDS)
.build(new WechatLoader());
private static class IdLoader extends CacheLoader<Long, User> {
@Override
public User load(Long key) throws Exception {
User u = getUserById0(key);
System.out.println("Queried user: " + u);
if (u == null) throw new UserNotFoundException();
if (u.getWechatId() != null) cache_wechat.put(u.getWechatId(), u);
return u;
}
}
private static class WechatLoader extends CacheLoader<String, User> {
@Override
public User load(String key) throws Exception {
User u = getUserByWechat0(key);
System.out.println("Queried user: " + u);
if (u == null) throw new UserNotFoundException();
cache_id.put(u.getId(), u);
return u;
}
}
public static class UserNotFoundException extends Exception { }
private static User getUserById0(long id) {
try (Connection conn = ds.getConnection()) {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM user_info WHERE id=?");
ps.setLong(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return constructUser(rs);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private static User getUserByWechat0(String wechat) {
try (Connection conn = ds.getConnection()) {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM user_info WHERE wechat=?");
ps.setString(1, wechat);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return constructUser(rs);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private static User getUserByName0(String name) {
try (Connection conn = ds.getConnection()) {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM user_info WHERE name=?");
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return constructUser(rs);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
private static int updateUser0(User user) {
try (Connection conn = ds.getConnection()) {
PreparedStatement ps = conn.prepareStatement("UPDATE user_info SET " +
COLUMN_WECHAT + "=?," +
COLUMN_ISP + "=?," +
COLUMN_NET_ACCOUNT + "=?," +
COLUMN_BLOCK + "=?," +
COLUMN_ROOM + "=?," +
COLUMN_PHONE + "=? " +
"WHERE id=?");
ps.setString(1, user.getWechatId());
ps.setInt(2, user.getIsp().id);
ps.setString(3, user.getNetAccount());
ps.setInt(4, user.getBlock().id);
ps.setInt(5, user.getRoom());
ps.setLong(6, user.getPhone());
ps.setLong(7, user.getId());
return ps.executeUpdate();
} catch (SQLException e) {
try (Session s = sf.openSession()) {
s.beginTransaction();
s.update(user);
s.getTransaction().commit();
return 1;
} catch (HibernateException e) {
e.printStackTrace();
}
return -1;
}
private static User constructUser(ResultSet rs) throws SQLException {
return new User(
rs.getLong(COLUMN_ID),
rs.getString(COLUMN_NAME),
ISP.fromId(rs.getInt(COLUMN_ISP)),
rs.getString(COLUMN_NET_ACCOUNT),
rs.getString(COLUMN_WECHAT),
Block.fromId(rs.getInt(COLUMN_BLOCK)),
rs.getInt(COLUMN_ROOM),
rs.getInt(COLUMN_PHONE)
);
}
}

View File

@@ -0,0 +1,21 @@
package love.sola.netsupport.util;
import javax.servlet.http.HttpServletRequest;
/**
* ***********************************************
* Created by Sola on 2015/12/3.
* Don't modify this source without my agreement
* ***********************************************
*/
public class JsonP {
public static String parse(HttpServletRequest request, String json) {
String jsonp = request.getParameter("jsonp");
if (jsonp == null || jsonp.isEmpty())
return json;
else
return jsonp.replace("{0}", json);
}
}

View File

@@ -3,6 +3,8 @@ package love.sola.netsupport.wechat;
import java.util.HashMap;
import java.util.Map;
import static love.sola.netsupport.config.Lang.lang;
/**
* ***********************************************
* Created by Sola on 2015/11/26.
@@ -11,7 +13,8 @@ import java.util.Map;
*/
public enum Command {
REGISTER(0, "Register", ".*"),
REGISTER(0, ".*"),
QUERY(1, "Query"),
;
private static final Map<Integer, Command> ID_MAP = new HashMap<>();
@@ -28,8 +31,8 @@ public enum Command {
public final String regex;
public final int id;
Command(int id, String name, String regex) {
this.name = name;
Command(int id, String regex) {
this.name = lang("CMD_" + name());
this.id = id;
this.regex = regex;
}

View File

@@ -0,0 +1,45 @@
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<!--<property name="jndi.class">org.apache.naming.factory.BeanFactory</property>-->
<property name="connection.datasource">java:comp/env/jdbc/netsupport</property>
<!--<property name="connection.driver_class">com.mysql.jdbc.Driver</property>-->
<!--<property name="connection.url">jdbc:mysql://localhost:3306/***?autoReconnect=true&amp;characterEncoding=utf8</property>-->
<!--<property name="connection.username">***</property>-->
<!--<property name="connection.password">***</property>-->
<!-- JDBC connection pool (use the built-in) -->
<!--<property name="connection.pool_size">50</property>-->
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">validate</property>
<!-- Names the annotated entity class -->
<mapping class="love.sola.netsupport.pojo.User"/>
<mapping class="love.sola.netsupport.pojo.Ticket"/>
</session-factory>
</hibernate-configuration>

View File

@@ -12,69 +12,15 @@
If you have any problem, please contact loli@sola.love .
</description>
<!-- Servlet definitions for the servlets that make up
your web application, including initialization
parameters. With Tomcat, you can also send requests
to servlets not listed here with a request like this:
http://localhost:8080/{context-path}/servlet/{classname}
but this usage is not guaranteed to be portable. It also
makes relative references to images and other resources
required by your servlet more complicated, so defining
all of your servlets (and defining a mapping to them with
a servlet-mapping element) is recommended.
Servlet initialization parameters can be retrieved in a
servlet or JSP page by calling:
String value =
getServletConfig().getInitParameter("name");
where "name" matches the <param-name> element of
one of these initialization parameters.
You can define any number of servlets, including zero.
-->
<!--
<servlet>
<servlet-name>C3P0Test</servlet-name>
<servlet-class>love.sola.netsupport.C3P0Test</servlet-class>
</servlet>
-->
<!-- Define mappings that are used by the servlet container to
translate a particular request URI (context-relative) to a
particular servlet. The examples below correspond to the
servlet descriptions above. Thus, a request URI like:
http://localhost:8080/{contextpath}/graph
will be mapped to the "graph" servlet, while a request like:
http://localhost:8080/{contextpath}/saveCustomer.do
will be mapped to the "controller" servlet.
You may define any number of servlet mappings, including zero.
It is also legal to define more than one mapping for the same
servlet, if you wish to.
-->
<!--
<servlet-mapping>
<servlet-name>C3P0Test</servlet-name>
<url-pattern>/c3p0test</url-pattern>
</servlet-mapping>
-->
<!-- Define the default session timeout for your application,
in minutes. From a servlet or JSP page, you can modify
the timeout for a particular session dynamically by using
HttpSession.getMaxInactiveInterval(). -->
<welcome-file-list>
<welcome-file>index</welcome-file>
</welcome-file-list>
<error-page>
<location>/index</location>
</error-page>
<session-config>
<session-timeout>30</session-timeout> <!-- 30 minutes -->
<session-timeout>10</session-timeout> <!-- 30 minutes -->
</session-config>
</web-app>

BIN
src/main/webapp/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

View File

@@ -0,0 +1,20 @@
package love.sola.netsupport.wechat;
import org.junit.Test;
import java.util.Date;
/**
* ***********************************************
* Created by Sola on 2015/12/3.
* Don't modify this source without my agreement
* ***********************************************
*/
public class TestDate {
@Test
public void test() {
System.out.println(new Date());
}
}

View File

@@ -1,25 +0,0 @@
package love.sola.netsupport.wechat;
import com.google.gson.Gson;
import love.sola.netsupport.config.Settings;
/**
* ***********************************************
* Created by Sola on 2015/11/26.
* Don't modify this source without my agreement
* ***********************************************
*/
public class TestGson {
// @Test
public void testGson() {
Gson gson = new Gson();
Settings settings = new Settings();
settings.Wechat_AppId = "*";
settings.Wechat_Secret = "*";
settings.Wechat_Token = "*";
settings.Wechat_AesKey = "*";
System.out.println(gson.toJson(settings));
}
}

View File

@@ -18,4 +18,11 @@ public class TestMessageFormat {
System.out.println(format.format(new Object[]{"wechatid"}));
}
@Test
public void testJsonp() {
String jsonp = "...{0}...";
MessageFormat format = new MessageFormat(jsonp);
System.out.println(format.format(new Object[]{"{SomeData}"}));
}
}