use of org.jocean.http.client.impl.DefaultHttpClient in project jocean-http by isdom.
the class SignalTest method main.
/**
* @param args
* @throws Exception
* @throws Exception
*/
public static void main(String[] args) throws Exception {
final TestChannelPool pool = new TestChannelPool(1);
final HttpClient httpClient = new DefaultHttpClient(new AbstractChannelCreator() {
@Override
protected void initializeBootstrap(final Bootstrap bootstrap) {
bootstrap.group(new NioEventLoopGroup(1)).channel(NioSocketChannel.class);
}
}, pool, ENABLE_LOGGING, ENABLE_COMPRESSOR);
final DefaultSignalClient client = new DefaultSignalClient(httpClient);
client.registerRequestType(FetchPatientsRequest.class, FetchPatientsResponse.class, new URI("http://jumpbox.medtap.cn:8888"));
client.registerRequestType(QueryMyPatientsForDoctorRequest.class, QueryMyPatientsForDoctorResponse.class, new URI("http://api.iplusmed.com"));
client.registerRequestType(AddMultiMediasToJourneyRequest.class, AddMultiMediasToJourneyResponse.class, new URI("http://jumpbox.medtap.cn:8888"));
{
final QueryMyPatientsForDoctorRequest req = new QueryMyPatientsForDoctorRequest();
req.setDoctorId("8510");
((SignalClient) client).interaction().request(req).<QueryMyPatientsForDoctorResponse>build().subscribe(new Subscriber<QueryMyPatientsForDoctorResponse>() {
@Override
public void onCompleted() {
LOG.debug("FetchPatientsRequest: onCompleted.");
}
@Override
public void onError(Throwable e) {
LOG.debug("FetchPatientsRequest: onError: {}", ExceptionUtils.exception2detail(e));
}
@Override
public void onNext(final QueryMyPatientsForDoctorResponse response) {
LOG.debug("QueryMyPatientsForDoctorRequest: onNext: {}", response);
}
});
}
/*
final CountDownLatch latch = new CountDownLatch(1);
{
final FetchPatientsRequest req = new FetchPatientsRequest();
req.setAccountId("2");
client.defineInteraction(req)
.compose(RxNettys.<FetchPatientsResponse>filterProgress())
.subscribe(new Subscriber<FetchPatientsResponse>() {
@Override
public void onCompleted() {
latch.countDown();
LOG.debug("FetchPatientsRequest: onCompleted.");
}
@Override
public void onError(Throwable e) {
latch.countDown();
LOG.debug("FetchPatientsRequest: onError: {}", ExceptionUtils.exception2detail(e));
}
@Override
public void onNext(final FetchPatientsResponse response) {
LOG.debug("FetchPatientsRequest: onNext: {}", response);
}});
}
latch.await();
pool.awaitRecycleChannels();
*/
{
final HttpUtil.TrafficCounterFeature trafficCounter = HttpUtil.buildTrafficCounterFeature();
final HttpUtil.PayloadCounterFeature payloadCounter = HttpUtil.buildPayloadCounterFeature();
final AddMultiMediasToJourneyRequest req = new AddMultiMediasToJourneyRequest();
req.setCaseId("120");
req.setJourneyId("1");
final Subscription subscription = client.interaction().request(req).feature(// new Attachment("/Users/isdom/Desktop/997df3df73797e91dea4853c228fcbdee36ceb8a38cc8-1vxyhE_fw236.jpeg", "image/jpeg"))
ENABLE_LOGGING, trafficCounter, payloadCounter, new Attachment("/Users/isdom/Pictures/IMG_3492.JPG", "image/jpeg")).<AddMultiMediasToJourneyResponse>build().subscribe(new Subscriber<AddMultiMediasToJourneyResponse>() {
@Override
public void onCompleted() {
LOG.debug("AddMultiMediasToJourneyRequest: onCompleted.");
LOG.debug("traffic: upload: {}/download: {}", trafficCounter.outboundBytes(), trafficCounter.inboundBytes());
LOG.debug("payload: totalUpload: {}/totalDownload: {}", payloadCounter.totalUploadBytes(), payloadCounter.totalDownloadBytes());
}
@Override
public void onError(Throwable e) {
LOG.debug("AddMultiMediasToJourneyRequest: onError: {}", ExceptionUtils.exception2detail(e));
}
@Override
public void onNext(final AddMultiMediasToJourneyResponse resp) {
LOG.debug("AddMultiMediasToJourneyRequest: onNext: {}", resp);
}
});
// subscription.unsubscribe();
// TODO, why invoke onCompleted Event? not onError, check
// TO BE CONTINUE, 2015-05-13
LOG.debug("traffic: upload: {}/download: {}", trafficCounter.outboundBytes(), trafficCounter.inboundBytes());
LOG.debug("payload: totalUpload: {}/totalDownload: {}", payloadCounter.totalUploadBytes(), payloadCounter.totalDownloadBytes());
}
}
use of org.jocean.http.client.impl.DefaultHttpClient in project jocean-http by isdom.
the class HttpServerDemo method main.
public static void main(final String[] args) throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
final // SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
// create for LocalChannel
@SuppressWarnings("resource") final HttpServerBuilder server = new DefaultHttpServerBuilder(new AbstractBootstrapCreator(new DefaultEventLoopGroup(1), new DefaultEventLoopGroup()) {
@Override
protected void initializeBootstrap(final ServerBootstrap bootstrap) {
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
bootstrap.channel(LocalServerChannel.class);
}
}, Feature.ENABLE_LOGGING, new Feature.ENABLE_SSL(sslCtx));
@SuppressWarnings("unused") final Subscription subscription = server.defineServer(new LocalAddress("test")).subscribe(new Action1<HttpTrade>() {
@Override
public void call(final HttpTrade trade) {
trade.outbound(trade.inbound().compose(RxNettys.message2fullreq(trade)).map(DisposableWrapperUtil.<FullHttpRequest>unwrap()).map(new Func1<FullHttpRequest, HttpObject>() {
@Override
public HttpObject call(final FullHttpRequest fullreq) {
try {
final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(Nettys.dumpByteBufAsBytes(fullreq.content())));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}));
}
});
@SuppressWarnings("resource") final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), Feature.ENABLE_LOGGING, new Feature.ENABLE_SSL(SslContextBuilder.forClient().build()));
while (true) {
final ByteBuf content = Unpooled.buffer(0);
content.writeBytes("test content".getBytes("UTF-8"));
final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", content);
HttpUtil.setContentLength(request, content.readableBytes());
/* // TODO using initiator
final Iterator<HttpObject> itr =
client.defineInteraction(
new LocalAddress("test"),
Observable.just(request))
.map(RxNettys.<HttpObject>retainer())
.toBlocking().toIterable().iterator();
final byte[] bytes = RxNettys.httpObjectsAsBytes(itr);
LOG.info("recv Response: {}", new String(bytes, "UTF-8"));
*/
Thread.sleep(1000);
}
}
use of org.jocean.http.client.impl.DefaultHttpClient in project jocean-http by isdom.
the class MessageUtilTestCase method testPostWithbody.
@Test
public final void testPostWithbody() {
final SendRedpackRequest request = new SendRedpackRequest();
request.setMchId("11111");
request.setMchBillno("222222");
final HttpClient client = new DefaultHttpClient();
MessageUtil.interact(client).method(HttpMethod.POST).uri("http://www.sina.com").reqbean(request).body(MessageUtil.toBody(request, MediaType.APPLICATION_XML, MessageUtil::serializeToXml)).feature(Feature.ENABLE_LOGGING_OVER_SSL).execution().compose(MessageUtil.responseAsString()).toBlocking().single();
}
use of org.jocean.http.client.impl.DefaultHttpClient in project jocean-http by isdom.
the class SslDemo method main.
public static void main(String[] args) throws Exception {
final SslContext sslCtx = SslContextBuilder.forClient().build();
final Feature sslfeature = new Feature.ENABLE_SSL(sslCtx);
try (final HttpClient client = new DefaultHttpClient()) {
{
final String host = "www.sina.com.cn";
final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
// HttpUtil.setKeepAlive(request, true);
request.headers().set(HttpHeaderNames.HOST, host);
LOG.debug("send request:{}", request);
final String content = sendRequestAndRecv(client, host, 443, request, sslfeature, Feature.ENABLE_LOGGING, Feature.ENABLE_COMPRESSOR);
// LOG.info("recv:{}", content);
}
/*
{
final String host = "www.alipay.com";
final DefaultFullHttpRequest request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_0, HttpMethod.GET, "/");
HttpUtil.setKeepAlive(request, true);
request.headers().set(HttpHeaderNames.HOST, host);
LOG.debug("send request:{}", request);
LOG.info("recv:{}", sendRequestAndRecv(client, request, host, sslfeature));
}
*/
/*
{
final String host = "github.com";
final DefaultFullHttpRequest request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_0, HttpMethod.GET, "/isdom");
HttpUtil.setKeepAlive(request, true);
request.headers().set(HttpHeaderNames.HOST, host);
LOG.debug("send request:{}", request);
LOG.info("recv:{}", sendRequestAndRecv(client, request, host, sslfeature));
}
*/
}
}
use of org.jocean.http.client.impl.DefaultHttpClient in project jocean-http by isdom.
the class DefaultSignalClientTestCase method testSignalClientWithAttachmentSuccess.
@Test
public void testSignalClientWithAttachmentSuccess() throws Exception {
final TestResponse respToSendback = new TestResponse("0", "OK");
final AtomicReference<HttpMethod> reqMethodReceivedRef = new AtomicReference<>();
final AtomicReference<String> reqpathReceivedRef = new AtomicReference<>();
final AtomicReference<TestRequestByPost> reqbeanReceivedRef = new AtomicReference<>();
final List<FileUpload> uploads = new ArrayList<>();
final Action2<FullHttpRequest, HttpTrade> requestAndTradeAwareWhenCompleted = new Action2<FullHttpRequest, HttpTrade>() {
@Override
public void call(final FullHttpRequest req, final HttpTrade trade) {
reqMethodReceivedRef.set(req.method());
reqpathReceivedRef.set(req.uri());
HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(HTTP_DATA_FACTORY, req);
// first is signal
boolean isfirst = true;
while (decoder.hasNext()) {
final InterfaceHttpData data = decoder.next();
if (!isfirst) {
if (data instanceof FileUpload) {
uploads.add((FileUpload) data);
}
} else {
isfirst = false;
try {
reqbeanReceivedRef.set((TestRequestByPost) JSON.parseObject(Nettys.dumpByteBufAsBytes(((FileUpload) data).content()), TestRequestByPost.class));
} catch (Exception e) {
LOG.warn("exception when JSON.parseObject, detail: {}", ExceptionUtils.exception2detail(e));
}
}
}
trade.outbound(buildResponse(respToSendback, trade.onTerminate()));
}
};
// launch test server for attachment send
final String testAddr = UUID.randomUUID().toString();
final Subscription server = TestHttpUtil.createTestServerWith(testAddr, requestAndTradeAwareWhenCompleted, Feature.ENABLE_LOGGING, Feature.ENABLE_COMPRESSOR);
try {
final TestChannelCreator creator = new TestChannelCreator();
final TestChannelPool pool = new TestChannelPool(1);
final DefaultHttpClient httpclient = new DefaultHttpClient(creator, pool);
final DefaultSignalClient signalClient = new DefaultSignalClient(new URI("http://test"), httpclient, new AttachmentBuilder4InMemory());
signalClient.registerRequestType(TestRequestByPost.class, TestResponse.class, null, buildUri2Addr(testAddr), Feature.ENABLE_LOGGING);
final AttachmentInMemory[] attachsToSend = new AttachmentInMemory[] { new AttachmentInMemory("1", "text/plain", "11111111111111".getBytes(Charsets.UTF_8)), new AttachmentInMemory("2", "text/plain", "22222222222222222".getBytes(Charsets.UTF_8)), new AttachmentInMemory("3", "text/plain", "333333333333333".getBytes(Charsets.UTF_8)) };
final TestRequestByPost reqToSend = new TestRequestByPost("1", null);
final TestResponse respReceived = ((SignalClient) signalClient).interaction().request(reqToSend).feature(attachsToSend).<TestResponse>build().timeout(1, TimeUnit.SECONDS).toBlocking().single();
assertEquals(HttpMethod.POST, reqMethodReceivedRef.get());
assertEquals("/test/simpleRequest", reqpathReceivedRef.get());
assertEquals(reqToSend, reqbeanReceivedRef.get());
assertEquals(respToSendback, respReceived);
final FileUpload[] attachsReceived = uploads.toArray(new FileUpload[0]);
assertEquals(attachsToSend.length, attachsReceived.length);
for (int idx = 0; idx < attachsToSend.length; idx++) {
final AttachmentInMemory inmemory = attachsToSend[idx];
final FileUpload upload = attachsReceived[idx];
assertEquals(inmemory.filename, upload.getName());
assertEquals(inmemory.contentType, upload.getContentType());
assertTrue(Arrays.equals(inmemory.content(), upload.get()));
}
pool.awaitRecycleChannels();
} finally {
server.unsubscribe();
}
}
Aggregations