Skip to content

Commit 40d2cef

Browse files
Updated the file in response to the PR comment
1 parent 7c682b8 commit 40d2cef

File tree

1 file changed

+52
-50
lines changed

1 file changed

+52
-50
lines changed

core/src/main/java/com/tqdev/CrudApiHandler.java

Lines changed: 52 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -23,24 +23,20 @@
2323
import com.zaxxer.hikari.HikariConfig;
2424
import com.zaxxer.hikari.HikariDataSource;
2525
import java.util.Properties;
26-
// Add import statement
27-
import java.util.*;
2826

29-
public class CrudApiHandler extends AbstractHandler
30-
{
27+
public class CrudApiHandler extends AbstractHandler {
3128
protected HikariDataSource dataSource;
32-
33-
public static void main(String[] args) throws Exception
34-
{
29+
30+
public static void main(String[] args) throws Exception {
3531
// jetty config
3632
Properties properties = new Properties();
3733
properties.load(CrudApiHandler.class.getClassLoader().getResourceAsStream("jetty.properties"));
3834
HttpConfiguration config = new HttpConfiguration();
39-
config.setSendServerVersion( false );
40-
HttpConnectionFactory factory = new HttpConnectionFactory( config );
35+
config.setSendServerVersion(false);
36+
HttpConnectionFactory factory = new HttpConnectionFactory(config);
4137
Server server = new Server();
42-
ServerConnector connector = new ServerConnector(server,factory);
43-
server.setConnectors( new Connector[] { connector } );
38+
ServerConnector connector = new ServerConnector(server, factory);
39+
server.setConnectors(new Connector[] {connector});
4440
connector.setHost(properties.getProperty("host"));
4541
connector.setPort(Integer.parseInt(properties.getProperty("port")));
4642
server.addConnector(connector);
@@ -49,13 +45,11 @@ public static void main(String[] args) throws Exception
4945
server.join();
5046
}
5147

52-
public CrudApiHandler() throws IOException
53-
{
48+
public CrudApiHandler() throws IOException {
5449
this.dataSource = this.getDataSource();
5550
}
5651

57-
protected HikariDataSource getDataSource()
58-
{
52+
protected HikariDataSource getDataSource() {
5953
HikariDataSource dataSource;
6054
try {
6155
Properties properties = new Properties();
@@ -68,8 +62,7 @@ protected HikariDataSource getDataSource()
6862
return dataSource;
6963
}
7064

71-
protected Connection getConnection()
72-
{
65+
protected Connection getConnection() {
7366
Connection link;
7467
try {
7568
link = this.dataSource.getConnection();
@@ -80,46 +73,45 @@ protected Connection getConnection()
8073
return link;
8174
}
8275

83-
public void handle(String target,Request baseReq,HttpServletRequest req,HttpServletResponse resp)
84-
throws IOException, ServletException
85-
{
76+
public void handle(String target, Request baseReq, HttpServletRequest req, HttpServletResponse resp)
77+
throws IOException, ServletException {
8678
Gson gson = new Gson();
8779
// get the HTTP method, path and body of the request
8880
String method = req.getMethod();
89-
String[] request = req.getPathInfo().replaceAll("/$|^/","").split("/");
81+
String[] request = req.getPathInfo().replaceAll("/$|^/", "").split("/");
9082
@SuppressWarnings("unchecked")
9183
Map<String, Object> input = gson.fromJson(req.getReader(), Map.class);
9284
// connect to the mysql database
9385
Connection link = this.getConnection();
9486
// retrieve the table and key from the path
95-
String table = request[0].replaceAll("[^a-zA-Z0-9_]+","");
96-
int key = (request.length>1?Integer.parseInt(request[1]):-1);
87+
String table = request[0].replaceAll("[^a-zA-Z0-9_]+", "");
88+
int key = (request.length > 1 ? Integer.parseInt(request[1]) : -1);
9789
// escape the columns and values from the input object
98-
String[] columns = input==null?(new String[0]):(String[])input.keySet().toArray();
99-
for (int i=0;i<columns.length;i++) {
100-
columns[i] = columns[i].replaceAll("[^a-zA-Z0-9_]+","");
90+
String[] columns = input == null ? (new String[0]) : (String[]) input.keySet().toArray();
91+
for (int i = 0; i < columns.length; i++) {
92+
columns[i] = columns[i].replaceAll("[^a-zA-Z0-9_]+", "");
10193
}
10294
// build the SET part of the SQL command
10395
String set = "";
104-
for (int i=0;i<columns.length;i++) {
105-
set+=(i>0?",":"")+"`"+columns[i]+"`=?";
96+
for (int i = 0; i < columns.length; i++) {
97+
set += (i > 0 ? "," : "") + "`" + columns[i] + "`=?";
10698
}
10799
// create SQL based on HTTP method
108-
String sql="";
100+
String sql = "";
109101
if (method.equals("GET")) {
110-
sql = "select * from `"+table+"`"+(key>0?" WHERE id="+key:"");
102+
sql = "select * from `" + table + "`" + (key > 0 ? " WHERE id=" + key : "");
111103
} else if (method.equals("PUT")) {
112-
sql = "update `"+table+"` set "+set+" where id="+key;
104+
sql = "update `" + table + "` set " + set + " where id=" + key;
113105
} else if (method.equals("POST")) {
114-
sql = "insert into `"+table+"` set "+set;
106+
sql = "insert into `" + table + "` set " + set;
115107
} else if (method.equals("DELETE")) {
116-
sql = "delete `"+table+"` where id="+key;
108+
sql = "delete from `" + table + "` where id=" + key;
117109
}
118-
PreparedStatement statement=null;
110+
PreparedStatement statement = null;
119111
try {
120112
// execute SQL statement
121113
statement = link.prepareStatement(sql);
122-
for (int i=0;i<columns.length;i++) {
114+
for (int i = 0; i < columns.length; i++) {
123115
statement.setObject(i, input.get(columns[i]));
124116
}
125117
// print results, insert id or affected row count
@@ -130,37 +122,47 @@ public void handle(String target,Request baseReq,HttpServletRequest req,HttpServ
130122
ResultSet result = statement.executeQuery();
131123
ResultSetMetaData meta = result.getMetaData();
132124
int colCount = meta.getColumnCount();
133-
if (key<0) w.print('[');
134-
int row=0;
125+
if (key < 0)
126+
w.print('[');
127+
int row = 0;
135128
while (result.next()) {
136-
if (row>0) w.print(',');
129+
if (row > 0)
130+
w.print(',');
137131
w.print('{');
138-
for (int col=1;col<=colCount;col++) {
139-
if (col>1) w.print(',');
132+
for (int col = 1; col <= colCount; col++) {
133+
if (col > 1)
134+
w.print(',');
140135
w.print(gson.toJson(meta.getColumnName(col)));
141136
w.print(':');
142137
w.print(gson.toJson(result.getObject(col)));
143138
}
144139
w.print('}');
145140
row++;
146141
}
147-
if (key<0) w.print(']');
142+
if (key < 0)
143+
w.print(']');
148144
} else if (method.equals("POST")) {
149-
statement.executeUpdate(sql);
145+
statement.executeUpdate();
150146
ResultSet result = statement.getGeneratedKeys();
151147
result.next();
152148
w.print(gson.toJson(result.getObject(1)));
153149
} else {
154-
w.print(gson.toJson(statement.executeUpdate(sql)));
150+
w.print(gson.toJson(statement.executeUpdate()));
155151
}
156-
}
157-
catch (SQLException e) {
158-
System.out.println("SQLException:"+e);
159-
}
160-
finally {
152+
} catch (SQLException e) {
153+
System.out.println("SQLException:" + e);
154+
} finally {
161155
// close mysql connection
162-
if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
163-
if (link != null) try { link.close(); } catch (SQLException ignore) {}
156+
if (statement != null)
157+
try {
158+
statement.close();
159+
} catch (SQLException ignore) {
160+
}
161+
if (link != null)
162+
try {
163+
link.close();
164+
} catch (SQLException ignore) {
165+
}
164166
}
165167
baseReq.setHandled(true);
166168
}

0 commit comments

Comments
 (0)