Here are the examples of the java api com.liulishuo.okdownload.OkDownload.with() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
111 Examples
19
Source : FileDownloadListTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void get() {
BaseDownloadTask.IRunningTask task = FileDownloadList.getImpl().get(0);
replacedertNull(task);
final DownloadTaskAdapter firstAddedTask = FileDownloadList.getImpl().list.get(0);
firstAddedTask.insurereplacedembleDownloadTask();
final DownloadDispatcher downloadDispatcher = OkDownload.with().downloadDispatcher();
when(downloadDispatcher.isRunning(firstAddedTask.getDownloadTask())).thenReturn(false);
task = FileDownloadList.getImpl().get(firstAddedTask.getId());
replacedertNull(task);
final DownloadTaskAdapter secondAddedTask = FileDownloadList.getImpl().list.get(1);
when(downloadDispatcher.isRunning(secondAddedTask.getDownloadTask())).thenReturn(true);
task = FileDownloadList.getImpl().get(secondAddedTask.getId());
replacedertThat(task).isEqualTo(secondAddedTask);
}
19
Source : FileDownloadList.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Nullable
public BaseDownloadTask.IRunningTask get(final int id) {
synchronized (list) {
for (DownloadTaskAdapter.IRunningTask task : list) {
if (task.is(id)) {
final DownloadTaskAdapter downloadTaskAdapter = (DownloadTaskAdapter) task.getOrigin();
if (OkDownload.with().downloadDispatcher().isRunning(downloadTaskAdapter.getDownloadTask())) {
return task;
}
}
}
}
return null;
}
19
Source : FileDownloader.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
public int pause(final int id) {
OkDownload.with().downloadDispatcher().cancel(id);
return 0;
}
19
Source : FileDownloader.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
public void pauseAll() {
OkDownload.with().downloadDispatcher().cancelAll();
}
19
Source : FileDownloader.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
/**
* Find the running task by {@code id}, and replace its listener width the new one
* {@code listener}.
*
* @return The target task's DownloadId, if not exist target task, and replace failed, will be 0
* @see #replaceListener(String, FileDownloadListener)
* @see #replaceListener(String, String, FileDownloadListener)
*/
public int replaceListener(int id, FileDownloadListener listener) {
final BaseDownloadTask.IRunningTask task = FileDownloadList.getImpl().get(id);
if (task == null) {
OkDownload.with().breakpointStore().remove(id);
return 0;
}
final DownloadTaskAdapter downloadTask = (DownloadTaskAdapter) task.getOrigin();
downloadTask.replaceListener(listener);
return downloadTask.getId();
}
19
Source : RemitStoreOnSQLiteTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void setRemitToDBDelayMillis() {
OkDownload.setSingletonInstance(mock(OkDownload.clreplaced));
doReturn(mock(BreakpointStoreOnCache.clreplaced)).when(OkDownload.with()).breakpointStore();
thrown.expect(IllegalStateException.clreplaced);
RemitStoreOnSQLite.setRemitToDBDelayMillis(1);
doReturn(store).when(OkDownload.with()).breakpointStore();
RemitStoreOnSQLite.setRemitToDBDelayMillis(-1);
replacedertThat(remitHelper.delayMillis).isEqualTo(0);
RemitStoreOnSQLite.setRemitToDBDelayMillis(1);
replacedertThat(remitHelper.delayMillis).isEqualTo(1);
}
19
Source : RemitStoreOnSQLite.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
public static void setRemitToDBDelayMillis(int delayMillis) {
final BreakpointStore store = OkDownload.with().breakpointStore();
if (!(store instanceof RemitStoreOnSQLite)) {
throw new IllegalStateException("The current store is " + store + " not RemitStoreOnSQLite!");
}
delayMillis = Math.max(0, delayMillis);
((RemitStoreOnSQLite) store).remitHelper.delayMillis = delayMillis;
}
19
Source : FetchDataInterceptorTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void interceptFetch() throws IOException {
final CallbackDispatcher dispatcher = OkDownload.with().callbackDispatcher();
doReturn(10).when(inputStream).read(any(byte[].clreplaced));
doReturn(true).when(dispatcher).isFetchProcessMoment(task);
interceptor.interceptFetch(chain);
final DownloadStrategy downloadStrategy = OkDownload.with().downloadStrategy();
verify(downloadStrategy).inspectNetworkOnWifi(eq(task));
verify(chain).increaseCallbackBytes(10L);
verify(chain).flushNoCallbackIncreaseBytes();
verify(outputStream).write(eq(0), any(byte[].clreplaced), eq(10));
}
19
Source : CallServerInterceptorTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void interceptConnect() throws Exception {
serverInterceptor.interceptConnect(chain);
final DownloadStrategy downloadStrategy = OkDownload.with().downloadStrategy();
verify(downloadStrategy).inspectNetworkOnWifi(eq(task));
verify(downloadStrategy).inspectNetworkAvailable();
}
19
Source : ProcessFileStrategyTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void isPreAllocateLength() throws IOException {
mockOkDownload();
// no pre-allocate set on task.
when(task.getSetPreAllocateLength()).thenReturn(null);
final DownloadOutputStream.Factory factory = OkDownload.with().outputStreamFactory();
when(factory.supportSeek()).thenReturn(false);
replacedertThat(strategy.isPreAllocateLength(task)).isFalse();
when(factory.supportSeek()).thenReturn(true);
replacedertThat(strategy.isPreAllocateLength(task)).isTrue();
// pre-allocate set on task.
when(task.getSetPreAllocateLength()).thenReturn(false);
replacedertThat(strategy.isPreAllocateLength(task)).isFalse();
when(task.getSetPreAllocateLength()).thenReturn(true);
replacedertThat(strategy.isPreAllocateLength(task)).isTrue();
// pre-allocate set on task is true but can't support seek.
when(factory.supportSeek()).thenReturn(false);
replacedertThat(strategy.isPreAllocateLength(task)).isFalse();
}
19
Source : MultiPointOutputStreamTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void cancel_notRun_withCancelled() throws IOException {
multiPointOutputStream.allNoSyncLength.set(1);
multiPointOutputStream.canceled = true;
final ProcessFileStrategy strategy = OkDownload.with().processFileStrategy();
final FileLock fileLock = mock(FileLock.clreplaced);
when(strategy.getFileLock()).thenReturn(fileLock);
multiPointOutputStream.cancel();
replacedertThat(multiPointOutputStream.noMoreStreamList).hreplacedize(0);
verify(multiPointOutputStream, never()).ensureSync(anyBoolean(), anyInt());
verify(fileLock, never()).increaseLock(eq(existFile.getAbsolutePath()));
verify(fileLock, never()).decreaseLock(eq(existFile.getAbsolutePath()));
verify(multiPointOutputStream, never()).close(anyInt());
verify(store, never()).onTaskEnd(anyInt(), any(EndCause.clreplaced), any(Exception.clreplaced));
}
19
Source : MultiPointOutputStreamTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void cancel_notRun_withRequireStreamBlocksNotInitial() throws IOException {
multiPointOutputStream.allNoSyncLength.set(1);
final ProcessFileStrategy strategy = OkDownload.with().processFileStrategy();
final FileLock fileLock = mock(FileLock.clreplaced);
when(strategy.getFileLock()).thenReturn(fileLock);
multiPointOutputStream.cancel();
verify(multiPointOutputStream, never()).ensureSync(anyBoolean(), anyInt());
verify(fileLock, never()).increaseLock(eq(existFile.getAbsolutePath()));
verify(fileLock, never()).decreaseLock(eq(existFile.getAbsolutePath()));
verify(multiPointOutputStream, never()).close(anyInt());
verify(store, never()).onTaskEnd(anyInt(), any(EndCause.clreplaced), any(Exception.clreplaced));
}
19
Source : DownloadStrategyTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void isUseMultiBlock() throws IOException {
mockOkDownload();
when(OkDownload.with().outputStreamFactory().supportSeek()).thenReturn(false);
replacedertThat(strategy.isUseMultiBlock(false)).isFalse();
replacedertThat(strategy.isUseMultiBlock(true)).isFalse();
when(OkDownload.with().outputStreamFactory().supportSeek()).thenReturn(true);
replacedertThat(strategy.isUseMultiBlock(true)).isTrue();
}
19
Source : DownloadChainTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void flushNoCallbackIncreaseBytes() {
chain.increaseCallbackBytes(10L);
chain.increaseCallbackBytes(6L);
replacedertThat(chain.noCallbackIncreaseBytes).isEqualTo(16L);
chain.flushNoCallbackIncreaseBytes();
verify(OkDownload.with().callbackDispatcher().dispatch()).fetchProgress(eq(chain.getTask()), eq(0), eq(16L));
replacedertThat(chain.noCallbackIncreaseBytes).isZero();
}
19
Source : DownloadChainTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void getConnectionOrCreate() throws IOException {
final String infoUrl = "infoUrl";
final DownloadConnection.Factory connectionFactory = OkDownload.with().connectionFactory();
final BreakpointInfo info = mock(BreakpointInfo.clreplaced);
when(info.getUrl()).thenReturn(infoUrl);
DownloadChain chain = DownloadChain.createChain(0, mock(DownloadTask.clreplaced), info, mock(DownloadCache.clreplaced), store);
// using info url
final DownloadConnection connection = chain.getConnectionOrCreate();
verify(connectionFactory).create(infoUrl);
// using created one.
replacedertThat(chain.getConnectionOrCreate()).isEqualTo(connection);
final String redirectLocation = "redirectLocation";
final DownloadCache cache = mock(DownloadCache.clreplaced);
when(cache.getRedirectLocation()).thenReturn(redirectLocation);
chain = DownloadChain.createChain(0, mock(DownloadTask.clreplaced), info, cache, store);
// using redirect location instead of info url.
chain.getConnectionOrCreate();
verify(connectionFactory).create(redirectLocation);
}
19
Source : DownloadCallTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void execute_preconditionFailedMaxTimes() throws InterruptedException, IOException {
final CallbackDispatcher dispatcher = OkDownload.with().callbackDispatcher();
final DownloadCache cache = mock(DownloadCache.clreplaced);
doReturn(cache).when(call).createCache(eq(info));
doNothing().when(call).start(eq(cache), eq(info));
doReturn(mock(BreakpointRemoteCheck.clreplaced)).when(call).createRemoteCheck(eq(info));
doReturn(mock(BreakpointLocalCheck.clreplaced)).when(call).createLocalCheck(eq(info), anyLong());
doReturn(mock(DownloadListener.clreplaced)).when(dispatcher).dispatch();
when(cache.isPreconditionFailed()).thenReturn(true);
call.execute();
verify(call, times(DownloadCall.MAX_COUNT_RETRY_FOR_PRECONDITION_FAILED + 1)).start(eq(cache), eq(info));
// only once.
final DownloadListener listener = OkDownload.with().callbackDispatcher().dispatch();
verify(listener).taskStart(eq(task));
}
19
Source : DownloadCallTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void finished_callToDispatch() {
call.finished();
verify(OkDownload.with().downloadDispatcher()).finish(call);
}
19
Source : DownloadCallTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void execute_reuseAnotherInfo() throws IOException, InterruptedException {
doReturn(mock(BreakpointRemoteCheck.clreplaced)).when(call).createRemoteCheck(eq(info));
doReturn(mock(BreakpointLocalCheck.clreplaced)).when(call).createLocalCheck(eq(info), anyLong());
doNothing().when(call).start(any(DownloadCache.clreplaced), eq(info));
call.execute();
final DownloadStrategy strategy = OkDownload.with().downloadStrategy();
verify(strategy).inspectAnotherSameInfo(eq(task), eq(info), eq(0L));
}
19
Source : DownloadCallTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void replacedembleBlockAndCallbackFromBeginning() {
final BreakpointRemoteCheck remoteCheck = mock(BreakpointRemoteCheck.clreplaced);
final ResumeFailedCause failedCause = mock(ResumeFailedCause.clreplaced);
call.replacedembleBlockAndCallbackFromBeginning(info, remoteCheck, failedCause);
final DownloadListener listener = OkDownload.with().callbackDispatcher().dispatch();
verify(listener).downloadFromBeginning(eq(task), eq(info), eq(failedCause));
}
19
Source : ConnectTrialTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
private void setupConnection() throws IOException {
mockOkDownload();
final DownloadConnection.Factory factory = OkDownload.with().connectionFactory();
when(factory.create(url)).thenReturn(connection);
}
19
Source : ConnectTrialTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void trialHeadMethodForInstanceLength() throws IOException {
final DownloadConnection.Factory factory = OkDownload.with().connectionFactory();
final DownloadConnection connection = mock(DownloadConnection.clreplaced);
when(factory.create(anyString())).thenReturn(connection);
final DownloadConnection.Connected connected = mock(DownloadConnection.Connected.clreplaced);
when(connection.execute()).thenReturn(connected);
when(connected.getResponseHeaderField(CONTENT_LENGTH)).thenReturn("10");
final CallbackDispatcher callbackDispatcher = OkDownload.with().callbackDispatcher();
final DownloadListener listener = mock(DownloadListener.clreplaced);
when(callbackDispatcher.dispatch()).thenReturn(listener);
connectTrial.trialHeadMethodForInstanceLength();
verify(connection).setRequestMethod(eq(METHOD_HEAD));
verify(listener).connectTrialStart(eq(task), nullable(Map.clreplaced));
verify(listener).connectTrialEnd(eq(task), anyInt(), nullable(Map.clreplaced));
replacedertThat(connectTrial.getInstanceLength()).isEqualTo(10L);
}
19
Source : ConnectTrialTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void executeTrial() throws Exception {
final String redirectLocation = "http://location";
when(connected.getRedirectLocation()).thenReturn(redirectLocation);
connectTrial.executeTrial();
final DownloadStrategy downloadStrategy = OkDownload.with().downloadStrategy();
verify(downloadStrategy).inspectNetworkOnWifi(eq(task));
verify(downloadStrategy).inspectNetworkAvailable();
verify(connection).addHeader(eq(IF_MATCH), eq(etag));
verify(connection).addHeader(eq(RANGE), eq("bytes=0-0"));
verify(task).setRedirectLocation(redirectLocation);
verify(connection).execute();
verify(connection).release();
}
19
Source : BreakpointRemoteCheckTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void check_collectResult() throws IOException {
mockOkDownload();
when(connectTrial.getInstanceLength()).thenReturn(1L);
when(connectTrial.isAcceptRange()).thenReturn(true);
check.check();
replacedertThat(check.isResumable()).isTrue();
replacedertThat(check.getCause()).isNull();
replacedertThat(check.getInstanceLength()).isEqualTo(1L);
replacedertThat(check.isAcceptRange()).isTrue();
final ResumeFailedCause cause = mock(ResumeFailedCause.clreplaced);
when(OkDownload.with().downloadStrategy().getPreconditionFailedCause(anyInt(), anyBoolean(), eq(info), eq(responseEtag))).thenReturn(cause);
check.check();
replacedertThat(check.isResumable()).isFalse();
replacedertThat(check.getCause()).isEqualTo(cause);
}
19
Source : BreakpointRemoteCheckTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void check_trialSpecialPreplaced() throws IOException {
mockOkDownload();
when(OkDownload.with().downloadStrategy().isServerCanceled(0, false)).thenReturn(true);
doReturn(true).when(check).isTrialSpecialPreplaced(anyInt(), anyLong(), anyBoolean());
check.check();
// no exception
}
19
Source : BreakpointRemoteCheckTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test(expected = FileBusyAfterRunException.clreplaced)
public void check_fileConflictAfterRun() throws IOException {
mockOkDownload();
when(OkDownload.with().downloadDispatcher().isFileConflictAfterRun(eq(task))).thenReturn(true);
check.check();
}
19
Source : BreakpointRemoteCheckTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void check_replacedembleBasicData() throws IOException {
mockOkDownload();
check.check();
final DownloadStrategy strategy = OkDownload.with().downloadStrategy();
verify(strategy).validFilenameFromResponse(eq(responseFilename), eq(task), eq(info));
verify(info).setChunked(eq(connectTrial.isChunked()));
verify(info).setEtag(eq(responseEtag));
}
19
Source : BreakpointRemoteCheckTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test(expected = ServerCanceledException.clreplaced)
public void check_serverCanceled() throws IOException {
mockOkDownload();
when(OkDownload.with().downloadStrategy().isServerCanceled(0, false)).thenReturn(true);
check.check();
}
19
Source : FetchDataInterceptor.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Override
public long interceptFetch(DownloadChain chain) throws IOException {
if (chain.getCache().isInterrupt()) {
throw InterruptException.SIGNAL;
}
OkDownload.with().downloadStrategy().inspectNetworkOnWifi(chain.getTask());
// fetch
int fetchLength = inputStream.read(readBuffer);
if (fetchLength == -1) {
return fetchLength;
}
// write to file
outputStream.write(blockIndex, readBuffer, fetchLength);
chain.increaseCallbackBytes(fetchLength);
if (this.dispatcher.isFetchProcessMoment(task)) {
chain.flushNoCallbackIncreaseBytes();
}
return fetchLength;
}
19
Source : CallServerInterceptor.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@NonNull
@Override
public DownloadConnection.Connected interceptConnect(DownloadChain chain) throws IOException {
OkDownload.with().downloadStrategy().inspectNetworkOnWifi(chain.getTask());
OkDownload.with().downloadStrategy().inspectNetworkAvailable();
return chain.getConnectionOrCreate().execute();
}
19
Source : DownloadChain.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
void start() throws IOException {
final CallbackDispatcher dispatcher = OkDownload.with().callbackDispatcher();
// connect chain
final RetryInterceptor retryInterceptor = new RetryInterceptor();
final BreakpointInterceptor breakpointInterceptor = new BreakpointInterceptor();
connectInterceptorList.add(retryInterceptor);
connectInterceptorList.add(breakpointInterceptor);
connectInterceptorList.add(new HeaderInterceptor());
connectInterceptorList.add(new CallServerInterceptor());
connectIndex = 0;
final DownloadConnection.Connected connected = processConnect();
if (cache.isInterrupt()) {
throw InterruptException.SIGNAL;
}
dispatcher.dispatch().fetchStart(task, blockIndex, getResponseContentLength());
// fetch chain
final FetchDataInterceptor fetchDataInterceptor = new FetchDataInterceptor(blockIndex, connected.getInputStream(), getOutputStream(), task);
fetchInterceptorList.add(retryInterceptor);
fetchInterceptorList.add(breakpointInterceptor);
fetchInterceptorList.add(fetchDataInterceptor);
fetchIndex = 0;
final long totalFetchedBytes = processFetch();
dispatcher.dispatch().fetchEnd(task, blockIndex, totalFetchedBytes);
}
19
Source : DownloadCall.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
public boolean cancel() {
synchronized (this) {
if (canceled)
return false;
if (finishing)
return false;
this.canceled = true;
}
final long startCancelTime = SystemClock.uptimeMillis();
OkDownload.with().downloadDispatcher().flyingCanceled(this);
final DownloadCache cache = this.cache;
if (cache != null)
cache.setUserCanceled();
// ArrayList#clone is not a thread safe operation,
// so chains#size may > chains#elementData.length and this will cause
// ConcurrentModificationException during iterate the ArrayList(ArrayList#next).
// This is a reproduce example:
// https://repl.it/talk/share/ConcurrentModificationException/18566.
// So don't use clone anymore.
final Object[] chains = blockChainList.toArray();
if (chains == null || chains.length == 0) {
if (currentThread != null) {
Util.d(TAG, "interrupt thread with cancel operation because of chains are not running " + task.getId());
currentThread.interrupt();
}
} else {
for (Object chain : chains) {
if (chain instanceof DownloadChain) {
((DownloadChain) chain).cancel();
}
}
}
if (cache != null)
cache.getOutputStream().cancelAsync();
Util.d(TAG, "cancel task " + task.getId() + " consume: " + (SystemClock.uptimeMillis() - startCancelTime) + "ms");
return true;
}
19
Source : ConnectTrial.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
// if instance length is can't certain through transfer-encoding and content-range but the
// content-length is exist but can't be used, we will request HEAD method request to find out
// right one.
void trialHeadMethodForInstanceLength() throws IOException {
final DownloadConnection connection = OkDownload.with().connectionFactory().create(task.getUrl());
final DownloadListener listener = OkDownload.with().callbackDispatcher().dispatch();
try {
connection.setRequestMethod(METHOD_HEAD);
final Map<String, List<String>> userHeader = task.getHeaderMapFields();
if (userHeader != null)
Util.addUserRequestHeaderField(userHeader, connection);
listener.connectTrialStart(task, connection.getRequestProperties());
final DownloadConnection.Connected connectedForContentLength = connection.execute();
listener.connectTrialEnd(task, connectedForContentLength.getResponseCode(), connectedForContentLength.getResponseHeaderFields());
this.instanceLength = Util.parseContentLength(connectedForContentLength.getResponseHeaderField(CONTENT_LENGTH));
} finally {
connection.release();
}
}
19
Source : ConnectTrial.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
public void executeTrial() throws IOException {
OkDownload.with().downloadStrategy().inspectNetworkOnWifi(task);
OkDownload.with().downloadStrategy().inspectNetworkAvailable();
DownloadConnection connection = OkDownload.with().connectionFactory().create(task.getUrl());
boolean isNeedTrialHeadMethod;
try {
if (!Util.isEmpty(info.getEtag())) {
connection.addHeader(IF_MATCH, info.getEtag());
}
connection.addHeader(RANGE, "bytes=0-0");
final Map<String, List<String>> userHeader = task.getHeaderMapFields();
if (userHeader != null)
Util.addUserRequestHeaderField(userHeader, connection);
final DownloadListener listener = OkDownload.with().callbackDispatcher().dispatch();
final Map<String, List<String>> requestProperties = connection.getRequestProperties();
listener.connectTrialStart(task, requestProperties);
final DownloadConnection.Connected connected = connection.execute();
task.setRedirectLocation(connected.getRedirectLocation());
Util.d(TAG, "task[" + task.getId() + "] redirect location: " + task.getRedirectLocation());
this.responseCode = connected.getResponseCode();
this.acceptRange = isAcceptRange(connected);
this.instanceLength = findInstanceLength(connected);
this.responseEtag = findEtag(connected);
this.responseFilename = findFilename(connected);
Map<String, List<String>> responseHeader = connected.getResponseHeaderFields();
if (responseHeader == null)
responseHeader = new HashMap<>();
listener.connectTrialEnd(task, responseCode, responseHeader);
isNeedTrialHeadMethod = isNeedTrialHeadMethodForInstanceLength(instanceLength, connected);
} finally {
connection.release();
}
if (isNeedTrialHeadMethod) {
trialHeadMethodForInstanceLength();
}
}
19
Source : BreakpointRemoteCheck.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
public void check() throws IOException {
// local etag
final DownloadStrategy downloadStrategy = OkDownload.with().downloadStrategy();
// execute trial
ConnectTrial connectTrial = createConnectTrial();
connectTrial.executeTrial();
// single/multi
final boolean isAcceptRange = connectTrial.isAcceptRange();
final boolean isChunked = connectTrial.isChunked();
// data
final long instanceLength = connectTrial.getInstanceLength();
final String responseEtag = connectTrial.getResponseEtag();
final String responseFilename = connectTrial.getResponseFilename();
final int responseCode = connectTrial.getResponseCode();
// 1. replacedemble basic data.
downloadStrategy.validFilenameFromResponse(responseFilename, task, info);
info.setChunked(isChunked);
info.setEtag(responseEtag);
if (OkDownload.with().downloadDispatcher().isFileConflictAfterRun(task)) {
throw FileBusyAfterRunException.SIGNAL;
}
// 2. collect result
final ResumeFailedCause resumeFailedCause = downloadStrategy.getPreconditionFailedCause(responseCode, info.getTotalOffset() != 0, info, responseEtag);
this.resumable = resumeFailedCause == null;
this.failedCause = resumeFailedCause;
this.instanceLength = instanceLength;
this.acceptRange = isAcceptRange;
// 3. check whether server cancelled.
if (!isTrialSpecialPreplaced(responseCode, instanceLength, resumable) && downloadStrategy.isServerCanceled(responseCode, info.getTotalOffset() != 0)) {
throw new ServerCanceledException(responseCode, info.getTotalOffset());
}
}
19
Source : BreakpointLocalCheck.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
public boolean isOutputStreamSupportResume() {
final boolean supportSeek = OkDownload.with().outputStreamFactory().supportSeek();
if (supportSeek)
return true;
if (info.getBlockCount() != 1)
return false;
if (OkDownload.with().processFileStrategy().isPreAllocateLength(task))
return false;
return true;
}
19
Source : DownloadDispatcher.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
public static void setMaxParallelRunningCount(int maxParallelRunningCount) {
DownloadDispatcher dispatcher = OkDownload.with().downloadDispatcher();
if (dispatcher.getClreplaced() != DownloadDispatcher.clreplaced) {
throw new IllegalStateException("The current dispatcher is " + dispatcher + " not DownloadDispatcher exactly!");
}
maxParallelRunningCount = Math.max(1, maxParallelRunningCount);
dispatcher.maxParallelRunningCount = maxParallelRunningCount;
}
18
Source : FileDownloader.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
public void pause(final FileDownloadListener listener) {
final List<DownloadTaskAdapter> taskAdapters = FileDownloadList.getImpl().getByFileDownloadListener(listener);
final DownloadTask[] downloadTasks = new DownloadTask[taskAdapters.size()];
for (int i = 0; i < taskAdapters.size(); i++) {
downloadTasks[i] = taskAdapters.get(i).getDownloadTask();
}
OkDownload.with().downloadDispatcher().cancel(downloadTasks);
}
18
Source : FileDownloader.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
/**
* Get downloaded bytes so far by the downloadId.
*/
public long getSoFar(final int downloadId) {
final BreakpointInfo info = OkDownload.with().breakpointStore().get(downloadId);
if (info == null)
return 0;
return info.getTotalOffset();
}
18
Source : DownloadTaskAdapter.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Override
public boolean isRunning() {
if (downloadTask == null) {
return false;
} else {
return OkDownload.with().downloadDispatcher().isRunning(downloadTask);
}
}
18
Source : DownloadTaskAdapter.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Override
public boolean cancel() {
if (downloadTask == null) {
return true;
} else {
return OkDownload.with().downloadDispatcher().cancel(downloadTask);
}
}
18
Source : MultiPointOutputStreamTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void cancel() throws IOException {
multiPointOutputStream.requireStreamBlocks = new ArrayList<Integer>() {
{
add(0);
add(1);
}
};
multiPointOutputStream.noSyncLengthMap.put(0, new AtomicLong());
multiPointOutputStream.noSyncLengthMap.put(1, new AtomicLong());
multiPointOutputStream.allNoSyncLength.set(1);
final ProcessFileStrategy strategy = OkDownload.with().processFileStrategy();
final FileLock fileLock = mock(FileLock.clreplaced);
when(strategy.getFileLock()).thenReturn(fileLock);
doNothing().when(multiPointOutputStream).close(anyInt());
doNothing().when(multiPointOutputStream).ensureSync(true, -1);
multiPointOutputStream.cancel();
replacedertThat(multiPointOutputStream.noMoreStreamList).containsExactly(0, 1);
verify(multiPointOutputStream).ensureSync(eq(true), eq(-1));
verify(multiPointOutputStream).close(eq(0));
verify(multiPointOutputStream).close(eq(1));
verify(fileLock).increaseLock(eq(existFile.getAbsolutePath()));
verify(fileLock).decreaseLock(eq(existFile.getAbsolutePath()));
verify(store).onTaskEnd(eq(task.getId()), eq(EndCause.CANCELED), nullable(Exception.clreplaced));
}
18
Source : MultiPointOutputStreamTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void cancel_syncNotRun_withSyncFutureHasDone() throws IOException {
multiPointOutputStream.requireStreamBlocks = new ArrayList<Integer>() {
{
add(0);
add(1);
}
};
multiPointOutputStream.allNoSyncLength.set(1);
doNothing().when(multiPointOutputStream).close(anyInt());
doNothing().when(multiPointOutputStream).ensureSync(true, -1);
multiPointOutputStream.syncFuture = mock(Future.clreplaced);
when(multiPointOutputStream.syncFuture.isDone()).thenReturn(true);
final ProcessFileStrategy strategy = OkDownload.with().processFileStrategy();
final FileLock fileLock = mock(FileLock.clreplaced);
when(strategy.getFileLock()).thenReturn(fileLock);
multiPointOutputStream.cancel();
replacedertThat(multiPointOutputStream.noMoreStreamList).containsExactly(0, 1);
verify(multiPointOutputStream, never()).ensureSync(eq(true), eq(-1));
verify(multiPointOutputStream).close(eq(0));
verify(multiPointOutputStream).close(eq(1));
verify(fileLock, never()).increaseLock(eq(existFile.getAbsolutePath()));
verify(fileLock, never()).decreaseLock(eq(existFile.getAbsolutePath()));
verify(store).onTaskEnd(eq(task.getId()), eq(EndCause.CANCELED), nullable(Exception.clreplaced));
}
18
Source : MultiPointOutputStreamTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void cancel_syncNotRun_withSyncFutureIsNull() throws IOException {
multiPointOutputStream.requireStreamBlocks = new ArrayList<Integer>() {
{
add(0);
add(1);
}
};
multiPointOutputStream.allNoSyncLength.set(1);
doNothing().when(multiPointOutputStream).close(anyInt());
doNothing().when(multiPointOutputStream).ensureSync(true, -1);
multiPointOutputStream.syncFuture = null;
final ProcessFileStrategy strategy = OkDownload.with().processFileStrategy();
final FileLock fileLock = mock(FileLock.clreplaced);
when(strategy.getFileLock()).thenReturn(fileLock);
multiPointOutputStream.cancel();
replacedertThat(multiPointOutputStream.noMoreStreamList).containsExactly(0, 1);
verify(multiPointOutputStream, never()).ensureSync(eq(true), eq(-1));
verify(multiPointOutputStream).close(eq(0));
verify(multiPointOutputStream).close(eq(1));
verify(fileLock, never()).increaseLock(eq(existFile.getAbsolutePath()));
verify(fileLock, never()).decreaseLock(eq(existFile.getAbsolutePath()));
verify(store).onTaskEnd(eq(task.getId()), eq(EndCause.CANCELED), nullable(Exception.clreplaced));
}
18
Source : DownloadStrategyTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void validFilenameFromStore() {
final DownloadStrategy.FilenameHolder holder = new DownloadStrategy.FilenameHolder();
when(task.getUrl()).thenReturn("url");
when(task.getFilenameHolder()).thenReturn(holder);
final BreakpointStore store = OkDownload.with().breakpointStore();
doReturn(null).when(store).getResponseFilename("url");
replacedertThat(strategy.validFilenameFromStore(task)).isFalse();
replacedertThat(holder.get()).isNull();
doReturn("filename").when(store).getResponseFilename("url");
replacedertThat(strategy.validFilenameFromStore(task)).isTrue();
replacedertThat(holder.get()).isEqualTo("filename");
}
18
Source : DownloadStrategyTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void resumeAvailableResponseCheck_notPartialAndOk() throws IOException {
mockOkDownload();
doReturn(spy(DownloadStrategy.clreplaced)).when(OkDownload.with()).downloadStrategy();
final DownloadStrategy.ResumeAvailableResponseCheck responseCheck = resumeAvailableResponseCheck();
when(connected.getResponseCode()).thenReturn(501);
when(info.getBlock(0)).thenReturn(mock(BlockInfo.clreplaced));
expectServerCancelled(501, 0);
responseCheck.inspect();
}
18
Source : DownloadCallTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void execute_replacedembleBlockData() throws InterruptedException, IOException {
setupFileStrategy();
final ProcessFileStrategy fileStrategy = OkDownload.with().processFileStrategy();
final BreakpointLocalCheck localCheck = mock(BreakpointLocalCheck.clreplaced);
final BreakpointRemoteCheck remoteCheck = mock(BreakpointRemoteCheck.clreplaced);
final ResumeFailedCause failedCauseByRemote = mock(ResumeFailedCause.clreplaced);
final ResumeFailedCause failedCauseByLocal = mock(ResumeFailedCause.clreplaced);
doReturn(remoteCheck).when(call).createRemoteCheck(eq(info));
doReturn(localCheck).when(call).createLocalCheck(eq(info), anyLong());
doReturn(failedCauseByRemote).when(remoteCheck).getCauseOrThrow();
doReturn(failedCauseByLocal).when(localCheck).getCauseOrThrow();
doNothing().when(call).replacedembleBlockAndCallbackFromBeginning(eq(info), eq(remoteCheck), any(ResumeFailedCause.clreplaced));
doNothing().when(call).start(any(DownloadCache.clreplaced), eq(info));
when(remoteCheck.isResumable()).thenReturn(false);
call.execute();
verify(call).replacedembleBlockAndCallbackFromBeginning(eq(info), eq(remoteCheck), eq(failedCauseByRemote));
verify(fileStrategy).discardProcess(eq(task));
when(remoteCheck.isResumable()).thenReturn(true);
when(localCheck.isDirty()).thenReturn(false);
call.execute();
verify(call, never()).replacedembleBlockAndCallbackFromBeginning(eq(info), eq(remoteCheck), eq(failedCauseByLocal));
// callback download from breakpoint.
final DownloadListener listener = OkDownload.with().callbackDispatcher().dispatch();
verify(listener).downloadFromBreakpoint(eq(task), eq(info));
when(localCheck.isDirty()).thenReturn(true);
call.execute();
verify(call).replacedembleBlockAndCallbackFromBeginning(eq(info), eq(remoteCheck), eq(failedCauseByLocal));
verify(fileStrategy, times(2)).discardProcess(eq(task));
}
18
Source : DownloadCallTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void execute_preconditionFailed() throws InterruptedException, IOException {
setupFileStrategy();
final DownloadCache cache = mock(DownloadCache.clreplaced);
doReturn(cache).when(call).createCache(eq(info));
when(cache.isPreconditionFailed()).thenReturn(true, false);
final ResumeFailedCause resumeFailedCause = mock(ResumeFailedCause.clreplaced);
doReturn(resumeFailedCause).when(cache).getResumeFailedCause();
doNothing().when(call).start(eq(cache), eq(info));
doReturn(mock(BreakpointRemoteCheck.clreplaced)).when(call).createRemoteCheck(eq(info));
doReturn(mock(BreakpointLocalCheck.clreplaced)).when(call).createLocalCheck(eq(info), anyLong());
call.execute();
verify(call, times(2)).start(eq(cache), eq(info));
final ProcessFileStrategy fileStrategy = OkDownload.with().processFileStrategy();
final int id = task.getId();
verify(store).remove(eq(id));
verify(fileStrategy, times(2)).discardProcess(eq(task));
}
18
Source : DownloadCallTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void cancel_finishing() {
call.finishing = true;
replacedertThat(call.cancel()).isFalse();
final DownloadDispatcher dispatcher = OkDownload.with().downloadDispatcher();
verify(dispatcher, never()).flyingCanceled(eq(call));
}
18
Source : BreakpointLocalCheckTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void isOutputStreamSupportResume_notSupport() throws IOException {
mockOkDownload();
final DownloadOutputStream.Factory factory = OkDownload.with().outputStreamFactory();
when(factory.supportSeek()).thenReturn(false);
when(info.getBlockCount()).thenReturn(2);
replacedertThat(check.isOutputStreamSupportResume()).isFalse();
when(info.getBlockCount()).thenReturn(1);
// pre allocate length but not support seek
final ProcessFileStrategy strategy = OkDownload.with().processFileStrategy();
doReturn(true).when(strategy).isPreAllocateLength(task);
replacedertThat(check.isOutputStreamSupportResume()).isFalse();
}
18
Source : BreakpointLocalCheckTest.java
with Apache License 2.0
from lingochamp
with Apache License 2.0
from lingochamp
@Test
public void isOutputStreamSupportResume_support() throws IOException {
mockOkDownload();
// support seek
final DownloadOutputStream.Factory factory = OkDownload.with().outputStreamFactory();
when(factory.supportSeek()).thenReturn(true);
replacedertThat(check.isOutputStreamSupportResume()).isTrue();
// not support seek
when(factory.supportSeek()).thenReturn(false);
// just one block
when(info.getBlockCount()).thenReturn(1);
// not pre allocate length
final ProcessFileStrategy strategy = OkDownload.with().processFileStrategy();
when(strategy.isPreAllocateLength(task)).thenReturn(false);
replacedertThat(check.isOutputStreamSupportResume()).isTrue();
}
See More Examples