|
| 1 | +package Controller; |
| 2 | + |
| 3 | +import Model.Configuration; |
| 4 | +import Model.FileParser; |
| 5 | +import Model.ParserException; |
| 6 | +import io.vertx.core.AbstractVerticle; |
| 7 | +import io.vertx.core.Context; |
| 8 | +import io.vertx.core.Future; |
| 9 | +import io.vertx.core.Vertx; |
| 10 | +import io.vertx.core.json.JsonArray; |
| 11 | +import io.vertx.ext.web.FileUpload; |
| 12 | +import io.vertx.ext.web.Router; |
| 13 | +import io.vertx.ext.web.RoutingContext; |
| 14 | +import io.vertx.ext.web.handler.BodyHandler; |
| 15 | +import io.vertx.ext.web.handler.StaticHandler; |
| 16 | + |
| 17 | +import java.util.Iterator; |
| 18 | + |
| 19 | +/** |
| 20 | + * @author Robin Duda |
| 21 | + */ |
| 22 | +public class Website extends AbstractVerticle { |
| 23 | + private Vertx vertx; |
| 24 | + |
| 25 | + @Override |
| 26 | + public void init(Vertx vertx, Context context) { |
| 27 | + this.vertx = vertx; |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + public void start(Future<Void> start) { |
| 32 | + Router router = Router.router(vertx); |
| 33 | + |
| 34 | + router.route().handler(BodyHandler.create()); |
| 35 | + setRouterAPI(router); |
| 36 | + router.route("/*").handler(StaticHandler.create()); |
| 37 | + |
| 38 | + vertx.createHttpServer().requestHandler(router::accept).listen(Configuration.WEB_PORT); |
| 39 | + |
| 40 | + start.complete(); |
| 41 | + } |
| 42 | + |
| 43 | + private void setRouterAPI(Router router) { |
| 44 | + router.route("/api/upload").handler(context -> { |
| 45 | + Iterator<FileUpload> iterator = context.fileUploads().iterator(); |
| 46 | + |
| 47 | + if (iterator.hasNext()) { |
| 48 | + FileUpload upload = context.fileUploads().iterator().next(); |
| 49 | + |
| 50 | + vertx.fileSystem().readFile(upload.uploadedFileName(), file -> { |
| 51 | + try { |
| 52 | + sendbus(new FileParser(file.result().getBytes()).toJsonArray()); |
| 53 | + redirect(context, "/done.html"); |
| 54 | + } catch (ParserException e) { |
| 55 | + redirect(context, "/error.html"); |
| 56 | + } |
| 57 | + }); |
| 58 | + } else { |
| 59 | + redirect(context, "/error.html"); |
| 60 | + } |
| 61 | + }); |
| 62 | + } |
| 63 | + |
| 64 | + private void sendbus(JsonArray list) { |
| 65 | + for (int i = 0; i < list.size(); i++) { |
| 66 | + vertx.eventBus().send(Configuration.BUS_TRANSACTIONS, list.getJsonObject(i)); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + private void redirect(RoutingContext context, String uri) { |
| 71 | + context.request().response().setStatusCode(301).putHeader("location", uri).end(); |
| 72 | + } |
| 73 | +} |
0 commit comments