23
23
import com .zaxxer .hikari .HikariConfig ;
24
24
import com .zaxxer .hikari .HikariDataSource ;
25
25
import java .util .Properties ;
26
- // Add import statement
27
- import java .util .*;
28
26
29
- public class CrudApiHandler extends AbstractHandler
30
- {
27
+ public class CrudApiHandler extends AbstractHandler {
31
28
protected HikariDataSource dataSource ;
32
-
33
- public static void main (String [] args ) throws Exception
34
- {
29
+
30
+ public static void main (String [] args ) throws Exception {
35
31
// jetty config
36
32
Properties properties = new Properties ();
37
33
properties .load (CrudApiHandler .class .getClassLoader ().getResourceAsStream ("jetty.properties" ));
38
34
HttpConfiguration config = new HttpConfiguration ();
39
- config .setSendServerVersion ( false );
40
- HttpConnectionFactory factory = new HttpConnectionFactory ( config );
35
+ config .setSendServerVersion (false );
36
+ HttpConnectionFactory factory = new HttpConnectionFactory (config );
41
37
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 } );
44
40
connector .setHost (properties .getProperty ("host" ));
45
41
connector .setPort (Integer .parseInt (properties .getProperty ("port" )));
46
42
server .addConnector (connector );
@@ -49,13 +45,11 @@ public static void main(String[] args) throws Exception
49
45
server .join ();
50
46
}
51
47
52
- public CrudApiHandler () throws IOException
53
- {
48
+ public CrudApiHandler () throws IOException {
54
49
this .dataSource = this .getDataSource ();
55
50
}
56
51
57
- protected HikariDataSource getDataSource ()
58
- {
52
+ protected HikariDataSource getDataSource () {
59
53
HikariDataSource dataSource ;
60
54
try {
61
55
Properties properties = new Properties ();
@@ -68,8 +62,7 @@ protected HikariDataSource getDataSource()
68
62
return dataSource ;
69
63
}
70
64
71
- protected Connection getConnection ()
72
- {
65
+ protected Connection getConnection () {
73
66
Connection link ;
74
67
try {
75
68
link = this .dataSource .getConnection ();
@@ -80,46 +73,45 @@ protected Connection getConnection()
80
73
return link ;
81
74
}
82
75
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 {
86
78
Gson gson = new Gson ();
87
79
// get the HTTP method, path and body of the request
88
80
String method = req .getMethod ();
89
- String [] request = req .getPathInfo ().replaceAll ("/$|^/" ,"" ).split ("/" );
81
+ String [] request = req .getPathInfo ().replaceAll ("/$|^/" , "" ).split ("/" );
90
82
@ SuppressWarnings ("unchecked" )
91
83
Map <String , Object > input = gson .fromJson (req .getReader (), Map .class );
92
84
// connect to the mysql database
93
85
Connection link = this .getConnection ();
94
86
// 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 );
97
89
// 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_]+" , "" );
101
93
}
102
94
// build the SET part of the SQL command
103
95
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 ] + "`=?" ;
106
98
}
107
99
// create SQL based on HTTP method
108
- String sql = "" ;
100
+ String sql = "" ;
109
101
if (method .equals ("GET" )) {
110
- sql = "select * from `" + table + "`" + (key > 0 ? " WHERE id=" + key : "" );
102
+ sql = "select * from `" + table + "`" + (key > 0 ? " WHERE id=" + key : "" );
111
103
} else if (method .equals ("PUT" )) {
112
- sql = "update `" + table + "` set " + set + " where id=" + key ;
104
+ sql = "update `" + table + "` set " + set + " where id=" + key ;
113
105
} else if (method .equals ("POST" )) {
114
- sql = "insert into `" + table + "` set " + set ;
106
+ sql = "insert into `" + table + "` set " + set ;
115
107
} else if (method .equals ("DELETE" )) {
116
- sql = "delete `" + table + "` where id=" + key ;
108
+ sql = "delete from `" + table + "` where id=" + key ;
117
109
}
118
- PreparedStatement statement = null ;
110
+ PreparedStatement statement = null ;
119
111
try {
120
112
// execute SQL statement
121
113
statement = link .prepareStatement (sql );
122
- for (int i = 0 ; i < columns .length ;i ++) {
114
+ for (int i = 0 ; i < columns .length ; i ++) {
123
115
statement .setObject (i , input .get (columns [i ]));
124
116
}
125
117
// print results, insert id or affected row count
@@ -130,37 +122,47 @@ public void handle(String target,Request baseReq,HttpServletRequest req,HttpServ
130
122
ResultSet result = statement .executeQuery ();
131
123
ResultSetMetaData meta = result .getMetaData ();
132
124
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 ;
135
128
while (result .next ()) {
136
- if (row >0 ) w .print (',' );
129
+ if (row > 0 )
130
+ w .print (',' );
137
131
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 (',' );
140
135
w .print (gson .toJson (meta .getColumnName (col )));
141
136
w .print (':' );
142
137
w .print (gson .toJson (result .getObject (col )));
143
138
}
144
139
w .print ('}' );
145
140
row ++;
146
141
}
147
- if (key <0 ) w .print (']' );
142
+ if (key < 0 )
143
+ w .print (']' );
148
144
} else if (method .equals ("POST" )) {
149
- statement .executeUpdate (sql );
145
+ statement .executeUpdate ();
150
146
ResultSet result = statement .getGeneratedKeys ();
151
147
result .next ();
152
148
w .print (gson .toJson (result .getObject (1 )));
153
149
} else {
154
- w .print (gson .toJson (statement .executeUpdate (sql )));
150
+ w .print (gson .toJson (statement .executeUpdate ()));
155
151
}
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 {
161
155
// 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
+ }
164
166
}
165
167
baseReq .setHandled (true );
166
168
}
0 commit comments