Java Code Examples for org.takes.misc.Opt#Single

The following examples show how to use org.takes.misc.Opt#Single . 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: 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 2
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 3
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 4
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 5
Source File: FkAuthenticated.java    From takes with MIT License 5 votes vote down vote up
@Override
public Opt<Response> route(final Request req) throws Exception {
    final Identity identity = new RqAuth(req).identity();
    final Opt<Response> resp;
    if (identity.equals(Identity.ANONYMOUS)) {
        resp = new Opt.Empty<>();
    } else {
        resp = new Opt.Single<>(this.take.get().act(req));
    }
    return resp;
}
 
Example 6
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 7
Source File: PsLinkedin.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(PsLinkedin.CODE).iterator();
    if (!code.hasNext()) {
        throw new HttpException(
            HttpURLConnection.HTTP_BAD_REQUEST,
            "code is not provided by LinkedIn"
        );
    }
    return new Opt.Single<>(
        this.fetch(this.token(href.toString(), code.next()))
    );
}
 
Example 8
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 9
Source File: FkContentType.java    From takes with MIT License 5 votes vote down vote up
@Override
public Opt<Response> route(final Request req) throws Exception {
    final Opt<Response> resp;
    if (FkContentType.getType(req).contains(this.type)) {
        resp = new Opt.Single<>(this.take.act(req));
    } else {
        resp = new Opt.Empty<>();
    }
    return resp;
}
 
Example 10
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 11
Source File: FkAnonymous.java    From takes with MIT License 5 votes vote down vote up
@Override
public Opt<Response> route(final Request req) throws Exception {
    final Identity identity = new RqAuth(req).identity();
    final Opt<Response> resp;
    if (identity.equals(Identity.ANONYMOUS)) {
        resp = new Opt.Single<>(this.take.get().act(req));
    } else {
        resp = new Opt.Empty<>();
    }
    return resp;
}
 
Example 12
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 13
Source File: FkTypes.java    From takes with MIT License 5 votes vote down vote up
@Override
public Opt<Response> route(final Request req) throws Exception {
    final Opt<Response> resp;
    if (FkTypes.accepted(req).contains(this.types)) {
        if (this.response.has()) {
            resp = new Opt.Single<>(this.response.get());
        } else {
            resp = new Opt.Single<>(this.take.get().act(req));
        }
    } else {
        resp = new Opt.Empty<>();
    }
    return resp;
}
 
Example 14
Source File: TkApp.java    From jpeek with MIT License 4 votes vote down vote up
/**
 * Ctor.
 * @param home Home directory
 * @return The take
 * @throws IOException If fails
 */
private static Take make(final Path home) throws IOException {
    final Futures futures = new Futures(
        new Reports(home)
    );
    final BiFunc<String, String, Func<String, Response>> reports =
        new AsyncReports(
            // @checkstyle MagicNumber (1 line)
            new StickyFutures(futures, 100)
        );
    return new TkSslOnly(
        new TkFallback(
            new TkForward(
                new TkFork(
                    new FkRegex("/", new TkIndex()),
                    new FkRegex("/robots.txt", new TkText("")),
                    new FkRegex("/mistakes", new TkMistakes()),
                    new FkRegex(
                        "/flush",
                        (Take) req -> new RsText(
                            String.format("%d flushed", new Results().flush())
                        )
                    ),
                    new FkRegex(
                        "/upload",
                        (Take) req -> new RsPage(req, "upload")
                    ),
                    new FkRegex("/do-upload", new TkUpload(reports)),
                    new FkRegex("/all", new TkAll()),
                    new FkRegex("/queue", new TkQueue(futures)),
                    new FkRegex(
                        ".+\\.xsl",
                        new TkWithType(
                            new TkClasspath(),
                            "text/xsl"
                        )
                    ),
                    new FkRegex(
                        "/jpeek\\.css",
                        new TkWithType(
                            new TkText(
                                new TextOf(
                                    new ResourceOf("org/jpeek/jpeek.css")
                                ).asString()
                            ),
                            "text/css"
                        )
                    ),
                    new FkRegex(
                        "/([^/]+)/([^/]+)(.*)",
                        new TkReport(reports, new Results())
                    )
                )
            ),
            new FbChain(
                new FbStatus(
                    HttpURLConnection.HTTP_NOT_FOUND,
                    (Fallback) req -> new Opt.Single<>(
                        new RsWithStatus(
                            new RsText(req.throwable().getMessage()),
                            req.code()
                        )
                    )
                ),
                req -> {
                    Sentry.capture(req.throwable());
                    return new Opt.Single<>(
                        new RsWithStatus(
                            new RsText(
                                new TextOf(req.throwable()).asString()
                            ),
                            HttpURLConnection.HTTP_INTERNAL_ERROR
                        )
                    );
                }
            )
        )
    );
}
 
Example 15
Source File: PsLogout.java    From takes with MIT License 4 votes vote down vote up
@Override
public Opt<Identity> enter(final Request request) {
    return new Opt.Single<>(Identity.ANONYMOUS);
}
 
Example 16
Source File: PsToken.java    From takes with MIT License 4 votes vote down vote up
@Override
public Opt<Identity> enter(final Request req) throws IOException {
    // @checkstyle ExecutableStatementCount (100 lines)
    Opt<Identity> user = new Opt.Empty<>();
    final UncheckedText head = new Unchecked<>(
        new FirstOf<>(
            text -> new StartsWith(
                new Trimmed(text),
                new TextOf("Bearer")
            ).value(),
            new Mapped<>(
                UncheckedText::new,
                new RqHeaders.Base(req).header(this.header)
            ),
            new Constant<>(new UncheckedText(""))
        )
    ).value();
    if (new Unchecked<>(new Not(new IsBlank(head))).value()) {
        final String jwt = new UncheckedText(
            new Trimmed(new TextOf(head.asString().split(" ", 2)[1]))
        ).asString();
        final String[] parts = jwt.split("\\.");
        final byte[] jwtheader = parts[0].getBytes(
            Charset.defaultCharset()
        );
        final byte[] jwtpayload = parts[1].getBytes(
            Charset.defaultCharset()
        );
        final byte[] jwtsign = parts[2].getBytes(Charset.defaultCharset());
        final ByteBuffer tocheck = ByteBuffer.allocate(
            jwtheader.length + jwtpayload.length + 1
        );
        tocheck.put(jwtheader).put(".".getBytes(Charset.defaultCharset()))
            .put(jwtpayload);
        final byte[] checked = this.signature.sign(tocheck.array());
        if (Arrays.equals(jwtsign, checked)) {
            try (JsonReader rdr = Json.createReader(
                new StringReader(
                    new String(
                        Base64.getDecoder().decode(jwtpayload),
                        Charset.defaultCharset()
                    )
                )
            )) {
                user = new Opt.Single<>(
                    new Identity.Simple(
                        rdr.readObject().getString(Token.Jwt.SUBJECT)
                    )
                );
            }
        }
    }
    return user;
}
 
Example 17
Source File: PsTwitter.java    From takes with MIT License 4 votes vote down vote up
@Override
public Opt<Identity> enter(final Request request)
    throws IOException {
    return new Opt.Single<>(this.identity(this.fetch()));
}
 
Example 18
Source File: RsWithType.java    From takes with MIT License 2 votes vote down vote up
/**
 * Constructs a {@code HTML} that will add text/html as the content type
 * header to the response using the specified charset as charset
 * parameter value.
 * @param res Original response
 * @param charset The character set to add in the content type header
 */
public Html(final Response res, final Charset charset) {
    this(res, new Opt.Single<>(charset));
}
 
Example 19
Source File: RsWithType.java    From takes with MIT License 2 votes vote down vote up
/**
 * Constructs a {@code RsWithType} that will add the content type header to
 * the response using the specified type as media type and the specified
 * charset as charset parameter value.
 * <p>The resulting header
 * is of type {@code Content-Type: media-type; charset=charset-value}.
 * @param res Original response
 * @param type Content type
 * @param charset The character set to add in the content type header
 */
public RsWithType(final Response res, final CharSequence type,
    final Charset charset) {
    this(res, type, new Opt.Single<>(charset));
}
 
Example 20
Source File: RsWithType.java    From takes with MIT License 2 votes vote down vote up
/**
 * Constructs a {@code JSON} that will add application/json as the
 * content type header to the response using the specified charset as
 * charset parameter value.
 * @param res Original response
 * @param charset The character set to add in the content type header
 */
public Json(final Response res, final Charset charset) {
    this(res, new Opt.Single<>(charset));
}