Skip to content

Commit 1ca1f91

Browse files
committed
Optimize WebRunner
1 parent acf5dbb commit 1ca1f91

File tree

8 files changed

+121
-101
lines changed

8 files changed

+121
-101
lines changed

src/main/java/net/cofcool/sourcebox/App.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import net.cofcool.sourcebox.logging.Logger;
1515
import net.cofcool.sourcebox.logging.LoggerFactory;
1616
import net.cofcool.sourcebox.runner.CLIRunner;
17+
import net.cofcool.sourcebox.runner.GUIRunner;
1718
import net.cofcool.sourcebox.runner.WebRunner;
1819
import net.cofcool.sourcebox.util.Utils;
1920
import org.apache.commons.io.FileUtils;
@@ -30,7 +31,8 @@ public class App {
3031

3132
private static final Map<RunnerType, ToolRunner> RUNNER_MAP = Map.of(
3233
RunnerType.WEB, new WebRunner(),
33-
RunnerType.CLI, new CLIRunner()
34+
RunnerType.CLI, new CLIRunner(),
35+
RunnerType.GUI, new GUIRunner()
3436
);
3537

3638
static final Args ALIAS = new Args();

src/main/java/net/cofcool/sourcebox/ToolContext.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ default ToolContext write(Object val) {
1414

1515
RunnerType runnerType();
1616

17+
default Object toObject() {
18+
return null;
19+
}
20+
1721
static String randomName() {
1822
return RandomStringUtils.randomAlphabetic(6);
1923
}

src/main/java/net/cofcool/sourcebox/internal/HtmlDownloader.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ public Args config() {
261261
.arg(new Arg("proxy", null, "request proxy", false, "127.0.0.1:8087"))
262262
.arg(new Arg("out", "./", "output folder", false, null))
263263
.arg(new Arg("clean", "false", "remove css or javascript", false, null))
264-
.runnerTypes(EnumSet.of(RunnerType.CLI));
264+
.runnerTypes(EnumSet.allOf(RunnerType.class));
265265
}
266266

267267
private static String checkText(Element e, String out) {

src/main/java/net/cofcool/sourcebox/internal/SimpleNote.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public Args config() {
4848
.arg(new Arg(NoteConfig.FILE_KEY, NoteConfig.FILE_NAME, "note filename", false, null))
4949
.arg(new Arg(NoteConfig.PATH_KEY, NoteConfig.PATH_VAL, "note file path", false, null))
5050
.arg(new Arg(NoteConfig.PORT_KEY, NoteConfig.PORT_VAL + "", "note web server listen port", false, null))
51-
.runnerTypes(EnumSet.of(RunnerType.CLI, RunnerType.WEB))
51+
.runnerTypes(EnumSet.allOf(RunnerType.class))
5252
.alias("note", name(), NoteConfig.PATH_KEY, null);
5353
}
5454

src/main/java/net/cofcool/sourcebox/internal/commandhelper/CommandHelper.java

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
package net.cofcool.sourcebox.internal.commandhelper;
22

3-
import io.vertx.core.Vertx;
4-
import io.vertx.ext.web.Router;
3+
import java.util.EnumSet;
54
import java.util.List;
65
import java.util.stream.Collectors;
76
import lombok.CustomLog;
7+
import net.cofcool.sourcebox.Tool;
88
import net.cofcool.sourcebox.ToolName;
9-
import net.cofcool.sourcebox.WebTool;
109
import org.apache.commons.io.FilenameUtils;
1110

1211
@CustomLog
13-
public class CommandHelper implements WebTool {
12+
public class CommandHelper implements Tool {
1413

1514
private CommandManager commandManager;
1615

@@ -67,7 +66,8 @@ public Args config() {
6766
.arg(new Arg("aliasPath", "./alias", "alias file path", false, null))
6867
.arg(new Arg("find", "ALL", "find command, can be tag or alias, ALL will list all", false, "#md5"))
6968
.arg(new Arg("del", null, "delete command, can be tag or alias, ALL will delete all", false, "#md5"))
70-
.arg(new Arg("store", null, "save alias into env, ALL will save all", false, "ALL"));
69+
.arg(new Arg("store", null, "save alias into env, ALL will save all", false, "ALL"))
70+
.runnerTypes(EnumSet.of(RunnerType.CLI, RunnerType.GUI));
7171
}
7272

7373
@Override
@@ -77,10 +77,5 @@ public Args defaultConfig(String globalDir) {
7777
.arg("aliasPath", FilenameUtils.concat(globalDir, "alias"));
7878
}
7979

80-
@Override
81-
public Router router(Vertx vertx) {
82-
return null;
83-
}
84-
8580

8681
}

src/main/java/net/cofcool/sourcebox/runner/WebRunner.java

Lines changed: 99 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@
1818
import java.util.Map;
1919
import java.util.Map.Entry;
2020
import java.util.concurrent.ConcurrentHashMap;
21+
import java.util.function.Supplier;
2122
import java.util.zip.ZipEntry;
2223
import java.util.zip.ZipOutputStream;
2324
import lombok.CustomLog;
25+
import lombok.RequiredArgsConstructor;
2426
import net.cofcool.sourcebox.App;
2527
import net.cofcool.sourcebox.Tool;
2628
import net.cofcool.sourcebox.Tool.Args;
@@ -38,20 +40,18 @@
3840
* config listen port: {@link #PORT_KEY}
3941
*/
4042
@CustomLog
41-
public class WebRunner extends AbstractVerticle implements ToolRunner, VertxDeployer {
43+
public class WebRunner implements ToolRunner {
4244

4345
public static final String PORT_KEY = "web.port";
4446
public static final String USER_KEY = "web.username";
4547
public static final String PASSWD_KEY = "web.password";
4648
public static final int PORT_VAL = 38080;
4749

48-
private Credentials usernamePasswordCredentials;
49-
private int port = PORT_VAL;
50-
5150
@Override
5251
public boolean run(Args args) throws Exception {
5352
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()));
5555
return true;
5656
}
5757

@@ -60,94 +60,63 @@ public String help() {
6060
return String.join(", ", USER_KEY, PASSWD_KEY, PORT_KEY);
6161
}
6262

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-
}
8763

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 {
10566

106-
private static class WebToolContext implements ToolContext {
10767

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;
10972

11073
@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);
11777
}
11878

11979
@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+
);
12289
}
12390

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+
}
134109
}
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);
142115
}
143116

144-
}
145-
146-
private static class Routers {
147-
148-
public static Router build(Vertx vertx, Credentials credentials) {
117+
private Router build(Credentials credentials) {
149118
var router = Router.router(vertx);
150-
var tools = App.supportTools(RunnerType.WEB);
119+
var tools = App.supportTools(runnerType);
151120

152121
router.route().handler(VertxUtils.bodyHandler(null));
153122
router.route().handler(LoggerHandler.create());
@@ -171,7 +140,8 @@ public static Router build(Vertx vertx, Credentials credentials) {
171140
.map(t ->
172141
new JsonObject().put(
173142
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())
175145
)
176146
)
177147
.reduce(new JsonObject(), JsonObject::mergeIn)
@@ -190,37 +160,80 @@ public static Router build(Vertx vertx, Credentials credentials) {
190160
null
191161
);
192162

193-
var globalConfig = VertxDeployer.getSharedArgs(WebRunner.class.getSimpleName(), vertx);
163+
var globalConfig = VertxDeployer.getSharedArgs(getClass().getSimpleName(), vertx);
194164
for (Tool tool : tools) {
195165
String toolName = tool.name().name();
196166
var path = "/" + toolName;
197167
if (tool instanceof WebTool) {
198168
VertxDeployer.sharedArgs(
199169
vertx,
200170
toolName,
201-
new Args().copyConfigFrom(globalConfig.removePrefix(toolName)).copyConfigFrom(tool.config())
171+
new Args().copyConfigFrom(globalConfig.removePrefix(toolName))
172+
.copyConfigFrom(tool.config())
202173
);
203174
router.route(path + "/*").subRouter(((WebTool) tool).router(vertx));
204175
} else {
205176
router.post(path).respond(r -> {
206177
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();
209181
args.copyConfigFrom(tool.config())
210182
.copyConfigFrom(globalConfig.removePrefix(toolName))
211183
.context(webToolContext);
212184

213185
try {
214186
tool.run(args);
215-
return Future.succeededFuture(webToolContext.result());
187+
return Future.succeededFuture(webToolContext.toObject());
216188
} catch (Exception e) {
217189
return Future.failedFuture(e);
218190
}
219191
});
220192
}
221193
}
222-
223194
return router;
224195
}
225196
}
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+
}
226239
}

src/test/java/net/cofcool/sourcebox/runner/WebRunnerAuthTest.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@
55
import io.vertx.junit5.VertxExtension;
66
import io.vertx.junit5.VertxTestContext;
77
import net.cofcool.sourcebox.Tool.Args;
8+
import net.cofcool.sourcebox.Tool.RunnerType;
89
import net.cofcool.sourcebox.ToolName;
910
import net.cofcool.sourcebox.internal.simplenote.NoteConfig;
11+
import net.cofcool.sourcebox.runner.WebRunner.WebToolContext;
12+
import net.cofcool.sourcebox.runner.WebRunner.WebVerticle;
1013
import org.apache.commons.lang3.RandomUtils;
1114
import org.junit.jupiter.api.Assertions;
1215
import org.junit.jupiter.api.BeforeAll;
@@ -22,7 +25,7 @@ public class WebRunnerAuthTest {
2225
static void deployVerticle(Vertx vertx, VertxTestContext testContext) throws Exception {
2326
System.setProperty("logging.debug", "true");
2427
System.setProperty("upload.dir", "target/file-uploads");
25-
new WebRunner()
28+
new WebVerticle(RunnerType.WEB, WebToolContext::new)
2629
.deploy(
2730
vertx,
2831
null,

0 commit comments

Comments
 (0)