Skip to content

Commit

Permalink
Allow direct byte array entities in responses
Browse files Browse the repository at this point in the history
  • Loading branch information
rchodava committed Mar 3, 2016
1 parent beadf57 commit a32a98d
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 0 deletions.
Expand Up @@ -15,6 +15,7 @@ public interface ResponseBuilder {
Observable<Response> notFound();
Observable<Response> ok();
Observable<Response> ok(String content);
Observable<Response> ok(byte[] content);
Observable<Response> unauthorized();
Observable<Response> unauthorized(String content);
}
@@ -0,0 +1,36 @@
package org.chodavarapu.datamill.http.impl;

import org.chodavarapu.datamill.http.Entity;
import org.chodavarapu.datamill.json.JsonObject;
import rx.Observable;

/**
* @author Ravi Chodavarapu (rchodava@gmail.com)
*/
public class BytesEntity implements Entity {
private byte[] bytes;

public BytesEntity(byte[] bytes) {
this.bytes = bytes;
}

@Override
public Observable<byte[]> asBytes() {
return Observable.just(bytes);
}

@Override
public Observable<byte[]> asChunks() {
return asBytes();
}

@Override
public Observable<JsonObject> asJson() {
return asString().map(json -> new JsonObject(json));
}

@Override
public Observable<String> asString() {
return asBytes().map(bytes -> new String(bytes));
}
}
Expand Up @@ -61,6 +61,11 @@ public Observable<Response> ok(String content) {
return Observable.just(new ResponseImpl(Status.OK, headers, new ValueEntity(new StringValue(content))));
}

@Override
public Observable<Response> ok(byte[] content) {
return Observable.just(new ResponseImpl(Status.OK, headers, new BytesEntity(content)));
}

@Override
public Observable<Response> unauthorized() {
return Observable.just(new ResponseImpl(Status.UNAUTHORIZED, headers));
Expand Down
@@ -0,0 +1,32 @@
package org.chodavarapu.datamill.http.impl;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

/**
* @author Ravi Chodavarapu (rchodava@gmail.com)
*/
public class BytesEntityTest {
@Test
public void entityTests() {
assertEquals("test", new BytesEntity("test".getBytes()).asString().toBlocking().last());
assertEquals("test", new String(new BytesEntity("test".getBytes()).asBytes().toBlocking().last()));
assertEquals("test", new String(new BytesEntity("test".getBytes())
.asChunks()
.collect(
() -> new ByteArrayOutputStream(),
(stream, chunk) -> {
try {
stream.write(chunk);
} catch (IOException e) {
}
})
.map(stream -> stream.toByteArray()).toBlocking().last()));
assertEquals("value", new BytesEntity("{\"name\":\"value\"}".getBytes())
.asJson().toBlocking().last().get("name").asString());
}
}

0 comments on commit a32a98d

Please sign in to comment.