org.takes.misc.Opt Java Examples

The following examples show how to use org.takes.misc.Opt. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PsGoogle.java    From takes with MIT License 6 votes vote down vote up
/**
 * Make identity from JSON object.
 * @param json JSON received from Google
 * @return Identity found
 */
private static Identity parse(final JsonObject json) {
    final Map<String, String> props = new HashMap<>(json.size());
    final Opt<JsonObject> image = new Opt.Single<>(
        json.getJsonObject("image")
    );
    if (image.has()) {
        props.put(PsGoogle.PICTURE, image.get().getString("url", "#"));
    } else {
        props.put(PsGoogle.PICTURE, "#");
    }
    props.put(
        PsGoogle.NAME, json.getString(PsGoogle.DISPLAY_NAME, "unknown")
    );
    return new Identity.Simple(
        String.format("urn:google:%s", json.getString("id")), props
    );
}
 
Example #2
Source File: PsBasicTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * PsBasic can handle connection with valid credential.
 * @throws Exception if any error occurs
 */
@Test
public void handleConnectionWithValidCredential() throws Exception {
    final String user = "john";
    final Opt<Identity> identity = new PsBasic(
        "RealmA",
        new PsBasic.Fake(true)
    ).enter(
        new RqWithHeaders(
            new RqFake(
                RqMethod.GET,
                String.format(
                    PsBasicTest.VALID_CODE,
                    RandomStringUtils.randomAlphanumeric(Tv.TEN)
                )
            ),
            PsBasicTest.header(user, "pass")
        )
    );
    MatcherAssert.assertThat(identity.has(), Matchers.is(true));
    MatcherAssert.assertThat(
        identity.get().urn(),
        CoreMatchers.equalTo(PsBasicTest.urn(user))
    );
}
 
Example #3
Source File: FkRegex.java    From takes with MIT License 6 votes vote down vote up
@Override
public Opt<Response> route(final Request req) throws Exception {
    String path = new RqHref.Base(req).href().path();
    if (
        this.removeslash
            && path.length() > 1
            && path.charAt(path.length() - 1) == '/'
    ) {
        path = path.substring(0, path.length() - 1);
    }
    final Matcher matcher = this.pattern.matcher(path);
    final Opt<Response> resp;
    if (matcher.matches()) {
        resp = new Opt.Single<>(
            this.target.get().act(
                new RqMatcher(matcher, req)
            )
        );
    } else {
        resp = new Opt.Empty<>();
    }
    return resp;
}
 
Example #4
Source File: TkFallbackTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * TkFallback can fall back.
 * @throws Exception If some problem inside
 */
@Test
public void fallsBack() throws Exception {
    final String err = "message";
    MatcherAssert.assertThat(
        new RsPrint(
            new TkFallback(
                new TkFailure(err),
                new Fallback() {
                    @Override
                    public Opt<Response> route(final RqFallback req) {
                        return new Opt.Single<Response>(
                            new RsText(req.throwable().getMessage())
                        );
                    }
                }
            ).act(new RqFake())
        ).printBody(),
        Matchers.endsWith(err)
    );
}
 
Example #5
Source File: RqLive.java    From takes with MIT License 6 votes vote down vote up
/**
 * Returns a legal character based n the read character.
 * @param data Character read
 * @param baos Byte stream containing read header
 * @param position Header line number
 * @return A legal character
 * @throws IOException if character is illegal
 */
private static Integer legalCharacter(final Opt<Integer> data,
    final ByteArrayOutputStream baos, final Integer position)
    throws IOException {
    // @checkstyle MagicNumber (1 line)
    if ((data.get() > 0x7f || data.get() < 0x20)
        && data.get() != '\t') {
        throw new HttpException(
            HttpURLConnection.HTTP_BAD_REQUEST,
            String.format(
                "illegal character 0x%02X in HTTP header line #%d: \"%s\"",
                data.get(),
                position,
                new TextOf(baos.toByteArray()).asString()
            )
        );
    }
    return data.get();
}
 
Example #6
Source File: RqLive.java    From takes with MIT License 6 votes vote down vote up
/**
 * Builds current read header.
 * @param data Current read character
 * @param baos Current read header
 * @return Read header
 */
private static Opt<String> newHeader(final Opt<Integer> data,
    final ByteArrayOutputStream baos) {
    Opt<String> header = new Opt.Empty<>();
    if (data.get() != ' ' && data.get() != '\t') {
        header = new Opt.Single<>(
            new UncheckedText(
                new TextOf(
                    baos.toByteArray()
                )
            ).asString()
        );
        baos.reset();
    }
    return header;
}
 
Example #7
Source File: RsWithType.java    From takes with MIT License 6 votes vote down vote up
/**
 * Factory allowing to create {@code Response} with the corresponding
 * content type and character set.
 * @param res Original response
 * @param type Content type
 * @param charset The character set to add to the content type header. If
 *  absent no character set will be added to the content type header
 * @return Response
 */
private static Response make(final Response res, final CharSequence type,
    final Opt<Charset> charset) {
    final Response response;
    if (charset.has()) {
        response = new RsWithHeader(
            new RsWithoutHeader(res, RsWithType.HEADER),
            RsWithType.HEADER,
            String.format(
                "%s; %s=%s",
                type,
                RsWithType.CHARSET,
                charset.get().name()
            )
        );
    } else {
        response = new RsWithHeader(
            new RsWithoutHeader(res, RsWithType.HEADER),
            RsWithType.HEADER,
            type
        );
    }
    return response;
}
 
Example #8
Source File: RsFork.java    From takes with MIT License 6 votes vote down vote up
/**
 * Pick the right one.
 * @param req Request
 * @param forks List of forks
 * @return Response
 * @throws IOException If fails
 */
@SuppressWarnings("PMD.AvoidCatchingGenericException")
private static Response pick(final Request req,
    final Iterable<Fork> forks) throws IOException {
    for (final Fork fork : forks) {
        try {
            final Opt<Response> rsps = fork.route(req);
            if (rsps.has()) {
                return rsps.get();
            }
            //@checkstyle IllegalCatch (1 line)
        } catch (final Exception ex) {
            throw new IOException(ex);
        }
    }
    throw new HttpException(HttpURLConnection.HTTP_NOT_FOUND);
}
 
Example #9
Source File: FbStatus.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param check HTTP status code predicate
 * @since 0.16.10
 */
public FbStatus(final Iterable<Integer> check) {
    this(check, new Fallback() {
        @Override
        public Opt<Response> route(final RqFallback req)
            throws Exception {
            final Response res = new RsWithStatus(req.code());
            return new Opt.Single<>(
                new RsWithType(
                    new RsWithBody(
                        res,
                        String.format(
                            "%s: %s", FbStatus.WHITESPACE.split(
                                res.head().iterator().next(),
                                2
                            )[1], req.throwable().getLocalizedMessage()
                        )
                    ), "text/plain"
                )
            );
        }
    });
}
 
Example #10
Source File: FbStatus.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param check Check
 * @param fallback Fallback
 */
@SuppressWarnings
    (
        {
            "PMD.CallSuperInConstructor",
            "PMD.ConstructorOnlyInitializesOrCallOtherConstructors"
        }
    )
public FbStatus(final Iterable<Integer> check,
    final Scalar<Fallback> fallback) {
    super(
        new Fallback() {
            @Override
            public Opt<Response> route(final RqFallback req)
                throws Exception {
                Opt<Response> rsp = new Opt.Empty<>();
                if (new ListOf<>(check).contains(req.code())) {
                    rsp = fallback.get().route(req);
                }
                return rsp;
            }
        }
    );
}
 
Example #11
Source File: FkHitRefresh.java    From takes with MIT License 6 votes vote down vote up
@Override
public Opt<Response> route(final Request req) throws Exception {
    final Iterator<String> header =
        new RqHeaders.Base(req).header("X-Takes-HitRefresh").iterator();
    final Opt<Response> resp;
    if (header.hasNext()) {
        if (this.handle.expired()) {
            this.exec.run();
            this.handle.touch();
        }
        resp = new Opt.Single<>(this.take.act(req));
    } else {
        resp = new Opt.Empty<>();
    }
    return resp;
}
 
Example #12
Source File: FkHitRefresh.java    From takes with MIT License 6 votes vote down vote up
/**
 * Directory contents updated?
 * @return TRUE if contents were updated
 */
private boolean directoryUpdated() {
    final long recent;
    try {
        this.lock.readLock().lock();
        recent = this.flag.get(0).lastModified();
    } finally {
        this.lock.readLock().unlock();
    }
    final File[] files = this.dir.listFiles();
    boolean expired = false;
    if (new Opt.Single<>(files).has()) {
        for (final File file : files) {
            if (file.lastModified() > recent) {
                expired = true;
                break;
            }
        }
    }
    return expired;
}
 
Example #13
Source File: PsBasic.java    From takes with MIT License 6 votes vote down vote up
@Override
public Opt<Identity> enter(final String user, final String pwd) {
    final Opt<String> urn = this.urn(user, pwd);
    final Opt<Identity> identity;
    if (urn.has()) {
        try {
            identity = new Opt.Single<>(
                new Identity.Simple(
                    URLDecoder.decode(
                        urn.get(), PsBasic.Default.ENCODING
                    )
                )
            );
        } catch (final UnsupportedEncodingException ex) {
            throw new IllegalStateException(ex);
        }
    } else {
        identity = new Opt.Empty<>();
    }
    return identity;
}
 
Example #14
Source File: PsByFlag.java    From takes with MIT License 6 votes vote down vote up
@Override
public Opt<Identity> enter(final Request req) throws Exception {
    final Iterator<String> flg = new RqHref.Base(req).href()
        .param(this.flag).iterator();
    Opt<Identity> user = new Opt.Empty<>();
    if (flg.hasNext()) {
        final String value = flg.next();
        for (final Map.Entry<Pattern, Pass> ent : this.passes.entrySet()) {
            if (ent.getKey().matcher(value).matches()) {
                user = ent.getValue().enter(req);
                break;
            }
        }
    }
    return user;
}
 
Example #15
Source File: PsCookie.java    From takes with MIT License 6 votes vote down vote up
@Override
public Opt<Identity> enter(final Request req) throws IOException {
    final Iterator<String> cookies = new RqCookies.Base(req)
        .cookie(this.cookie).iterator();
    Opt<Identity> user = new Opt.Empty<>();
    if (cookies.hasNext()) {
        user = new Opt.Single<>(
            this.codec.decode(
                new UncheckedBytes(
                    new BytesOf(cookies.next())
                ).asBytes()
            )
        );
    }
    return user;
}
 
Example #16
Source File: TakesApp.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(final String... args) throws IOException, SQLException {
    new FtBasic(
        new TkFallback(
            new TkFork(
                new FkRegex("/", new TakesHelloWorld()),
                new FkRegex("/index", new TakesIndex()),
                new FkRegex("/contact", new TakesContact())
                ),
            new FbChain(
                new FbStatus(404, new RsText("Page Not Found")),
                new FbStatus(405, new RsText("Method Not Allowed")),
                new Fallback() {
                    @Override
                    public Opt<Response> route(final RqFallback req) {
                        return new Opt.Single<Response>(new RsText(req.throwable().getMessage()));
                    }
                })
            ), 6060
        ).start(Exit.NEVER);
}
 
Example #17
Source File: FbEmpty.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 */
public FbEmpty() {
    super(
        new Fallback() {
            @Override
            public Opt<Response> route(final RqFallback req) {
                return new Opt.Empty<>();
            }
        }
    );
}
 
Example #18
Source File: PsBasicTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * PsBasic can handle connection with valid credential when Entry is
 * a instance of Default.
 * @throws Exception if any error occurs
 */
@Test
public void handleConnectionWithValidCredentialDefaultEntry()
    throws Exception {
    final String user = "johny";
    final String password = "password2";
    final Opt<Identity> identity = new PsBasic(
        "RealmAA",
        new PsBasic.Default(
            "mike my%20password1 urn:basic:michael",
            String.format("%s %s urn:basic:%s", user, password, user)
        )
    ).enter(
        new RqWithHeaders(
            new RqFake(
                RqMethod.GET,
                String.format(
                    PsBasicTest.VALID_CODE,
                    RandomStringUtils.randomAlphanumeric(Tv.TEN)
                )
            ),
            PsBasicTest.header(user, password)
        )
    );
    MatcherAssert.assertThat(identity.has(), Matchers.is(true));
    MatcherAssert.assertThat(
        identity.get().urn(),
        CoreMatchers.equalTo(PsBasicTest.urn(user))
    );
}
 
Example #19
Source File: FbLog4j.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 */
public FbLog4j() {
    super(
        new Fallback() {
            @Override
            public Opt<Response> route(final RqFallback req)
                throws IOException {
                FbLog4j.log(req);
                return new Opt.Empty<>();
            }
        }
    );
}
 
Example #20
Source File: FbFixed.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param take Take to use
 * @since 0.14
 */
public FbFixed(final Take take) {
    super(
        new Fallback() {
            @Override
            public Opt<Response> route(final RqFallback req)
                throws Exception {
                return new Opt.Single<>(take.act(req));
            }
        }
    );
}
 
Example #21
Source File: FbStatus.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param code HTTP status code
 * @param take Take
 */
public FbStatus(final int code, final Take take) {
    this(
        code,
        new Fallback() {
            @Override
            public Opt<Response> route(final RqFallback req)
                throws Exception {
                return new Opt.Single<>(take.act(req));
            }
        }
    );
}
 
Example #22
Source File: RqLive.java    From takes with MIT License 5 votes vote down vote up
/**
 * Parse input stream.
 * @param input Input stream
 * @return Request
 * @throws IOException If fails
 * @checkstyle ExecutableStatementCountCheck (100 lines)
 */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
private static Request parse(final InputStream input) throws IOException {
    boolean eof = true;
    final Collection<String> head = new LinkedList<>();
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Opt<Integer> data = new Opt.Empty<>();
    data = RqLive.data(input, data, false);
    while (data.get() > 0) {
        eof = false;
        if (data.get() == '\r') {
            RqLive.checkLineFeed(input, baos, head.size() + 1);
            if (baos.size() == 0) {
                break;
            }
            data = new Opt.Single<>(input.read());
            final Opt<String> header = RqLive.newHeader(data, baos);
            if (header.has()) {
                head.add(header.get());
            }
            data = RqLive.data(input, data, false);
            continue;
        }
        baos.write(RqLive.legalCharacter(data, baos, head.size() + 1));
        data = RqLive.data(input, new Opt.Empty<>(), true);
    }
    if (eof) {
        throw new IOException("empty request");
    }
    return new RequestOf(head, input);
}
 
Example #23
Source File: FbSlf4j.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 */
public FbSlf4j() {
    super(
        new Fallback() {
            @Override
            public Opt<Response> route(final RqFallback req)
                throws IOException {
                FbSlf4j.log(req);
                return new Opt.Empty<>();
            }
        }
    );
}
 
Example #24
Source File: FbChain.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param fallbacks Fallbacks
 */
@SuppressWarnings
    (
        {
            "PMD.CallSuperInConstructor",
            "PMD.ConstructorOnlyInitializesOrCallOtherConstructors"
        }
    )
public FbChain(final Iterable<Fallback> fallbacks) {
    super(
        new Fallback() {
            @Override
            public Opt<Response> route(final RqFallback req)
                throws Exception {
                Opt<Response> rsp = new Opt.Empty<>();
                for (final Fallback fbk : fallbacks) {
                    final Opt<Response> opt = fbk.route(req);
                    if (opt.has()) {
                        rsp = opt;
                        break;
                    }
                }
                return rsp;
            }
        }
    );
}
 
Example #25
Source File: PsBasic.java    From takes with MIT License 5 votes vote down vote up
@Override
public Opt<Identity> enter(final String usr, final String pwd) {
    final Opt<Identity> user;
    if (this.condition) {
        user = new Opt.Single<>(
            new Identity.Simple(
                String.format("urn:basic:%s", usr)
            )
        );
    } else {
        user = new Opt.Empty<>();
    }
    return user;
}
 
Example #26
Source File: PsBasicTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * PsBasic can handle multiple headers with valid credential.
 * @throws Exception If some problem inside
 */
@Test
public void handleMultipleHeadersWithValidCredential() throws Exception {
    final String user = "bill";
    final Opt<Identity> identity = new PsBasic(
        "RealmC",
        new PsBasic.Fake(true)
    ).enter(
        new RqWithHeaders(
            new RqFake(
                RqMethod.GET,
                String.format(
                    "?multiple_code=%s",
                    RandomStringUtils.randomAlphanumeric(Tv.TEN)
                )
            ),
            PsBasicTest.header(user, "changeit"),
            "Referer: http://teamed.io/",
            "Connection:keep-alive",
            "Content-Encoding:gzip",
            "X-Check-Cacheable:YES",
            "X-Powered-By:Java/1.7"
        )
    );
    MatcherAssert.assertThat(identity.has(), Matchers.is(true));
    MatcherAssert.assertThat(
        identity.get().urn(),
        CoreMatchers.equalTo(PsBasicTest.urn(user))
    );
}
 
Example #27
Source File: PsFake.java    From takes with MIT License 5 votes vote down vote up
@Override
public Opt<Identity> enter(final Request request) {
    final Opt<Identity> user;
    if (this.condition) {
        user = new Opt.Single<>(
            new Identity.Simple("urn:test:1")
        );
    } else {
        user = new Opt.Empty<>();
    }
    return user;
}
 
Example #28
Source File: TkAppFallback.java    From jare with MIT License 5 votes vote down vote up
/**
 * Authenticated.
 * @param take Takes
 * @return Authenticated takes
 */
private static Take make(final Take take) {
    return new TkFallback(
        take,
        new FbChain(
            new FbStatus(
                HttpURLConnection.HTTP_NOT_FOUND,
                new RsWithStatus(
                    new RsText("Page not found"),
                    HttpURLConnection.HTTP_NOT_FOUND
                )
            ),
            new FbStatus(
                HttpURLConnection.HTTP_BAD_REQUEST,
                new RsWithStatus(
                    new RsText("Bad request"),
                    HttpURLConnection.HTTP_BAD_REQUEST
                )
            ),
            req -> {
                Sentry.capture(req.throwable());
                return new Opt.Empty<>();
            },
            req -> new Opt.Single<>(TkAppFallback.fatal(req))
        )
    );
}
 
Example #29
Source File: PsGoogle.java    From takes with MIT License 5 votes vote down vote up
@Override
public Opt<Identity> enter(final Request request)
    throws IOException {
    final Href href = new RqHref.Base(request).href();
    final Iterator<String> code = href.param(PsGoogle.CODE).iterator();
    if (!code.hasNext()) {
        throw new HttpException(
            HttpURLConnection.HTTP_BAD_REQUEST,
            "code is not provided by Google, probably some mistake"
        );
    }
    return new Opt.Single<>(this.fetch(this.token(code.next())));
}
 
Example #30
Source File: PsGithub.java    From takes with MIT License 5 votes vote down vote up
@Override
public Opt<Identity> enter(final Request request)
    throws IOException {
    final Href href = new RqHref.Base(request).href();
    final Iterator<String> code = href.param(PsGithub.CODE).iterator();
    if (!code.hasNext()) {
        throw new HttpException(
            HttpURLConnection.HTTP_BAD_REQUEST,
            "code is not provided by Github"
        );
    }
    return new Opt.Single<>(
        this.fetch(this.token(href.toString(), code.next()))
    );
}