Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite9d4a9e

Browse files
committed
backport FeedableBodyGenerator from master
1 parent12177c4 commite9d4a9e

File tree

2 files changed

+245
-0
lines changed

2 files changed

+245
-0
lines changed
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
packagecom.ning.http.client.providers.netty;
2+
3+
importcom.ning.http.client.Body;
4+
importcom.ning.http.client.BodyGenerator;
5+
6+
importjava.io.IOException;
7+
importjava.io.UnsupportedEncodingException;
8+
importjava.nio.ByteBuffer;
9+
importjava.util.Queue;
10+
importjava.util.concurrent.ConcurrentLinkedQueue;
11+
importjava.util.concurrent.atomic.AtomicInteger;
12+
13+
/**
14+
* {@link com.ning.http.client.BodyGenerator} which may return just part of the payload at the time handler is requesting it.
15+
* If it happens, PartialBodyGenerator becomes responsible for finishing payload transferring asynchronously.
16+
*/
17+
publicclassFeedableBodyGeneratorimplementsBodyGenerator {
18+
privatestaticfinalStringUS_ASCII ="US-ASCII";
19+
privatefinalstaticbyte[]END_PADDING =getBytes("\r\n");
20+
privatefinalstaticbyte[]ZERO =getBytes("0");
21+
privatefinalQueue<BodyPart>queue =newConcurrentLinkedQueue<BodyPart>();
22+
privatefinalAtomicIntegerqueueSize =newAtomicInteger();
23+
privateFeedListenerlistener;
24+
25+
@Override
26+
publicBodycreateBody()throwsIOException {
27+
returnnewPushBody();
28+
}
29+
30+
publicvoidfeed(finalByteBufferbuffer,finalbooleanisLast)throwsIOException {
31+
queue.offer(newBodyPart(buffer,isLast));
32+
queueSize.incrementAndGet();
33+
if (listener !=null) {
34+
listener.onContentAdded();
35+
}
36+
}
37+
38+
publicstaticinterfaceFeedListener {
39+
voidonContentAdded();
40+
}
41+
42+
publicvoidsetListener(FeedListenerlistener) {
43+
this.listener =listener;
44+
}
45+
46+
privatefinalclassPushBodyimplementsBody {
47+
privatefinalintONGOING =0;
48+
privatefinalintCLOSING =1;
49+
privatefinalintFINISHED =2;
50+
51+
privateintfinishState =0;
52+
53+
@Override
54+
publiclonggetContentLength() {
55+
return -1;
56+
}
57+
58+
@Override
59+
publiclongread(finalByteBufferbuffer)throwsIOException {
60+
BodyPartnextPart =queue.peek();
61+
if (nextPart ==null) {
62+
// Nothing in the queue
63+
switch (finishState) {
64+
caseONGOING:
65+
return0;
66+
caseCLOSING:
67+
buffer.put(ZERO);
68+
buffer.put(END_PADDING);
69+
finishState =FINISHED;
70+
returnbuffer.position();
71+
caseFINISHED:
72+
buffer.put(END_PADDING);
73+
return -1;
74+
}
75+
}
76+
intcapacity =buffer.remaining() -10;// be safe (we'll have to add size, ending, etc.)
77+
intsize =Math.min(nextPart.buffer.remaining(),capacity);
78+
buffer.put(getBytes(Integer.toHexString(size)));
79+
buffer.put(END_PADDING);
80+
for (inti =0;i <size;i++) {
81+
buffer.put(nextPart.buffer.get());
82+
}
83+
buffer.put(END_PADDING);
84+
if (!nextPart.buffer.hasRemaining()) {
85+
if (nextPart.isLast) {
86+
finishState =CLOSING;
87+
}
88+
queue.remove();
89+
}
90+
returnsize;
91+
}
92+
93+
@Override
94+
publicvoidclose()throwsIOException {
95+
}
96+
97+
}
98+
99+
privatefinalstaticclassBodyPart {
100+
privatefinalbooleanisLast;
101+
privatefinalByteBufferbuffer;
102+
103+
publicBodyPart(finalByteBufferbuffer,finalbooleanisLast) {
104+
this.buffer =buffer;
105+
this.isLast =isLast;
106+
}
107+
}
108+
109+
privatestaticbyte[]getBytes(Strings) {
110+
// for compatibility with java5, we cannot use s.getBytes(Charset)
111+
try {
112+
returns.getBytes(US_ASCII);
113+
}catch (UnsupportedEncodingExceptione) {
114+
thrownewRuntimeException(e);
115+
}
116+
}
117+
}
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
/*
2+
* Copyright (c) 2013-2014 Sonatype, Inc. All rights reserved.
3+
*
4+
* This program is licensed to you under the Apache License Version 2.0,
5+
* and you may not use this file except in compliance with the Apache License Version 2.0.
6+
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
7+
*
8+
* Unless required by applicable law or agreed to in writing,
9+
* software distributed under the Apache License Version 2.0 is distributed on an
10+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
12+
*/
13+
14+
packagecom.ning.http.client.async.netty;
15+
16+
importcom.ning.http.client.*;
17+
importcom.ning.http.client.async.AbstractBasicTest;
18+
importcom.ning.http.client.async.ChunkingTest;
19+
importcom.ning.http.client.async.ProviderUtil;
20+
importcom.ning.http.client.providers.netty.FeedableBodyGenerator;
21+
importorg.eclipse.jetty.server.handler.AbstractHandler;
22+
importorg.testng.Assert;
23+
importorg.testng.annotations.Test;
24+
25+
importjavax.servlet.ServletException;
26+
importjavax.servlet.ServletInputStream;
27+
importjavax.servlet.http.HttpServletRequest;
28+
importjavax.servlet.http.HttpServletResponse;
29+
importjava.io.File;
30+
importjava.io.FileInputStream;
31+
importjava.io.IOException;
32+
importjava.net.URL;
33+
importjava.nio.ByteBuffer;
34+
importjava.nio.channels.FileChannel;
35+
36+
importstaticorg.testng.FileAssert.fail;
37+
38+
publicclassNettyFeedableBodyGeneratorTestextendsAbstractBasicTest {
39+
40+
@Override
41+
publicAsyncHttpClientgetAsyncHttpClient(AsyncHttpClientConfigconfig) {
42+
returnProviderUtil.nettyProvider(config);
43+
}
44+
45+
@Test(groups = {"standalone","default_provider" },enabled =true)
46+
publicvoidtestPutImageFile()throwsException {
47+
FilelargeFile =getTestFile();
48+
finalFileChannelfileChannel =newFileInputStream(largeFile).getChannel();
49+
50+
AsyncHttpClientConfigconfig =newAsyncHttpClientConfig.Builder().setRequestTimeoutInMs(100 *6000).build();
51+
AsyncHttpClientclient =getAsyncHttpClient(config);
52+
finalFeedableBodyGeneratorbodyGenerator =newFeedableBodyGenerator();
53+
54+
try {
55+
RequestBuilderbuilder =newRequestBuilder("PUT")
56+
.setUrl(getTargetUrl())
57+
.setBody(bodyGenerator);
58+
59+
ListenableFuture<Response>listenableFuture =client.executeRequest(builder.build());
60+
61+
booleanrepeat =true;
62+
while (repeat) {
63+
finalByteBufferbuffer =ByteBuffer.allocate(1024);
64+
if (fileChannel.read(buffer) >0) {
65+
buffer.flip();
66+
bodyGenerator.feed(buffer,false);
67+
}else {
68+
repeat =false;
69+
}
70+
}
71+
ByteBufferemptyBuffer =ByteBuffer.wrap(newbyte[0]);
72+
bodyGenerator.feed(emptyBuffer,true);
73+
74+
Responseresponse =listenableFuture.get();
75+
Assert.assertEquals(200,response.getStatusCode());
76+
Assert.assertEquals("" +largeFile.length(),response.getHeader("X-TRANSFERRED"));
77+
}finally {
78+
fileChannel.close();
79+
client.close();
80+
}
81+
}
82+
83+
privatestaticFilegetTestFile() {
84+
StringtestResource1 ="300k.png";
85+
86+
FiletestResource1File =null;
87+
try {
88+
ClassLoadercl =ChunkingTest.class.getClassLoader();
89+
URLurl =cl.getResource(testResource1);
90+
testResource1File =newFile(url.toURI());
91+
}catch (Throwablee) {
92+
// TODO Auto-generated catch block
93+
fail("unable to find " +testResource1);
94+
}
95+
96+
returntestResource1File;
97+
}
98+
99+
@Override
100+
publicAbstractHandlerconfigureHandler()throwsException {
101+
returnnewAbstractHandler() {
102+
103+
publicvoidhandle(Stringarg0,org.eclipse.jetty.server.Requestarg1,HttpServletRequestreq,HttpServletResponseresp)throwsIOException,ServletException {
104+
105+
ServletInputStreamin =req.getInputStream();
106+
byte[]b =newbyte[8192];
107+
108+
intcount = -1;
109+
inttotal =0;
110+
while ((count =in.read(b)) != -1) {
111+
b =newbyte[8192];
112+
total +=count;
113+
}
114+
System.err.println("consumed " +total +" bytes.");
115+
116+
resp.setStatus(200);
117+
resp.addHeader("X-TRANSFERRED",String.valueOf(total));
118+
resp.getOutputStream().flush();
119+
resp.getOutputStream().close();
120+
121+
arg1.setHandled(true);
122+
123+
}
124+
};
125+
}
126+
127+
128+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp