br.com.objectos.way.base.io.UrlTimeoutValid Maven / Gradle / Ivy
/*
* Copyright 2014 Objectos, Fábrica de Software LTDA.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package br.com.objectos.way.base.io;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.google.common.base.Stopwatch;
/**
* @author [email protected] (Marcio Endo)
*/
class UrlTimeoutValid extends UrlTimeout {
private final long timeout;
private final TimeUnit unit;
public UrlTimeoutValid(Url url, long timeout, TimeUnit unit) {
super(url);
this.timeout = timeout;
this.unit = unit;
}
@Override
DataFile get(DataFile file) {
DataFile res = file;
Stopwatch stopwatch = Stopwatch.createStarted();
try {
url.onStart();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future future = executor.submit(new Task(file));
res = future.get(timeout, unit);
url.onSuccess(res);
} catch (InterruptedException e) {
url.onError(e);
} catch (ExecutionException e) {
url.onError(e);
} catch (TimeoutException e) {
url.onTimeout(timeout, unit);
} finally {
url.onFinish(stopwatch);
}
return res;
}
private class Task implements Callable {
private final DataFile file;
public Task(DataFile file) {
this.file = file;
}
@Override
public DataFile call() throws Exception {
UrlStream stream = url.toUrlStream();
return stream.saveTo(file);
}
}
}