org.cactoos.io.BytesOf Java Examples

The following examples show how to use org.cactoos.io.BytesOf. 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: HtHeadTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void largeText() throws Exception {
    //@checkstyle MagicNumberCheck (1 lines)
    final byte[] bytes = new byte[18000];
    new Random().nextBytes(bytes);
    new Assertion<>(
        "Header does not have text/plain header",
        new TextOf(
            new HtHead(
                new InputOf(
                    new Joined(
                        "\r\n",
                        "HTTP/1.1 200 OK",
                        "Content-type: text/plain",
                        "",
                        new TextOf(new BytesOf(bytes)).asString()
                    )
                )
            )
        ),
        new EndsWith("text/plain")
    ).affirm();
}
 
Example #2
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 #3
Source File: PsTwitter.java    From takes with MIT License 6 votes vote down vote up
/**
 * Retrieve Twitter access token.
 * @return The Twitter access token
 * @throws IOException If failed
 */
private String fetch() throws IOException {
    return this.token
        .method("POST")
        .header(
            "Content-Type",
            "application/x-www-form-urlencoded;charset=UTF-8"
        )
        .header(
            "Authorization",
            String.format(
                "Basic %s", DatatypeConverter.printBase64Binary(
                    new UncheckedBytes(
                        new BytesOf(
                            String.format("%s:%s", this.app, this.key)
                        )
                    ).asBytes()
                )
            )
        )
        .fetch().as(RestResponse.class)
        .assertStatus(HttpURLConnection.HTTP_OK)
        .as(JsonResponse.class)
        .json().readObject().getString(PsTwitter.ACCESS_TOKEN);
}
 
Example #4
Source File: RqAuth.java    From takes with MIT License 6 votes vote down vote up
/**
 * Authenticated user.
 * @return User identity
 * @throws IOException If fails
 */
public Identity identity() throws IOException {
    final Iterator<String> headers =
        new RqHeaders.Base(this).header(this.header).iterator();
    final Identity user;
    if (headers.hasNext()) {
        user = new CcPlain().decode(
            new UncheckedBytes(
                new BytesOf(headers.next())
            ).asBytes()
        );
    } else {
        user = Identity.ANONYMOUS;
    }
    return user;
}
 
Example #5
Source File: CcPlain.java    From takes with MIT License 6 votes vote down vote up
@Override
public byte[] encode(final Identity identity) throws IOException {
    final String encoding = Charset.defaultCharset().name();
    final StringBuilder text = new StringBuilder(
        URLEncoder.encode(identity.urn(), encoding)
    );
    for (final Map.Entry<String, String> ent
        : identity.properties().entrySet()) {
        text.append(';')
            .append(ent.getKey())
            .append('=')
            .append(URLEncoder.encode(ent.getValue(), encoding));
    }
    return new UncheckedBytes(
        new BytesOf(text)
    ).asBytes();
}
 
Example #6
Source File: BkBasicTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * Creates Socket mock for reuse.
 *
 * @return Prepared Socket mock
 * @throws Exception If some problem inside
 */
private static MkSocket createMockSocket() throws Exception {
    return new MkSocket(
        new ByteArrayInputStream(
            new BytesOf(
                new Joined(
                    BkBasicTest.CRLF,
                    "GET / HTTP/1.1",
                    BkBasicTest.HOST,
                    "Content-Length: 2",
                    "",
                    "hi"
                )
            ).asBytes()
        )
    );
}
 
Example #7
Source File: HexOfTest.java    From cactoos with MIT License 6 votes vote down vote up
@Test
public void validHex() throws Exception {
    final byte[] bytes = new byte[256];
    for (int index = 0; index < 256; ++index) {
        bytes[index] = (byte) (index + Byte.MIN_VALUE);
    }
    new Assertion<>(
        "Must convert hexadecimal text to bytes",
        new HexOf(
            new org.cactoos.text.HexOf(
                new BytesOf(bytes)
            )
        ).asBytes(),
        new MatcherOf<>(
            (byte[] array) -> Arrays.equals(bytes, array)
        )
    ).affirm();
}
 
Example #8
Source File: TextOfTest.java    From cactoos with MIT License 6 votes vote down vote up
@Test
public void readsFromReader() throws Exception {
    final String source = "hello, друг!";
    new Assertion<>(
        "Can't read string through a reader",
        new TextOf(
            new StringReader(source),
            StandardCharsets.UTF_8
        ).asString(),
        Matchers.equalTo(
            new String(
                new BytesOf(source).asBytes(),
                StandardCharsets.UTF_8
            )
        )
    ).affirm();
}
 
Example #9
Source File: BodyUrlTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * Body.URL can provide the expected input.
 * @throws Exception If there is some problem inside.
 */
@Test
public void returnsCorrectInputWithUrl() throws Exception {
    try (TempFile file = new TempFile()) {
        final Bytes body = new BytesOf("URL returnsCorrectInput!");
        try (OutputStream outStream =
            new OutputTo(file.value()).stream()) {
            new LengthOf(
                new TeeInput(body, new OutputTo(outStream))
            ).intValue();
        }
        final Body.Url input = new Body.Url(file.value().toUri().toURL());
        MatcherAssert.assertThat(
            "Body content of Body.Url doesn't provide the correct bytes",
            new BytesOf(input).asBytes(),
            new IsEqual<>(body.asBytes())
        );
    }
}
 
Example #10
Source File: SkipInputTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void skipsEverythingWhenEndingWithDelimiter() throws Exception {
    final String delimiter = "\r\n";
    MatcherAssert.assertThat(
        new TextOf(
            new SkipInput(
                new InputOf(
                    new Joined(
                        "",
                        "Hello dude! How are you?",
                        delimiter
                    )
                ),
                new BytesOf(delimiter)
            )
        ),
        new TextHasString("")
    );
}
 
Example #11
Source File: BodyUrlTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * Body.URL can provide the expected length.
 * @throws Exception If there is some problem inside.
 */
@Test
public void returnsCorrectLengthWithUrl() throws Exception {
    try (TempFile file = new TempFile()) {
        final Bytes body = new BytesOf("URL returnsCorrectLength!");
        try (OutputStream outStream =
            new OutputTo(file.value()).stream()) {
            new LengthOf(
                new TeeInput(body, new OutputTo(outStream))
            ).intValue();
        }
        MatcherAssert.assertThat(
            "Body content of Body.Url doesn't have the correct length",
            new LengthOf(
                new Body.Url(file.value().toUri().toURL())
            ).intValue(),
            new IsEqual<>(body.asBytes().length)
        );
    }
}
 
Example #12
Source File: SkipInputTest.java    From cactoos-http with MIT License 6 votes vote down vote up
@Test
public void skipsSomeBytes() throws Exception {
    final String prefix = "Hello dude!";
    final String suffix = "How are you?";
    final String delimiter = "\r";
    MatcherAssert.assertThat(
        new TextOf(
            new SkipInput(
                new InputOf(
                    new Joined(
                        delimiter,
                        prefix,
                        suffix
                    )
                ),
                new BytesOf(delimiter)
            )
        ),
        new TextHasString(suffix)
    );
}
 
Example #13
Source File: FbSlf4j.java    From takes with MIT License 5 votes vote down vote up
/**
 * Log this request.
 * @param req Request
 * @throws IOException If fails
 */
private static void log(final RqFallback req) throws IOException {
    FbSlf4j.LOGGER.error(
        "{} {} failed with {}: {}",
        new RqMethod.Base(req).method(),
        new RqHref.Base(req).href(),
        req.code(),
        new TextOf(new BytesOf(req.throwable()))
    );
}
 
Example #14
Source File: BkBasic.java    From takes with MIT License 5 votes vote down vote up
/**
 * Make a failure response.
 * @param err Error
 * @param code HTTP error code
 * @return Response
 */
private static Response failure(final Throwable err, final int code) {
    return new RsWithStatus(
        new RsText(
            new InputStreamOf(
                new BytesOf(err)
            )
        ),
        code
    );
}
 
Example #15
Source File: BytesBase64Test.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void checkEncodeMime() throws Exception {
    new Assertion<>(
        "Must encode bytes using the Base64 mime encoding scheme",
        new BytesBase64(
            new BytesOf(
                "Hello!"
            ), Base64.getMimeEncoder()
        ).asBytes(),
        new IsEqual<>(
            new BytesOf("SGVsbG8h").asBytes()
        )
    ).affirm();
}
 
Example #16
Source File: ResponseOf.java    From takes with MIT License 5 votes vote down vote up
@Override
@SuppressFBWarnings("EQ_UNUSUAL")
public boolean equals(final Object that) {
    return new Unchecked<>(
        new Or(
            () -> this == that,
            new And(
                () -> that != null,
                () -> ResponseOf.class.equals(that.getClass()),
                () -> {
                    final ResponseOf other = (ResponseOf) that;
                    return new And(
                        () -> {
                            final Iterator<String> iter = other.head()
                                .iterator();
                            return new And(
                                (String hdr) -> hdr.equals(iter.next()),
                                this.head()
                            ).value();
                        },
                        () -> new Equality<>(
                            new BytesOf(this.body()),
                            new BytesOf(other.body())
                        ).value() == 0
                    ).value();
                }
            )
        )
    ).value();
}
 
Example #17
Source File: BodyByteArrayTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * Body.ByteArray can provide the expected input.
 * @throws Exception If there is some problem inside.
 */
@Test
public void returnsCorrectInputWithByteArray() throws Exception {
    final byte[] bytes =
        new BytesOf("ByteArray returnsCorrectInput!").asBytes();
    MatcherAssert.assertThat(
        "Body content of Body.ByteArray doesn't provide the correct bytes",
        new BytesOf(new Body.ByteArray(bytes)).asBytes(),
        new IsEqual<>(bytes)
    );
}
 
Example #18
Source File: BodyByteArrayTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * Body.ByteArray can provide the expected length.
 * @throws Exception If there is some problem inside.
 */
@Test
public void returnsCorrectLengthWithStream() throws Exception {
    final byte[] bytes =
        new BytesOf("Stream returnsCorrectLength!").asBytes();
    MatcherAssert.assertThat(
        "Body content of Body.ByteArray doesn't have the correct length",
        new LengthOf(new Body.ByteArray(bytes)).intValue(),
        new IsEqual<>(bytes.length)
    );
}
 
Example #19
Source File: FbLog4j.java    From takes with MIT License 5 votes vote down vote up
/**
 * Log this request.
 * @param req Request
 * @throws IOException If fails
 */
private static void log(final RqFallback req) throws IOException {
    Logger.getLogger(FbLog4j.class).error(
        String.format(
            "%s %s failed with %s: %s",
            new RqMethod.Base(req).method(),
            new RqHref.Base(req).href(),
            req.code(),
            new TextOf(new BytesOf(req.throwable()))
        )
    );
}
 
Example #20
Source File: BodyStreamTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * Body.Stream can provide the expected input.
 * @throws Exception If there is some problem inside.
 */
@Test
public void returnsCorrectInputWithStream() throws Exception {
    final byte[] bytes =
        new BytesOf("Stream returnsCorrectInput!").asBytes();
    MatcherAssert.assertThat(
        "Body content of Body.Stream doesn't provide the correct bytes",
        new BytesOf(
            new Body.Stream(new InputOf(bytes).stream())
        ).asBytes(),
        new IsEqual<>(bytes)
    );
}
 
Example #21
Source File: BodyStreamTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * Body.Stream can provide the expected length.
 * @throws Exception If there is some problem inside.
 */
@Test
public void returnsCorrectLengthWithStream() throws Exception {
    final byte[] bytes =
        new BytesOf("Stream returnsCorrectLength!").asBytes();
    MatcherAssert.assertThat(
        "Body content of Body.Stream doesn't have the correct length",
        new LengthOf(
            new Body.Stream(new InputOf(bytes).stream())
        ).intValue(),
        new IsEqual<>(bytes.length)
    );
}
 
Example #22
Source File: BodyTempFileTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * Body.TemFile can provide the expected input.
 * @throws Exception If there is some problem inside.
 */
@Test
public void returnsCorrectInputWithStream() throws Exception {
    final byte[] bytes =
        new BytesOf("Stream returnsCorrectInput!").asBytes();
    MatcherAssert.assertThat(
        "Body content of Body.TempFile doesn't provide the correct bytes",
        new BytesOf(
            new Body.TempFile(new Body.ByteArray(bytes))
        ).asBytes(),
        new IsEqual<>(bytes)
    );
}
 
Example #23
Source File: BodyTempFileTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * Body.TemFile can provide the expected length.
 * @throws Exception If there is some problem inside.
 */
@Test
public void returnsCorrectLengthWithTempFile() throws Exception {
    final byte[] bytes =
        new BytesOf("TempFile returnsCorrectLength!").asBytes();
    MatcherAssert.assertThat(
        "Body content of Body.TempFile doesn't have the correct length",
        new LengthOf(
            new Body.TempFile(new Body.ByteArray(bytes))
        ).intValue(),
        new IsEqual<>(bytes.length)
    );
}
 
Example #24
Source File: RqFake.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param head Head
 * @param body Body
 */
public RqFake(final List<String> head, final CharSequence body) {
    this(
        head,
        new UncheckedBytes(
            new BytesOf(body.toString())
        ).asBytes());
}
 
Example #25
Source File: CcXor.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param codec Original codec
 * @param key Secret key for encoding
 */
public CcXor(final Codec codec, final String key) {
    this(
        codec,
        new UncheckedBytes(
            new BytesOf(key)
        ).asBytes());
}
 
Example #26
Source File: CcPlain.java    From takes with MIT License 5 votes vote down vote up
@Override
public Identity decode(final byte[] bytes) throws IOException {
    final List<Text> parts = new ListOf<>(
        new Split(
            new TextOf(new BytesOf(bytes)), ";"
        )
    );
    final Map<String, String> map = new HashMap<>(parts.size());
    for (int idx = 1; idx < parts.size(); ++idx) {
        final List<Text> pair = new ListOf<>(
            new Split(parts.get(idx), "=")
        );
        try {
            map.put(
                new UncheckedText(pair.get(0)).asString(),
                CcPlain.decode(new UncheckedText(pair.get(1)).asString())
            );
        } catch (final IllegalArgumentException ex) {
            throw new DecodingException(ex);
        }
    }
    return new Identity.Simple(
        CcPlain.decode(
            new UncheckedText(parts.get(0)).asString()
        ), map
    );
}
 
Example #27
Source File: TextOfTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void readsFromReaderWithDefaultEncoding() throws Exception {
    final String source = "hello, друг! with default encoding";
    new Assertion<>(
        "Can't read string with default encoding through a reader",
        new TextOf(new StringReader(source)).asString(),
        Matchers.equalTo(
            new String(
                new BytesOf(source).asBytes(),
                StandardCharsets.UTF_8
            )
        )
    ).affirm();
}
 
Example #28
Source File: HexOfTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void notEmpytString() throws IOException {
    new Assertion<>(
        "Can't represent a string as hexadecimal",
        new HexOf(
            new BytesOf("What's up, друг?")
        ),
        new TextHasString("5768617427732075702c20d0b4d180d183d0b33f")
    ).affirm();
}
 
Example #29
Source File: HexOfTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void empytString() {
    new Assertion<>(
        "Can't represent an empty string as hexadecimal",
        new HexOf(
            new BytesOf("")
        ),
        new TextHasString("")
    ).affirm();
}
 
Example #30
Source File: RqTempTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * RqTemp can delete the underlying temporary file.
 * @throws IOException if some problem occurs.
 */
@Test
public void deletesTempFile() throws Exception {
    final File file = File.createTempFile(
        RqTempTest.class.getName(),
        ".tmp"
    );
    Files.write(
        file.toPath(),
        new BytesOf("Temp file deletion test").asBytes()
    );
    final Request request = new RqTemp(file);
    try {
        MatcherAssert.assertThat(
            "File is not created!",
            file.exists(),
            Matchers.is(true)
        );
    } finally {
        request.body().close();
    }
    MatcherAssert.assertThat(
        "File exists after stream closure",
        file.exists(),
        Matchers.is(false)
    );
}