Example usage for io.vertx.core Future failedFuture

List of usage examples for io.vertx.core Future failedFuture

Introduction

In this page you can find the example usage for io.vertx.core Future failedFuture.

Prototype

static <T> Future<T> failedFuture(String failureMessage) 

Source Link

Document

Create a failed future with the specified failure message.

Usage

From source file:net.kuujo.vertigo.util.CountingCompletionHandler.java

License:Apache License

/**
 * Checks whether the handler should be called.
 */// w  w  w  .  j ava 2 s .  c  o  m
private void checkDone() {
    if (doneHandler != null) {
        if (cause != null) {
            doneHandler.handle(Future.failedFuture(cause));
        } else {
            if (count == required) {
                doneHandler.handle(Future.succeededFuture());
            }
        }
    }
}

From source file:net.kuujo.vertigo.util.IncrementalCompletionHandler.java

License:Apache License

/**
 * Checks whether the handler should be called.
 *//*from  w  ww . jav a2 s .  c om*/
protected void checkDone() {
    if (failed && doneHandler != null) {
        doneHandler.handle(Future.failedFuture(cause));
        doneHandler = null;
    } else if (complete && count == required) {
        doneHandler.handle(Future.succeededFuture());
        doneHandler = null;
    }
}

From source file:org.dfr.dfr.worker.MemberWorker.java

@Override
public void start(Future<Void> fut) {
    JsonObject config = new JsonObject();
    config.put("url", "jdbc:mysql://localhost:3306/latihan");
    config.put("driver_class", "com.mysql.jdbc.Driver");
    config.put("user", "root");
    config.put("password", "admin");
    JDBCClient client = JDBCClient.createShared(vertx, config, "memberds");
    final Validator v = Validation.buildDefaultValidatorFactory().getValidator();
    SimpleDateFormat mysqlFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    vertx.eventBus().consumer("MemberWorker#Register").handler(h -> {
        MemberRegisterRequest req = null;
        try {/*from  w  w w . ja  v a 2s  .  co  m*/
            req = Json.decodeValue(h.body().toString(), MemberRegisterRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }
        Set<ConstraintViolation<MemberRegisterRequest>> vr = v.validate(req);
        if (!vr.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)
                    .setMessage(vr.iterator().next().getMessage())));
            return;
        }
        final MemberRegisterRequest r = req;
        final HashMap<String, Object> smap = new HashMap();

        client.getConnection(ch -> {
            if (ch.succeeded()) {
                SQLConnection c = ch.result();
                Future<Void> f1 = Future.future();
                c.setAutoCommit(false, f1.completer());
                f1.compose(o -> {
                    Future<ResultSet> f2 = Future.future();
                    c.queryWithParams("select username from member where username=?",
                            new JsonArray().add(r.getUsername()), f2.completer());
                    return f2;
                }).compose(res -> {
                    Future<ResultSet> f2 = Future.future();
                    if (res.getNumRows() != 0) {
                        f2.fail(ErrorCode.USER_EXIST);
                    } else {
                        c.queryWithParams("select email from member where email=?",
                                new JsonArray().add(r.getEmail()), f2.completer());
                    }
                    return f2;
                }).compose(res -> {
                    if (res.getNumRows() > 0) {
                        return Future.failedFuture(ErrorCode.EMAIL_EXIST);
                    } else {
                        try {
                            r.setPassword(hash(r.getPassword()));
                        } catch (Exception e) {
                            return Future.failedFuture(ErrorCode.SERVER_ERROR);
                        }
                        Future<UpdateResult> f2 = Future.future();
                        c.updateWithParams("insert into member(username,password,email) values (?,?,?)",
                                new JsonArray().add(r.getUsername()).add(r.getPassword()).add(r.getEmail()),
                                f2.completer());
                        return f2;
                    }
                }).compose(res -> {
                    Future<UpdateResult> f2 = Future.future();
                    c.updateWithParams("insert into profile(member_id) values(?)",
                            new JsonArray().add(res.getKeys().getLong(0)), f2.completer());
                    return f2;
                }).compose(res -> {
                    Future<Void> cfut = Future.future();
                    c.commit(cfut.completer());
                    return cfut;
                }).setHandler(ch1 -> {
                    if (ch1.succeeded()) {
                        c.close(close -> {
                            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE)));
                        });
                    } else {
                        c.rollback(rr -> {
                            c.close(close -> {
                                h.reply(Json.encode(new GeneralResponse().setCode(ch1.cause().getMessage())
                                        .setMessage(ErrorCode.getMessage(ch1.cause().getMessage()))));
                            });
                        });
                    }
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)
                        .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR))));
            }
        });
    });

    vertx.eventBus().consumer("MemberWorker#ProfileUpdate").handler(h -> {
        ProfileUpdateRequest req = null;
        try {
            req = Json.decodeValue(h.body().toString(), ProfileUpdateRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }
        Set<ConstraintViolation<ProfileUpdateRequest>> vr = v.validate(req);
        if (!vr.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)
                    .setMessage(vr.iterator().next().getMessage())));
            return;
        }

        ProfileUpdateRequest rq = req;

        client.getConnection(connection -> {
            if (connection.succeeded()) {
                HashMap<String, Object> sm = new HashMap<String, Object>();
                SQLConnection con = connection.result();
                Future<Void> ac = Future.future();
                con.setAutoCommit(false, ac.completer());
                ac.compose(rv -> {
                    Future<ResultSet> lock = Future.future();
                    con.queryWithParams(
                            "select p.* from profile p inner join member m on p.member_id=m.member_id where m.username=? and m.password=? for update",
                            new JsonArray().add(rq.getUsername()).add(rq.getPassword()), lock.completer());
                    return lock;
                }).compose(r -> {
                    if (r.getNumRows() == 0) {
                        return Future.failedFuture(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
                    }
                    long member_id = r.getRows().iterator().next().getLong("member_id");
                    Future<UpdateResult> up = Future.future();
                    con.updateWithParams(
                            "update profile set name=?, phone=?, address=?, company_name=?, company_address=? where member_id=?",
                            new JsonArray().add(rq.getName()).add(rq.getPhone()).add(rq.getAddress())
                                    .add(rq.getCompanyName()).add(rq.getCompanyAddress()).add(member_id),
                            up.completer());
                    return up;
                }).compose(ok -> {
                    Future<Void> commitFu = Future.future();
                    con.commit(commitFu.completer());
                    return commitFu;
                }).setHandler(th -> {
                    if (th.succeeded()) {
                        con.close(cr -> {
                            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE)));
                        });
                    } else {
                        con.rollback(rh -> {
                            con.close(cl -> {
                                h.reply(Json.encode(new GeneralResponse().setCode(th.cause().getMessage())
                                        .setMessage(ErrorCode.getMessage(th.cause().getMessage()))));
                            });
                        });
                    }
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)
                        .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR))));
            }
        });
    });

    vertx.eventBus().consumer("MemberWorker#GetProfile").handler(h -> {
        ProfileRequest req = null;
        try {
            req = Json.decodeValue(h.body().toString(), ProfileRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }

        Set<ConstraintViolation<ProfileRequest>> rV = v.validate(req);

        if (!rV.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }

        final ProfileRequest r = req;

        client.getConnection(cH -> {
            if (cH.succeeded()) {
                SQLConnection c = cH.result();
                Future<Void> f = Future.future();
                c.setAutoCommit(true, f.completer());
                f.compose(res -> {
                    Future<ResultSet> f0 = Future.future();
                    c.queryWithParams("select member_id from member m where m.username=? and m.password=?",
                            new JsonArray().add(r.getUsername()).add(r.getPassword()), f0.completer());
                    return f0;
                }).compose(res -> {
                    Future<ResultSet> f0 = Future.future();
                    if (res.getNumRows() <= 0) {
                        f0.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
                    } else {
                        c.queryWithParams("select * from profile where member_id=?",
                                new JsonArray().add(res.getRows().iterator().next().getLong("member_id")),
                                f0.completer());
                    }
                    return f0;
                }).setHandler(rh -> {
                    c.close();
                    if (rh.succeeded()) {
                        h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE)
                                .setData(rh.result().getRows().get(0))));
                    } else {
                        h.reply(Json.encode(new GeneralResponse().setCode(rh.cause().getMessage())
                                .setMessage(ErrorCode.getMessage(rh.cause().getMessage()))));
                    }
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)
                        .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR))));
            }
        });
    });

    vertx.eventBus().consumer("MemberWorker#ChangePassword").handler(h -> {
        ChangePasswordRequest req = null;
        try {
            req = Json.decodeValue(h.body().toString(), ChangePasswordRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }
        Set<ConstraintViolation<ChangePasswordRequest>> rV = v.validate(req);
        if (!rV.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }
        final ChangePasswordRequest r = req;

        client.getConnection(connection -> {
            if (connection.succeeded()) {
                SQLConnection c = connection.result();
                Future<Void> f1 = Future.future();
                c.setAutoCommit(false, f1.completer());
                f1.compose(vo -> {
                    Future<ResultSet> f = Future.future();
                    c.queryWithParams("select member_id from member where username=? and password=? for update",
                            new JsonArray().add(r.getUsername()).add(r.getPassword()), f.completer());
                    return f;
                }).compose(res -> {
                    Future<UpdateResult> f0 = Future.future();
                    if (res.getNumRows() <= 0) {
                        f0.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
                    } else {
                        long member_id = res.getRows().iterator().next().getLong("member_id");
                        String hash = null;
                        try {
                            hash = hash(r.getNewPassword());
                        } catch (Exception e) {
                            return Future.failedFuture(ErrorCode.SERVER_ERROR);
                        }
                        c.updateWithParams("update member set password=? where member_id=?",
                                new JsonArray().add(hash).add(member_id), f0.completer());
                    }
                    return f0;
                }).compose(res -> {
                    Future<Void> cf = Future.future();
                    c.commit(cf.completer());
                    return cf;
                }).setHandler(ch -> {
                    if (ch.succeeded()) {
                        c.close();
                        h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE)));
                    } else {
                        ch.cause().printStackTrace();
                        c.rollback(rh -> {
                            c.close();
                            h.reply(Json.encode(new GeneralResponse().setCode(ch.cause().getMessage())
                                    .setMessage(ErrorCode.getMessage(ch.cause().getMessage()))));
                        });
                    }
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)
                        .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR))));
            }
        });
    });

    vertx.eventBus().consumer("MembrWorker#AddAsset").handler(h -> {
        AddAssetRequest req = null;
        try {
            req = Json.decodeValue(h.body().toString(), AddAssetRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }
        Set<ConstraintViolation<AddAssetRequest>> res = v.validate(req);
        if (!res.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)
                    .setMessage(res.iterator().next().getMessage())));
            return;
        }

        AddAssetRequest r = req;

        client.getConnection(connection -> {
            if (connection.succeeded()) {
                SQLConnection con = connection.result();
                Future<Void> f = Future.future();
                con.setAutoCommit(false, f.completer());
                f.compose(vo -> {
                    Future<ResultSet> f1 = Future.future();
                    con.queryWithParams("select * from member where username=? and password=?",
                            new JsonArray().add(r.getUsername()).add(r.getPassword()), f1.completer());
                    return f1;
                }).compose(re -> {
                    Future<UpdateResult> f1 = Future.future();
                    if (re.getNumRows() <= 0) {
                        System.out.println(Json.encode(re));
                        System.out.println(Json.encode(r));
                        f1.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
                    } else {
                        long member_id = re.getRows().iterator().next().getLong("member_id");
                        con.updateWithParams(
                                "insert into assets (member_id,debit_credit,asset_name,asset_value,date_time,description) values(?,?,?,?,?,?)",
                                new JsonArray().add(member_id).add(r.getDebitCredit()).add(r.getAssetName())
                                        .add(r.getAssetValue()).add(mysqlFormat.format(new Date()))
                                        .add(r.getDescription()),
                                f1.completer());
                    }
                    return f1;
                }).compose(re -> {
                    Future<Void> end = Future.future();
                    con.commit(end.completer());
                    return end;
                }).setHandler(ch -> {
                    if (ch.succeeded()) {
                        con.close();
                        h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE)));
                    } else {
                        con.rollback(rh -> {
                            con.close();
                            h.reply(Json.encode(new GeneralResponse().setCode(ch.cause().getMessage())
                                    .setMessage(ErrorCode.getMessage(ch.cause().getMessage()))));
                        });
                    }
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)
                        .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR))));
            }
        });
    });

    vertx.eventBus().consumer("AssetWorker#GetAsset").handler(h -> {

        GetAssetRequest req = null;
        try {
            req = Json.decodeValue(h.body().toString(), GetAssetRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }
        Set<ConstraintViolation<GetAssetRequest>> res = v.validate(req);
        if (!res.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)
                    .setMessage(res.iterator().next().getMessage())));
            return;
        }

        GetAssetRequest r = req;

        client.getConnection(connection -> {
            if (connection.succeeded()) {
                SQLConnection c = connection.result();
                Future<Void> vo = Future.future();
                c.setAutoCommit(true, vo.completer());
                vo.compose(re -> {
                    Future<ResultSet> f0 = Future.future();
                    c.queryWithParams("select member_id from member where username=? and password=?",
                            new JsonArray().add(r.getUsername()).add(r.getPassword()), f0.completer());
                    return f0;
                }).compose(re -> {
                    Future<ResultSet> f0 = Future.future();
                    if (re.getNumRows() <= 0) {
                        f0.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
                    } else {
                        long member_id = re.getRows().iterator().next().getLong("member_id");
                        c.queryWithParams("select * from assets where member_id=?",
                                new JsonArray().add(member_id), f0.completer());
                    }
                    return f0;
                }).setHandler(resp -> {
                    if (resp.succeeded()) {
                        h.reply(Json.encodePrettily(new GeneralResponse().setCode(ErrorCode.COMPLETE)
                                .setData(resp.result().getRows())));
                    } else {
                        h.reply(Json.encode(new GeneralResponse().setCode(resp.cause().getMessage())
                                .setMessage(ErrorCode.getMessage(resp.cause().getMessage()))));
                    }
                    c.close();
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)
                        .setMessage(connection.cause().getMessage())));
            }
        });
    });

    vertx.eventBus().consumer("AssetWorker#UpdateAsset").handler(h -> {

        UpdateAssetRequest req = null;
        try {
            req = Json.decodeValue(h.body().toString(), UpdateAssetRequest.class);
        } catch (Exception e) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)));
            return;
        }

        Set<ConstraintViolation<UpdateAssetRequest>> res = v.validate(req);

        if (!res.isEmpty()) {
            h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON)
                    .setMessage(res.iterator().next().getMessage())));
            return;
        }

        final UpdateAssetRequest r = req;

        client.getConnection(connection -> {
            if (connection.succeeded()) {
                SQLConnection con = connection.result();
                Future<Void> f = Future.future();
                con.setAutoCommit(false, f.completer());
                f.compose(vo -> {
                    Future<ResultSet> f0 = Future.future();
                    con.queryWithParams("select member_id from member where username=? and password=?",
                            new JsonArray().add(r.getUsername()).add(r.getPassword()), f0.completer());
                    return f0;
                }).compose(rs -> {
                    Future<ResultSet> f0 = Future.future();
                    if (rs.getNumRows() <= 0) {
                        f0.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
                    } else {
                        long member_id = rs.getRows().iterator().next().getLong("member_id");
                        con.queryWithParams("select * from assets where asset_id=? and member_id=? for update",
                                new JsonArray().add(r.getAssetId()).add(member_id), f0.completer());
                    }
                    return f0;
                }).compose(rs -> {
                    Future<UpdateResult> f0 = Future.future();
                    con.updateWithParams(
                            "update assets set debit_credit=?,asset_name=?,asset_value=?,date_time=?,description=? where asset_id=?",
                            new JsonArray().add(r.getDebitCredit()).add(r.getAssetName()).add(r.getAssetValue())
                                    .add(mysqlFormat.format(new Date())).add(r.getDescription())
                                    .add(r.getAssetId()),
                            f0.completer());
                    return f0;
                }).compose(rs -> {
                    Future<Void> cf = Future.future();
                    con.commit(cf.completer());
                    return cf;
                }).setHandler(sh -> {
                    if (sh.succeeded()) {
                        con.close();
                        h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE)));
                    } else {
                        con.rollback(rh -> {
                            con.close();
                            h.reply(Json.encode(new GeneralResponse().setCode(sh.cause().getMessage())
                                    .setMessage(ErrorCode.getMessage(sh.cause().getMessage()))));
                        });
                    }
                });
            } else {
                h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR)));
            }
        });
    });

    fut.complete();
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

License:Open Source License

@Override
public final void doStart(final Future<Void> startFuture) {

    checkPortConfiguration().compose(s -> preStartup()).compose(s -> {
        Router router = createRouter();//from  ww  w .j a  va  2s.co  m
        if (router == null) {
            return Future.failedFuture("no router configured");
        } else {
            addRoutes(router);
            return CompositeFuture.all(bindSecureHttpServer(router), bindInsecureHttpServer(router));
        }
    }).compose(s -> {
        connectToMessaging(null);
        connectToDeviceRegistration(null);
        connectToCredentialsService(null);
        try {
            onStartupSuccess();
            startFuture.complete();
        } catch (Exception e) {
            LOG.error("error in onStartupSuccess", e);
            startFuture.fail(e);
        }
    }, startFuture);
}

From source file:org.eclipse.hono.adapter.http.HonoAuthHandlerImpl.java

License:Open Source License

@Override
public void authorize(User user, Handler<AsyncResult<Void>> handler) {
    int requiredcount = authorities.size();
    if (requiredcount > 0) {
        if (user == null) {
            handler.handle(Future.failedFuture(FORBIDDEN));
            return;
        }//from  w  w  w. ja  v a  2  s  .c om

        AtomicInteger count = new AtomicInteger();
        AtomicBoolean sentFailure = new AtomicBoolean();

        Handler<AsyncResult<Boolean>> authHandler = res -> {
            if (res.succeeded()) {
                if (res.result()) {
                    if (count.incrementAndGet() == requiredcount) {
                        // Has all required authorities
                        handler.handle(Future.succeededFuture());
                    }
                } else {
                    if (sentFailure.compareAndSet(false, true)) {
                        handler.handle(Future.failedFuture(FORBIDDEN));
                    }
                }
            } else {
                handler.handle(Future.failedFuture(res.cause()));
            }
        };
        for (String authority : authorities) {
            if (!sentFailure.get()) {
                user.isAuthorized(authority, authHandler);
            }
        }
    } else {
        // No auth required
        handler.handle(Future.succeededFuture());
    }
}

From source file:org.eclipse.hono.adapter.http.HonoAuthHandlerImpl.java

License:Open Source License

@Override
public void parseCredentials(RoutingContext context, Handler<AsyncResult<JsonObject>> handler) {

    parseAuthorization(context, false, parseAuthorization -> {
        if (parseAuthorization.failed()) {
            handler.handle(Future.failedFuture(parseAuthorization.cause()));
            return;
        }//ww  w.  j a  v  a  2  s . co m

        final String suser;
        final String spass;

        try {
            // decode the payload
            String decoded = new String(Base64.getDecoder().decode(parseAuthorization.result()));

            int colonIdx = decoded.indexOf(":");
            if (colonIdx != -1) {
                suser = decoded.substring(0, colonIdx);
                spass = decoded.substring(colonIdx + 1);
            } else {
                suser = decoded;
                spass = null;
            }
        } catch (RuntimeException e) {
            // IllegalArgumentException includes PatternSyntaxException
            context.fail(e);
            return;
        }

        handler.handle(Future.succeededFuture(new JsonObject().put("username", suser).put("password", spass)));
    });
}

From source file:org.eclipse.hono.adapter.http.HonoAuthHandlerImpl.java

License:Open Source License

protected final void parseAuthorization(RoutingContext ctx, boolean optional,
        Handler<AsyncResult<String>> handler) {

    final HttpServerRequest request = ctx.request();
    final String authorization = request.headers().get(HttpHeaders.AUTHORIZATION);

    if (authorization == null) {
        if (optional) {
            // this is allowed
            handler.handle(Future.succeededFuture());
        } else {/*from w  w  w  .j a v a 2 s  .c om*/
            handler.handle(Future.failedFuture(UNAUTHORIZED));
        }
        return;
    }

    try {
        int idx = authorization.indexOf(' ');

        if (idx <= 0) {
            handler.handle(Future.failedFuture(BAD_REQUEST));
            return;
        }

        if (!type.is(authorization.substring(0, idx))) {
            handler.handle(Future.failedFuture(UNAUTHORIZED));
            return;
        }

        handler.handle(Future.succeededFuture(authorization.substring(idx + 1)));
    } catch (RuntimeException e) {
        handler.handle(Future.failedFuture(e));
    }
}

From source file:org.eclipse.hono.adapter.http.HonoBasicAuthHandler.java

License:Open Source License

@Override
public void parseCredentials(final RoutingContext context, final Handler<AsyncResult<JsonObject>> handler) {

    parseAuthorization(context, false, parseAuthorization -> {
        if (parseAuthorization.failed()) {
            handler.handle(Future.failedFuture(parseAuthorization.cause()));
            return;
        }//from   w  w w  .  j  a v  a2s .  com

        final String suser;
        final String spass;

        try {
            // decode the payload
            final String decoded = new String(Base64.getDecoder().decode(parseAuthorization.result()));

            final int colonIdx = decoded.indexOf(":");
            if (colonIdx != -1) {
                suser = decoded.substring(0, colonIdx);
                spass = decoded.substring(colonIdx + 1);
            } else {
                suser = decoded;
                spass = null;
            }
        } catch (RuntimeException e) {
            // IllegalArgumentException includes PatternSyntaxException
            context.fail(e);
            return;
        }

        handler.handle(Future.succeededFuture(new JsonObject().put("username", suser).put("password", spass)));
    });
}

From source file:org.eclipse.hono.adapter.http.HonoBasicAuthHandler.java

License:Open Source License

/**
 * Extracts authentication information from the <em>Authorization</em>
 * header of an HTTP request./* w  ww  .j av  a  2  s  .  c  om*/
 * 
 * @param ctx The routing context that contains the HTTP request.
 * @param optional Indicates whether the authorization header is mandatory.
 * @param handler The handler to invoke with the authentication info.
 */
protected final void parseAuthorization(final RoutingContext ctx, final boolean optional,
        final Handler<AsyncResult<String>> handler) {

    final HttpServerRequest request = ctx.request();
    final String authorization = request.headers().get(HttpHeaders.AUTHORIZATION);

    if (authorization == null) {
        if (optional) {
            // this is allowed
            handler.handle(Future.succeededFuture());
        } else {
            handler.handle(Future.failedFuture(UNAUTHORIZED));
        }
        return;
    }

    try {
        final int idx = authorization.indexOf(' ');

        if (idx <= 0) {
            handler.handle(Future.failedFuture(BAD_REQUEST));
            return;
        }

        if (!"Basic".equalsIgnoreCase(authorization.substring(0, idx))) {
            handler.handle(Future.failedFuture(UNAUTHORIZED));
            return;
        }

        handler.handle(Future.succeededFuture(authorization.substring(idx + 1)));
    } catch (RuntimeException e) {
        handler.handle(Future.failedFuture(e));
    }
}

From source file:org.eclipse.hono.adapter.http.X509AuthHandler.java

License:Open Source License

@Override
public final void parseCredentials(final RoutingContext context,
        final Handler<AsyncResult<JsonObject>> handler) {

    Objects.requireNonNull(context);
    Objects.requireNonNull(handler);

    if (context.request().isSSL()) {
        try {/*from  w  w w  . j  a v a 2 s .  c  o  m*/
            final Certificate[] clientChain = context.request().sslSession().getPeerCertificates();
            getX509CertificateChain(clientChain).compose(x509chain -> {
                return getTenant(x509chain[0]).compose(tenant -> getCredentials(x509chain, tenant));
            }).setHandler(handler);
        } catch (SSLPeerUnverifiedException e) {
            // client certificate has not been validated
            handler.handle(Future.failedFuture(UNAUTHORIZED));
        }
    } else {
        handler.handle(Future.failedFuture(UNAUTHORIZED));
    }
}