Example usage for io.vertx.core.json JsonArray add

List of usage examples for io.vertx.core.json JsonArray add

Introduction

In this page you can find the example usage for io.vertx.core.json JsonArray add.

Prototype

public JsonArray add(Object value) 

Source Link

Document

Add an Object to the JSON array.

Usage

From source file:com.github.ithildir.numbers.game.util.JsonUtil.java

License:Open Source License

public static JsonArray getArray(JsonObject jsonObject) {
    JsonArray jsonArray = new JsonArray();

    jsonArray.add(jsonObject);

    return jsonArray;
}

From source file:com.groupon.vertx.redis.RedisCommand.java

License:Apache License

/**
 * Renders the command into a JsonObject for transport across the event bus.
 *
 * @return - A JsonObject containing the command.
 *//* w w w. j  a  v a2 s. co m*/
public JsonObject toJson() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.put("command", type.getCommand());

    JsonArray arrayArgs = new JsonArray();
    for (String arg : arguments) {
        arrayArgs.add(arg);
    }
    jsonObject.put("arguments", arrayArgs);

    return jsonObject;
}

From source file:com.groupon.vertx.redis.RedisInputStream.java

License:Apache License

/**
 * The multi-line responses will be an array containing all of the subsequent responses for the
 * multi-line response.//from  w  ww  .  j  av  a  2 s . c o  m
 *
 * @param multiLine
 * @return JsonArray
 */
private JsonArray processMultiLine(byte[] multiLine) {
    if (multiLine[1] == '-') {
        return null;
    }

    JsonArray result = new JsonArray();

    int lines = processIntegerLine(multiLine);
    while (lines > 0) {
        byte[] line = completedLines.poll();
        if (line == null) {
            // Unable to find completed line for multi command
            result.addNull();
        } else if (line[0] == RedisResponseType.MULTI_BULK_REPLY.marker) {
            result.add(processMultiLine(line));
        } else if (line[0] == RedisResponseType.BULK_REPLY.marker) {
            result.add(processBulkLine(line));
        } else if (line[0] == RedisResponseType.INTEGER_REPLY.marker) {
            result.add(processIntegerLine(line));
        } else {
            result.add(processLine(line));
        }

        lines--;
    }

    return result;
}

From source file:com.groupon.vertx.redis.RedisTransaction.java

License:Apache License

public Future<JsonObject> exec() {
    final Future<JsonObject> finalResult = Future.future();
    if (!pendingCommands.isEmpty()) {
        JsonArray commands = new JsonArray();
        final List<Future<JsonObject>> clientCommandResponses = new ArrayList<>();
        clientCommandResponses.add(finalResult);

        RedisCommand command = pendingCommands.poll();
        while (command != null) {
            clientCommandResponses.add(command.getClientCommandResponse());
            commands.add(command.toJson());
            command = pendingCommands.poll();
        }/* w ww  . ja  va  2s  . c  o m*/

        JsonObject transactionCommands = new JsonObject();
        transactionCommands.put("isTransaction", true);
        transactionCommands.put("commands", commands);
        final DeliveryOptions deliveryOptions = new DeliveryOptions().setSendTimeout(replyTimeout);
        eventBus.send(eventBusAddress, transactionCommands, deliveryOptions,
                new Handler<AsyncResult<Message<JsonObject>>>() {
                    @Override
                    public void handle(AsyncResult<Message<JsonObject>> messageAsyncResult) {
                        JsonObject response;
                        if (messageAsyncResult.failed()) {
                            response = new JsonObject().put("status", "error").put("code",
                                    HttpURLConnection.HTTP_GATEWAY_TIMEOUT);
                        } else {
                            response = messageAsyncResult.result().body();
                        }

                        int index = 0;
                        executeResponse(clientCommandResponses.remove(0), response); // EXEC response
                        for (Future<JsonObject> clientCommandResponse : clientCommandResponses) {
                            if (clientCommandResponse != null) {
                                JsonObject result = constructTransactionCommandResult(response, index);
                                executeResponse(clientCommandResponse, result);
                            }
                            index++;
                        }
                    }
                });
    } else {
        // Nothing to execute.
        finalResult.complete(null);
    }
    return finalResult;
}

From source file:com.hpe.sw.cms.verticle.ApiVerticle.java

License:Apache License

/**
 * Handler to handle Docker Registry event
 *
 * @return handler context//from www .  ja v a 2 s  .c o  m
 */
private Handler<RoutingContext> registryEventHandler() {
    return routingContext -> {
        JsonObject body = routingContext.getBodyAsJson();
        LOG.info("Docker Registry events received from {}", routingContext.request().getParam("registry"));
        JsonArray events = body.getJsonArray("events");
        JsonArray updated = new JsonArray();
        JsonArray deleted = new JsonArray();
        events.forEach(e -> {
            JsonObject event = (JsonObject) e;
            if (event.getString("action").equals("push")) {
                JsonObject obj = createObj(event);
                if (obj != null) {
                    updated.add(obj);
                }
            } else if (event.getString("action").equals("delete")) {
                JsonObject obj = createObj(event);
                if (obj != null) {
                    deleted.add(obj);
                }
            }
        });
        if (updated.size() != 0)
            vertx.eventBus().publish(Events.EVENT_IMAGES_UPDATED.name(), updated);
        if (deleted.size() != 0) //TODO
            vertx.eventBus().publish(Events.EVENT_IMAGES_DELETED.name(), deleted);
        //Always return 200 OK.
        routingContext.response().setStatusCode(200).end("OK");

    };
}

From source file:com.hpe.sw.cms.verticle.MongoStoreVerticle.java

License:Apache License

@Override
public void start() throws Exception {
    super.start();
    client = MongoClient.createShared(vertx, config().getJsonObject("mongo"));
    vertx.eventBus().consumer(Events.GET_IMAGES.name(), msg -> {
        JsonObject param = (JsonObject) msg.body();
        JsonObject query = new JsonObject();
        if (param != null && param.getString("timestamp") != null) {
            Long timestamp = Long.parseLong(param.getString("timestamp"));
            query.put(Image.TIMESTAMP, new JsonObject().put("$gte", timestamp));
        } else if (param != null && param.getString("imageid") != null) {
            query.put(Image.IMAGE_ID, param.getString(Image.IMAGE_ID));
        }/*ww w  . j a v  a  2  s. co  m*/

        if (!query.containsKey(Image.IMAGE_ID) && (param == null || param.getString("include") == null
                || !"all".equals(param.getString("include")))) {
            query.put(Image.IMAGE_ID, new JsonObject().put("$exists", true));
        }
        JsonArray images = new JsonArray();
        client.find("images", query, res -> {
            if (res.succeeded()) {
                List<JsonObject> result = res.result();
                for (JsonObject dbImage : result) {
                    images.add(Image.cloneImage(dbImage));
                }
                msg.reply(images);
            }
        });
    });

    vertx.eventBus().consumer(Events.DOWNLOAD_FILE.name(), msg -> {
        JsonObject query = (JsonObject) msg.body();
        LOG.debug("DOWNLOAD_FILE query is " + query);
        client.find("images", query, res -> {
            if (res.succeeded()) {
                List<JsonObject> result = res.result();
                LOG.debug("DOWNLOAD_FILE result is " + result.size());
                if (result.size() > 0) {
                    msg.reply(result.get(0));
                } else {
                    msg.reply(null);
                }
            }
        });
    });

    vertx.eventBus().consumer(Events.IMAGES_UPDATED.name(), msg -> {
        JsonArray updates = new JsonArray();
        JsonObject query = new JsonObject();
        query.put(Image.IS_SCANNED, false);
        int fetchSize = Integer.valueOf(String.valueOf(msg.body()));
        FindOptions options = new FindOptions();
        JsonObject sort = new JsonObject();
        sort.put(Image.TIMESTAMP, -1);
        options.setLimit(fetchSize).setSort(sort);
        client.findWithOptions("images", query, options, res -> {
            if (res.succeeded()) {
                List<JsonObject> result = res.result();
                for (JsonObject update : result) {
                    updates.add(update);
                    LOG.debug("get image from DB :" + Image.getImageKey(update));
                }
                LOG.debug("IMAGES_UPDATED reply updates size " + updates.size());
                msg.reply(updates);
            }
        });
    });

    vertx.eventBus().consumer(Events.SCANFILE_UPLOADED.name(), msg -> {
        JsonObject upFile = (JsonObject) msg.body();
        JsonObject query = new JsonObject();
        query.put(Image.HOST, upFile.getString(Image.HOST)).put(Image.NAME, upFile.getString(Image.NAME))
                .put(Image.TAG, upFile.getString(Image.TAG));
        client.find("images", query, res -> {
            if (res.succeeded()) {
                List<JsonObject> result = res.result();
                if (result.size() == 0) {
                    LOG.error("no mapped image in DB for " + Image.getImageKey(upFile));
                    return;
                }
                for (JsonObject dbImage : result) {
                    if (upFile.getBoolean("isScanFailed")) {
                        //Failed in scanning.
                        LOG.info("store failed scan to DB " + Image.getImageKey(upFile));
                        dbImage.put(Image.IS_SCANNED, true);
                        dbImage.put(Image.IS_SCANNED_FAILED, true);
                    } else {
                        //successfully in scanning.
                        LOG.info("store scanfile to DB " + Image.getImageKey(upFile));
                        dbImage.put(Image.IS_SCANNED, true);
                        dbImage.put(Image.IS_SCANNED_FAILED, false);
                        dbImage.put(Image.IMAGE_ID, upFile.getString(Image.IMAGE_ID));
                        dbImage.put(Image.SCANNED_FILE, upFile.getBinary(Image.SCANNED_FILE));
                    }
                    client.save("images", dbImage, h -> {
                        if (h.succeeded()) {
                            LOG.info("SCANFILE_UPLOADED:Image " + Image.getImageKey(dbImage) + " updated !");
                        } else {
                            h.cause().printStackTrace();
                        }
                    });
                }
            }
        });

    });

    vertx.eventBus().consumer(Events.ENRICHFILE_UPLOADED.name(), msg -> {
        JsonArray upFiles = (JsonArray) msg.body();
        for (Object upFileObj : upFiles) {
            JsonObject upFile = (JsonObject) upFileObj;
            if (upFile.getBinary("enrichedFile") == null) {
                LOG.info("enrichedFile is emptry for " + upFile.getString("imageid"));
                continue;
            }
            LOG.info("store enrichfile to DB " + upFile.getString("imageid"));
            JsonObject query = new JsonObject();
            query.put(Image.IMAGE_ID, upFile.getString(Image.IMAGE_ID));
            client.find("images", query, res -> {
                if (res.succeeded()) {
                    List<JsonObject> result = res.result();
                    for (JsonObject dbImage : result) {
                        dbImage.put(Image.IS_ENRICHED, true);
                        dbImage.put(Image.ENRICHED_FILE, upFile.getBinary(Image.ENRICHED_FILE));
                        client.save("images", dbImage, h -> {
                            if (h.succeeded()) {
                                LOG.info("ENRICHFILE_UPLOADED:Image " + Image.getImageKey(dbImage)
                                        + " updated !");
                            } else {
                                h.cause().printStackTrace();
                            }
                        });
                    }
                }
            });
        }

    });

    vertx.eventBus().consumer(Events.IMAGE_TO_ENRICH.name(), msg -> {
        JsonObject query = new JsonObject();
        query.put(Image.IS_SCANNED, true).put(Image.IS_SCANNED_FAILED, false).put(Image.IS_ENRICHED, false);
        client.find("images", query, res -> {
            if (res.succeeded()) {
                List<JsonObject> result = res.result();
                msg.reply(new JsonArray(result));
            }
        });
    });

    vertx.eventBus().consumer(Events.NEW_IMAGE.name(), msg -> {
        //to store events in
        JsonObject obj = (JsonObject) msg.body();
        JsonObject query = new JsonObject();
        query.put(Image.HOST, obj.getString(Image.HOST)).put(Image.NAME, obj.getString(Image.NAME))
                .put(Image.TAG, obj.getString(Image.TAG));
        client.find("images", query, res -> {
            if (res.succeeded()) {
                List<JsonObject> result = res.result();
                if (result.isEmpty()) {
                    //inserted
                    client.insert("images", obj, h -> {
                        if (h.succeeded()) {
                            LOG.info("IMAGES_COMMING :Image " + Image.getImageKey(obj) + " inserted !");
                        } else {
                            h.cause().printStackTrace();
                        }
                    });
                } else if (result.size() == 1) {
                    JsonObject toUpdate = result.get(0);
                    if (!obj.getString(Image.SIGN).equals(toUpdate.getString(Image.SIGN))) {
                        toUpdate.put(Image.TIMESTAMP, obj.getLong(Image.TIMESTAMP))
                                .put(Image.SIGN, obj.getString(Image.SIGN))
                                .put(Image.IS_SCANNED, obj.getBoolean(Image.IS_SCANNED))
                                .put(Image.IS_ENRICHED, obj.getBoolean(Image.IS_ENRICHED));
                        //saved
                        client.save("images", toUpdate, h -> {
                            if (h.succeeded()) {
                                LOG.info("IMAGES_COMMING :Image " + Image.getImageKey(obj) + " updated !");
                            } else {
                                h.cause().printStackTrace();
                            }
                        });
                    } else {
                        LOG.info("IMAGES_COMMING :Image " + Image.getImageKey(obj)
                                + " has the same sign with the coming image, so will not update to DB !");
                    }
                } else {
                    throw new RuntimeException(
                            "IMAGES_COMMING :Found " + result.size() + " image for " + Image.getImageKey(obj));
                }
            }
        });
    });
}

From source file:com.hpe.sw.cms.verticle.RecognizerVerticle.java

License:Apache License

@Override
public void start() throws Exception {
    super.start();
    getVertx().setPeriodic(config().getLong("recognizer.interval", INTERVAL), h -> {
        getVertx().eventBus().send(Events.IMAGE_TO_ENRICH.name(), null, event -> {
            Message msg = event.result();
            if (msg != null) {
                String enrichPath = Constant.PROJECT_PATH + "xmlenricher/runtime/xmlenricher/Scans/incoming/";
                JsonArray scanfiles = (JsonArray) msg.body();
                for (Object obj : scanfiles) {
                    FileOutputStream fop = null;
                    try {
                        JsonObject image = (JsonObject) obj;
                        String filePath = enrichPath + image.getString("imageid") + ".xsf";
                        File file = new File(filePath);
                        if (!file.exists()) {
                            file.createNewFile();
                        }/*from   w w  w .java  2 s  .  com*/
                        fop = new FileOutputStream(file);
                        IOUtils.write(image.getBinary("scannedFile"), fop);
                        fop.flush();
                        fop.close();
                    } catch (Exception e) {
                        LOG.error("Error in writing scan file", e);
                    } finally {
                        if (fop != null) {
                            try {
                                fop.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
    });

    //check whether there are new enriched files
    getVertx().setPeriodic(config().getLong("recognizer.interval", INTERVAL), h -> {
        String enrichPath = Constant.PROJECT_PATH + "xmlenricher/runtime/xmlenricher/Scans/processedcore/";
        File fileDir = new File(enrichPath);
        File[] fileList = fileDir.listFiles(XSF_FILTER);
        JsonArray enrichedFiles = new JsonArray();
        for (File file : fileList) {
            if (file.isFile()) {
                String imageid = file.getName().split("\\.")[0];
                try {
                    JsonObject enrichedFile = new JsonObject();
                    enrichedFile.put("imageid", imageid);
                    enrichedFile.put("enrichedFile", FileUtils.readFileToByteArray(file));
                    enrichedFiles.add(enrichedFile);
                    file.delete(); //TODO: do a batch delete after all enrichedFiles are collected
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (enrichedFiles.size() > 0) {
            getVertx().eventBus().publish(Events.ENRICHFILE_UPLOADED.name(), enrichedFiles);
        }
    });
}

From source file:com.hpe.sw.cms.verticle.ScanVerticle.java

License:Apache License

private void processImage(String dricHost, String reigstryHost, String image, String tag) throws Exception {
    final String swarmProtocol = config().getString("swarm.protocol");
    final String swarmHost = config().getString("swarm.host");

    JsonObject hostConfig = new JsonObject();
    hostConfig.put("Privileged", true);

    JsonObject restartPolicy = new JsonObject();
    restartPolicy.put("Name", "no");

    JsonObject createContinaerJson = new JsonObject();
    createContinaerJson.put("AttachStdin", true);
    createContinaerJson.put("AttachStdout", true);
    createContinaerJson.put("AttachStderr", true);
    createContinaerJson.put("Tty", true);
    createContinaerJson.put("OpenStdin", true);
    createContinaerJson.put("StdinOnce", true);
    JsonArray cmds = new JsonArray();
    cmds.add("-l=file").add(dricHost).add(reigstryHost).add(image).add(tag);
    createContinaerJson.put("Cmd", cmds);
    createContinaerJson.put("Image", config().getString("swarm.scan.image"));
    createContinaerJson.put("StopSignal", "SIGTERM");
    createContinaerJson.put("", true);

    hostConfig.put("RestartPolicy", restartPolicy);
    createContinaerJson.put("HostConfig", hostConfig);

    httpClient.postAbs(swarmProtocol + swarmHost + "/containers/create", new Handler<HttpClientResponse>() {
        @Override//  w  w  w .  j  a  v  a2  s. c om
        public void handle(HttpClientResponse event) {
            event.bodyHandler(new Handler<Buffer>() {
                @Override
                public void handle(Buffer buffer) {
                    JsonObject retVal = buffer.toJsonObject();
                    String containerId = retVal.getString("Id");
                    getVertx().sharedData().getLocalMap("scanContainerIds").put(containerId, containerId);
                    httpClient.postAbs(swarmProtocol + swarmHost + "/containers/" + containerId + "/start",
                            new Handler<HttpClientResponse>() {
                                @Override
                                public void handle(HttpClientResponse event) {
                                    LOG.info("start container with response code :" + event.statusCode());
                                }
                            }).end();
                }
            });
        }
    }).putHeader("content-type", "application/json")
            .putHeader("content-length", String.valueOf(createContinaerJson.toString().length()))
            .write(createContinaerJson.toString()).end();
}

From source file:com.iot.i4.server.I4Server.java

@Override
public void start() throws Exception {
    // Create a mongo client using all defaults (connect to localhost and default port) using the database name "demo".
    JsonObject config = new JsonObject().put("connection_string", "mongodb://localhost:27017").put("db_name",
            "i4");
    mongo = MongoClient.createShared(Vertx.vertx(), config);

    // the load function just populates some data on the storage
    loadData(mongo);/*from ww  w .  j  a  v  a2  s  .c  o  m*/

    Router router = Router.router(Vertx.vertx());
    router.route().handler(BodyHandler.create());

    //1.findAll payloads
    router.get("/api/payloads").handler(ctx -> {
        mongo.find("payloads", new JsonObject(), lookup -> {
            // error handling
            if (lookup.failed()) {
                ctx.fail(500);
                return;
            }

            // now convert the list to a JsonArray because it will be easier to encode the final object as the response.
            final JsonArray json = new JsonArray();
            for (JsonObject o : lookup.result()) {
                json.add(o);
            }
            ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            ctx.response().end(json.encode());
        });
    });

    //1. findAll
    router.get("/api/users").handler(ctx -> {
        mongo.find("users", new JsonObject(), lookup -> {
            // error handling
            if (lookup.failed()) {
                ctx.fail(500);
                return;
            }
            // now convert the list to a JsonArray because it will be easier to encode the final object as the response.
            final JsonArray json = new JsonArray();
            for (JsonObject o : lookup.result()) {
                json.add(o);
            }
            ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            ctx.response().end(json.encode());
        });
    });

    //2.findOne
    router.get("/api/users/:id").handler(ctx -> {
        mongo.findOne("users", new JsonObject().put("_id", ctx.request().getParam("id")), null, lookup -> {
            // error handling
            if (lookup.failed()) {
                ctx.fail(500);
                return;
            }

            JsonObject user = lookup.result();

            if (user == null) {
                ctx.fail(404);
            } else {
                ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json");
                ctx.response().end(user.encode());
            }
        });
    });

    router.post("/api/users").handler(ctx -> {
        JsonObject newUser = ctx.getBodyAsJson();

        mongo.findOne("users", new JsonObject().put("username", newUser.getString("username")), null,
                lookup -> {
                    // error handling
                    if (lookup.failed()) {
                        ctx.fail(500);
                        return;
                    }

                    JsonObject user = lookup.result();

                    if (user != null) {
                        // already exists
                        ctx.fail(500);
                    } else {
                        mongo.insert("users", newUser, insert -> {
                            // error handling
                            if (insert.failed()) {
                                ctx.fail(500);
                                return;
                            }

                            // add the generated id to the user object
                            newUser.put("_id", insert.result());

                            ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json");
                            ctx.response().end(newUser.encode());
                        });
                    }
                });
    });

    router.put("/api/users/:id").handler(ctx -> {
        mongo.findOne("users", new JsonObject().put("_id", ctx.request().getParam("id")), null, lookup -> {
            // error handling
            if (lookup.failed()) {
                ctx.fail(500);
                return;
            }

            JsonObject user = lookup.result();

            if (user == null) {
                // does not exist
                ctx.fail(404);
            } else {

                // update the user properties
                JsonObject update = ctx.getBodyAsJson();

                user.put("username", update.getString("username"));
                user.put("firstName", update.getString("firstName"));
                user.put("lastName", update.getString("lastName"));
                user.put("address", update.getString("address"));

                mongo.replace("users", new JsonObject().put("_id", ctx.request().getParam("id")), user,
                        replace -> {
                            // error handling
                            if (replace.failed()) {
                                ctx.fail(500);
                                return;
                            }

                            ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json");
                            ctx.response().end(user.encode());
                        });
            }
        });
    });

    router.delete("/api/users/:id").handler(ctx -> {
        mongo.findOne("users", new JsonObject().put("_id", ctx.request().getParam("id")), null, lookup -> {
            // error handling
            if (lookup.failed()) {
                ctx.fail(500);
                return;
            }

            JsonObject user = lookup.result();

            if (user == null) {
                // does not exist
                ctx.fail(404);
            } else {

                mongo.remove("users", new JsonObject().put("_id", ctx.request().getParam("id")), remove -> {
                    // error handling
                    if (remove.failed()) {
                        ctx.fail(500);
                        return;
                    }

                    ctx.response().setStatusCode(204);
                    ctx.response().end();
                });
            }
        });
    });
    // Create a router endpoint for the static content.
    router.route().handler(StaticHandler.create());
    Vertx.vertx().createHttpServer().requestHandler(router::accept).listen(8080);
    //Vertx.vertx().createHttpServer().requestHandler(req -> req.response().end("Hello World From I4Server!")).listen(8080);
    System.out.println("Server started & listening to [8080]");
}

From source file:com.klwork.spring.vertx.render.MyStaticHandlerImpl.java

License:Open Source License

private void sendDirectoryListing(String dir, RoutingContext context) {
    FileSystem fileSystem = new WindowsFileSystem((VertxInternal) context.vertx());
    HttpServerRequest request = context.request();

    fileSystem.readDir(dir, asyncResult -> {
        if (asyncResult.failed()) {
            context.fail(asyncResult.cause());
        } else {//  ww  w . j  av  a 2  s  .com

            String accept = request.headers().get("accept");
            if (accept == null) {
                accept = "text/plain";
            }

            if (accept.contains("html")) {
                String normalizedDir = context.normalisedPath();
                if (!normalizedDir.endsWith("/")) {
                    normalizedDir += "/";
                }

                String file;
                StringBuilder files = new StringBuilder("<ul id=\"files\">");

                List<String> list = asyncResult.result();
                Collections.sort(list);

                for (String s : list) {
                    file = s.substring(s.lastIndexOf(File.separatorChar) + 1);
                    // skip dot files
                    if (!includeHidden && file.charAt(0) == '.') {
                        continue;
                    }
                    files.append("<li><a href=\"");
                    files.append(normalizedDir);
                    files.append(file);
                    files.append("\" title=\"");
                    files.append(file);
                    files.append("\">");
                    files.append(file);
                    files.append("</a></li>");
                }

                files.append("</ul>");

                // link to parent dir
                int slashPos = 0;
                for (int i = normalizedDir.length() - 2; i > 0; i--) {
                    if (normalizedDir.charAt(i) == '/') {
                        slashPos = i;
                        break;
                    }
                }

                String parent = "<a href=\"" + normalizedDir.substring(0, slashPos + 1) + "\">..</a>";

                request.response().putHeader("content-type", "text/html");
                request.response().end(directoryTemplate(context.vertx()).replace("{directory}", normalizedDir)
                        .replace("{parent}", parent).replace("{files}", files.toString()));
            } else if (accept.contains("json")) {
                String file;
                JsonArray json = new JsonArray();

                for (String s : asyncResult.result()) {
                    file = s.substring(s.lastIndexOf(File.separatorChar) + 1);
                    // skip dot files
                    if (!includeHidden && file.charAt(0) == '.') {
                        continue;
                    }
                    json.add(file);
                }
                request.response().putHeader("content-type", "application/json");
                request.response().end(json.encode());
            } else {
                String file;
                StringBuilder buffer = new StringBuilder();

                for (String s : asyncResult.result()) {
                    file = s.substring(s.lastIndexOf(File.separatorChar) + 1);
                    // skip dot files
                    if (!includeHidden && file.charAt(0) == '.') {
                        continue;
                    }
                    buffer.append(file);
                    buffer.append('\n');
                }

                request.response().putHeader("content-type", "text/plain");
                request.response().end(buffer.toString());
            }
        }
    });
}