18
18
import java .util .Map ;
19
19
import java .util .Map .Entry ;
20
20
import java .util .concurrent .ConcurrentHashMap ;
21
+ import java .util .function .Supplier ;
21
22
import java .util .zip .ZipEntry ;
22
23
import java .util .zip .ZipOutputStream ;
23
24
import lombok .CustomLog ;
25
+ import lombok .RequiredArgsConstructor ;
24
26
import net .cofcool .sourcebox .App ;
25
27
import net .cofcool .sourcebox .Tool ;
26
28
import net .cofcool .sourcebox .Tool .Args ;
38
40
* config listen port: {@link #PORT_KEY}
39
41
*/
40
42
@ CustomLog
41
- public class WebRunner extends AbstractVerticle implements ToolRunner , VertxDeployer {
43
+ public class WebRunner implements ToolRunner {
42
44
43
45
public static final String PORT_KEY = "web.port" ;
44
46
public static final String USER_KEY = "web.username" ;
45
47
public static final String PASSWD_KEY = "web.password" ;
46
48
public static final int PORT_VAL = 38080 ;
47
49
48
- private Credentials usernamePasswordCredentials ;
49
- private int port = PORT_VAL ;
50
-
51
50
@ Override
52
51
public boolean run (Args args ) throws Exception {
53
52
Vertx v = Vertx .vertx ();
54
- deploy (v , null , args ).onComplete (VertxUtils .logResult (log , e -> v .close ()));
53
+ new WebVerticle (RunnerType .WEB , WebToolContext ::new ).deploy (v , null , args )
54
+ .onComplete (VertxUtils .logResult (log , e -> v .close ()));
55
55
return true ;
56
56
}
57
57
@@ -60,94 +60,63 @@ public String help() {
60
60
return String .join (", " , USER_KEY , PASSWD_KEY , PORT_KEY );
61
61
}
62
62
63
- @ Override
64
- public Future <String > deploy (Vertx vertx , Verticle verticle , Args args ) {
65
- args .getArgVal (USER_KEY ).ifPresent (a -> {
66
- usernamePasswordCredentials = new UsernamePasswordCredentials (
67
- a ,
68
- args .readArg (PASSWD_KEY )
69
- .getRequiredVal ("If username is not null, password must also not be null" )
70
- ) {
71
- @ Override
72
- public <V > void checkValid (V arg ) throws CredentialValidationException {
73
- super .checkValid (arg );
74
- if (arg instanceof JsonObject credentials ) {
75
- if (!(getUsername ().equals (credentials .getString ("username" ))
76
- && getPassword ().equals (credentials .getString ("password" )))) {
77
- throw new CredentialValidationException ("Username or password error" );
78
- }
79
- }
80
- }
81
- };
82
- log .info ("Enable basicAuth" );
83
- });
84
- args .getArgVal (PORT_KEY ).ifPresent (a -> port = Integer .parseInt (a ));
85
- return VertxDeployer .super .deploy (vertx , verticle , args );
86
- }
87
63
88
- @ Override
89
- public void init (Vertx vertx , Context context ) {
90
- super .init (vertx , context );
91
- SqlRepository .init (vertx );
92
- }
93
-
94
- @ Override
95
- public void start (Promise <Void > startPromise ) throws Exception {
96
- VertxUtils
97
- .initHttpServer (
98
- vertx ,
99
- startPromise ,
100
- Routers .build (vertx , usernamePasswordCredentials ),
101
- port ,
102
- log
103
- );
104
- }
64
+ @ RequiredArgsConstructor
65
+ static class WebVerticle extends AbstractVerticle implements VertxDeployer {
105
66
106
- private static class WebToolContext implements ToolContext {
107
67
108
- Map <String , String > out = new ConcurrentHashMap <>();
68
+ private Credentials usernamePasswordCredentials ;
69
+ private int port = PORT_VAL ;
70
+ private final RunnerType runnerType ;
71
+ private final Supplier <ToolContext > contextSupplier ;
109
72
110
73
@ Override
111
- public ToolContext write (String name , String in ) {
112
- if (name == null ) {
113
- name = ToolContext .randomName ();
114
- }
115
- out .put (name , in );
116
- return this ;
74
+ public void init (Vertx vertx , Context context ) {
75
+ super .init (vertx , context );
76
+ SqlRepository .init (vertx );
117
77
}
118
78
119
79
@ Override
120
- public RunnerType runnerType () {
121
- return RunnerType .WEB ;
80
+ public void start (Promise <Void > startPromise ) throws Exception {
81
+ VertxUtils
82
+ .initHttpServer (
83
+ vertx ,
84
+ startPromise ,
85
+ build (usernamePasswordCredentials ),
86
+ port ,
87
+ log
88
+ );
122
89
}
123
90
124
- public JsonObject result () {
125
- String name ;
126
- if (out .size () == 1 ) {
127
- name = out .values ().toArray (String []::new )[0 ];
128
- } else {
129
- name = VertxUtils .resourcePath (RandomStringUtils .randomAlphabetic (10 ) + ".zip" );
130
- try (var zipOut = new ZipOutputStream (new FileOutputStream (name ))) {
131
- for (Entry <String , String > entry : out .entrySet ()) {
132
- zipOut .putNextEntry (new ZipEntry (entry .getKey ()));
133
- IOUtils .write (entry .getValue (), zipOut , StandardCharsets .UTF_8 );
91
+ @ Override
92
+ public Future <String > deploy (Vertx vertx , Verticle verticle , Args args ) {
93
+ args .getArgVal (USER_KEY ).ifPresent (a -> {
94
+ usernamePasswordCredentials = new UsernamePasswordCredentials (
95
+ a ,
96
+ args .readArg (PASSWD_KEY )
97
+ .getRequiredVal ("If username is not null, password must also not be null" )
98
+ ) {
99
+ @ Override
100
+ public <V > void checkValid (V arg ) throws CredentialValidationException {
101
+ super .checkValid (arg );
102
+ if (arg instanceof JsonObject credentials ) {
103
+ if (!(getUsername ().equals (credentials .getString ("username" ))
104
+ && getPassword ().equals (credentials .getString ("password" )))) {
105
+ throw new CredentialValidationException (
106
+ "Username or password error" );
107
+ }
108
+ }
134
109
}
135
- } catch (IOException e ) {
136
- log .error ("Write zip file error" , e );
137
- throw new RuntimeException (e );
138
- }
139
- log .info ("Generate file {0} ok" , name );
140
- }
141
- return JsonObject .of ("result" , name );
110
+ };
111
+ log .info ("Enable basicAuth" );
112
+ });
113
+ args .getArgVal (PORT_KEY ).ifPresent (a -> port = Integer .parseInt (a ));
114
+ return VertxDeployer .super .deploy (vertx , verticle , args );
142
115
}
143
116
144
- }
145
-
146
- private static class Routers {
147
-
148
- public static Router build (Vertx vertx , Credentials credentials ) {
117
+ private Router build (Credentials credentials ) {
149
118
var router = Router .router (vertx );
150
- var tools = App .supportTools (RunnerType . WEB );
119
+ var tools = App .supportTools (runnerType );
151
120
152
121
router .route ().handler (VertxUtils .bodyHandler (null ));
153
122
router .route ().handler (LoggerHandler .create ());
@@ -171,7 +140,8 @@ public static Router build(Vertx vertx, Credentials credentials) {
171
140
.map (t ->
172
141
new JsonObject ().put (
173
142
t .name ().name (),
174
- JsonObject .of ("desc" , t .name ().toString (), "help" , t .config ().toHelpString ())
143
+ JsonObject .of ("desc" , t .name ().toString (), "help" ,
144
+ t .config ().toHelpString ())
175
145
)
176
146
)
177
147
.reduce (new JsonObject (), JsonObject ::mergeIn )
@@ -190,37 +160,80 @@ public static Router build(Vertx vertx, Credentials credentials) {
190
160
null
191
161
);
192
162
193
- var globalConfig = VertxDeployer .getSharedArgs (WebRunner . class .getSimpleName (), vertx );
163
+ var globalConfig = VertxDeployer .getSharedArgs (getClass () .getSimpleName (), vertx );
194
164
for (Tool tool : tools ) {
195
165
String toolName = tool .name ().name ();
196
166
var path = "/" + toolName ;
197
167
if (tool instanceof WebTool ) {
198
168
VertxDeployer .sharedArgs (
199
169
vertx ,
200
170
toolName ,
201
- new Args ().copyConfigFrom (globalConfig .removePrefix (toolName )).copyConfigFrom (tool .config ())
171
+ new Args ().copyConfigFrom (globalConfig .removePrefix (toolName ))
172
+ .copyConfigFrom (tool .config ())
202
173
);
203
174
router .route (path + "/*" ).subRouter (((WebTool ) tool ).router (vertx ));
204
175
} else {
205
176
router .post (path ).respond (r -> {
206
177
var args = new Args ();
207
- r .body ().asJsonObject ().forEach (e -> args .arg (e .getKey (), (String ) e .getValue ()));
208
- var webToolContext = new WebToolContext ();
178
+ r .body ().asJsonObject ()
179
+ .forEach (e -> args .arg (e .getKey (), (String ) e .getValue ()));
180
+ var webToolContext = contextSupplier .get ();
209
181
args .copyConfigFrom (tool .config ())
210
182
.copyConfigFrom (globalConfig .removePrefix (toolName ))
211
183
.context (webToolContext );
212
184
213
185
try {
214
186
tool .run (args );
215
- return Future .succeededFuture (webToolContext .result ());
187
+ return Future .succeededFuture (webToolContext .toObject ());
216
188
} catch (Exception e ) {
217
189
return Future .failedFuture (e );
218
190
}
219
191
});
220
192
}
221
193
}
222
-
223
194
return router ;
224
195
}
225
196
}
197
+
198
+ static class WebToolContext implements ToolContext {
199
+
200
+ Map <String , String > out = new ConcurrentHashMap <>();
201
+
202
+ @ Override
203
+ public ToolContext write (String name , String in ) {
204
+ if (name == null ) {
205
+ name = ToolContext .randomName ();
206
+ }
207
+ out .put (name , in );
208
+ return this ;
209
+ }
210
+
211
+ @ Override
212
+ public RunnerType runnerType () {
213
+ return RunnerType .WEB ;
214
+ }
215
+
216
+ @ Override
217
+ public JsonObject toObject () {
218
+ String name ;
219
+ if (out .size () == 1 ) {
220
+ name = out .values ().toArray (String []::new )[0 ];
221
+ } else {
222
+ name = VertxUtils .resourcePath (RandomStringUtils .randomAlphabetic (10 ) + ".zip" );
223
+ try (var zipOut = new ZipOutputStream (new FileOutputStream (name ))) {
224
+ for (Entry <String , String > entry : out .entrySet ()) {
225
+ zipOut .putNextEntry (new ZipEntry (entry .getKey ()));
226
+ IOUtils .write (entry .getValue (), zipOut , StandardCharsets .UTF_8 );
227
+ }
228
+ } catch (IOException e ) {
229
+ log .error ("Write zip file error" , e );
230
+ throw new RuntimeException (e );
231
+ }
232
+ log .info ("Generate file {0} ok" , name );
233
+ }
234
+ return JsonObject .of ("result" , name );
235
+ }
236
+
237
+
238
+ }
226
239
}
0 commit comments