use of org.aisen.android.network.task.TaskException in project AisenWeiBo by wangdan.
the class ABizLogic method doGet.
@Override
public <T> T doGet(HttpConfig config, Setting action, Params params, Class<T> responseCls) throws TaskException {
// 缓存器
ICacheUtility cacheUtility = null;
// 返回的缓存
T cache = null;
// 配置的缓存模式
if (action.getExtras().containsKey(CACHE_UTILITY)) {
if (!TextUtils.isEmpty(action.getExtras().get(CACHE_UTILITY).getValue())) {
try {
cacheUtility = (ICacheUtility) Class.forName(action.getExtras().get(CACHE_UTILITY).getValue()).newInstance();
} catch (Exception e) {
Logger.w(getTag(action, "Get"), "CacheUtility 配置错误");
}
}
} else {
Logger.v(getTag(action, "Get"), "CacheUtility 没有配置");
}
if (mCacheMode != CacheMode.disable) {
// 拉取缓存数据
if (cacheUtility != null) {
long time = System.currentTimeMillis();
cache = (T) cacheUtility.findCacheData(action, params);
if (cache != null) {
Logger.d(getTag(action, "Cache"), "读取缓存耗时 %s ms", String.valueOf(System.currentTimeMillis() - time));
}
}
}
// 缓存不存在、服务数据优先等情况下,拉取服务数据
if (cache == null || mCacheMode == CacheMode.servicePriority) {
try {
long time = System.currentTimeMillis();
T result = getHttpUtility(action).doGet(resetHttpConfig(config, action), action, params, responseCls);
Logger.d(getTag(action, "Get-Http"), "耗时 %s ms", String.valueOf(System.currentTimeMillis() - time));
if (result != null && result instanceof IResult) {
putToCache(action, params, (IResult) result, cacheUtility);
}
Logger.d(getTag(action, "Get-Http"), "返回服务器数据");
return result;
} catch (TaskException e) {
Logger.w(getTag(action, "Exception"), e + "");
throw e;
} catch (Exception e) {
Logger.w(getTag(action, "Exception"), e + "");
throw new TaskException(TextUtils.isEmpty(e.getMessage()) ? "服务器错误" : e.getMessage());
}
} else {
if (cache != null) {
Logger.d(getTag(action, "Cache"), "返回缓存数据");
// 缓存存在,且有效
return cache;
}
}
throw null;
}
use of org.aisen.android.network.task.TaskException in project AisenWeiBo by wangdan.
the class DefHttpUtility method executeRequest.
private <T> T executeRequest(Request request, Class<T> responseCls, Setting action, String method) throws TaskException {
try {
if (SettingUtility.getPermanentSettingAsInt("http_delay") > 0) {
Thread.sleep(SettingUtility.getPermanentSettingAsInt("http_delay"));
}
} catch (Throwable e) {
}
try {
Response response = getOkHttpClient().newCall(request).execute();
Logger.w(getTag(action, method), "Http-code = %d", response.code());
if (!(response.code() == HttpURLConnection.HTTP_OK || response.code() == HttpURLConnection.HTTP_PARTIAL)) {
String responseStr = response.body().string();
if (Logger.DEBUG) {
Logger.w(getTag(action, method), responseStr);
}
TaskException.checkResponse(responseStr);
throw new TaskException(TaskException.TaskError.timeout.toString());
} else {
String responseStr = response.body().string();
Logger.v(getTag(action, method), "Response = %s", responseStr);
return parseResponse(responseStr, responseCls);
}
} catch (SocketTimeoutException e) {
Logger.printExc(DefHttpUtility.class, e);
Logger.w(getTag(action, method), e + "");
throw new TaskException(TaskException.TaskError.timeout.toString());
} catch (IOException e) {
Logger.printExc(DefHttpUtility.class, e);
Logger.w(getTag(action, method), e + "");
throw new TaskException(TaskException.TaskError.timeout.toString());
} catch (TaskException e) {
Logger.printExc(DefHttpUtility.class, e);
Logger.w(getTag(action, method), e + "");
throw e;
} catch (Exception e) {
Logger.printExc(DefHttpUtility.class, e);
Logger.w(getTag(action, method), e + "");
throw new TaskException(TaskException.TaskError.resultIllegal.toString());
}
}
use of org.aisen.android.network.task.TaskException in project AisenWeiBo by wangdan.
the class PictureFragment method onPublish.
@Override
public void onPublish(final DownloadMsg downloadMsg) {
this.downloadMsg = downloadMsg;
int status = downloadMsg.getStatus();
if (downloadMsg.isNull()) {
} else // 失败
if (status == DownloadManager.STATUS_FAILED) {
if (getActivity() != null) {
Snackbar.make(layError, "下载失败:" + downloadMsg.getReason() + "", Snackbar.LENGTH_LONG).setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View v) {
DownloadManager.getInstance().resume(downloadMsg.getKey());
}
}).show();
}
} else // 成功
if (status == DownloadManager.STATUS_SUCCESSFUL) {
if (getActivity() != null) {
final File file = BitmapLoader.getInstance().getCacheFile(getOrigImage());
new WorkTask<Void, Void, byte[]>() {
@Override
public byte[] workInBackground(Void... params) throws TaskException {
Logger.d("Download-Picture", downloadMsg.getFilePath().toString());
return FileUtils.readFileToBytes(file);
}
@Override
protected void onSuccess(byte[] bytes) {
super.onSuccess(bytes);
onDownloadPicture(bytes, file);
}
}.execute();
getActivity().invalidateOptionsMenu();
}
} else // 暂停
if (status == DownloadManager.STATUS_PAUSED) {
if (getActivity() != null) {
getActivity().invalidateOptionsMenu();
}
} else // 等待
if (status == DownloadManager.STATUS_PENDING || status == DownloadManager.STATUS_WAITING) {
if (getActivity() != null) {
getActivity().invalidateOptionsMenu();
}
} else // 下载中
if (status == DownloadManager.STATUS_RUNNING) {
if (getActivity() != null) {
getActivity().invalidateOptionsMenu();
}
}
}
use of org.aisen.android.network.task.TaskException in project AisenWeiBo by wangdan.
the class PictureFragment method downloadImage.
private void downloadImage() {
new IAction(getActivity(), new SdcardPermissionAction((BaseActivity) getActivity(), null)) {
@Override
public void doAction() {
new WorkTask<Void, Void, String>() {
@Override
protected void onPrepare() {
super.onPrepare();
ViewUtils.createProgressDialog(getActivity(), getString(R.string.msg_save_pic_loading), ThemeUtils.getThemeColor()).show();
}
private void notifyFileSys(File file) {
SystemUtils.scanPhoto(getActivity(), file);
}
@Override
public String workInBackground(Void... params) throws TaskException {
File file = origFile;
if (!file.exists())
file = BitmapLoader.getInstance().getCacheFile(getImage());
String path = SystemUtils.getSdcardPath() + File.separator + AppSettings.getImageSavePath() + File.separator + file.getName();
File newFile = new File(path);
if (!newFile.exists()) {
if (!newFile.getParentFile().exists())
newFile.getParentFile().mkdirs();
try {
FileUtils.copyFile(file, newFile);
notifyFileSys(newFile);
return newFile.getParentFile().getAbsolutePath();
} catch (Exception e) {
}
} else {
notifyFileSys(newFile);
return newFile.getParentFile().getAbsolutePath();
}
return null;
}
@Override
protected void onSuccess(String aBoolean) {
super.onSuccess(aBoolean);
if (!TextUtils.isEmpty(aBoolean)) {
showMessage(String.format(getString(R.string.msg_save_pic_success), aBoolean));
} else {
showMessage(R.string.msg_save_pic_faild);
}
}
@Override
protected void onFinished() {
super.onFinished();
ViewUtils.dismissProgressDialog();
}
}.execute();
}
}.run();
}
use of org.aisen.android.network.task.TaskException in project AisenWeiBo by wangdan.
the class WallpaperDownloadTask method doDownload.
// 下载壁纸
private File doDownload(File file) throws TaskException {
if (!isRunning())
throw new TaskException("-100", "");
// 判断网络是否连接
if (SystemUtils.getNetworkType(GlobalContext.getInstance()) == SystemUtils.NetWorkType.none) {
throw new TaskException("", mContext.getResources().getString(org.aisen.android.R.string.comm_error_none_network));
}
// 先下载一个临时文件
File tempFile = new File(file.getAbsolutePath() + ".tmp");
// 如果图片没有content-length
final int defaultLength = 8 * 1024 * 1024;
// 开始下载图片
try {
total = 0;
progress = 0;
// 发布进度
publishProgress(progress, total);
Logger.d(TAG, "开始下载壁纸 ---> %s", mImageUrl);
Request request = new Request.Builder().get().url(mImageUrl).build();
mCall = httpClient.newCall(request);
Response response = mCall.execute();
if (response == null) {
throw new TaskException(TaskException.TaskError.failIOError.toString());
}
int statusCode = response.code();
if (!(statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_PARTIAL)) {
throw new TaskException(TaskException.TaskError.failIOError.toString());
}
InputStream imageStream = null;
// 写临时文件
FileOutputStream out = new FileOutputStream(tempFile);
try {
String encoding = response.header("Content-Encoding");
if (encoding != null && !TextUtils.isEmpty(encoding) && "gzip".equals(encoding)) {
imageStream = new GZIPInputStream(response.body().byteStream());
Logger.w(TAG, "解压gzip文件, 解压前大小:");
} else {
imageStream = response.body().byteStream();
}
try {
total = response.body().contentLength();
} catch (Exception e) {
// 容错处理,如果未读到大小,默认为8M
total = defaultLength;
}
Logger.d(TAG, "Content-Length = " + total);
if (total < 0)
total = defaultLength;
// 获取图片数据
byte[] buffer = new byte[1024 * 8];
int readLen = -1;
long lastPublishTime = 0l;
while ((readLen = imageStream.read(buffer)) != -1) {
if (!isRunning())
throw new TaskException("-100", "");
progress += readLen;
out.write(buffer, 0, readLen);
Logger.v(TAG, "下载进度, %s / %s", getUnit(progress), getUnit(total));
// 发布进度
long now = System.currentTimeMillis();
if (now - lastPublishTime > PUBLISH_INTERVAL_TIME) {
lastPublishTime = now;
publishProgress(progress, total);
}
}
publishProgress(progress, progress);
Logger.d(TAG, "total : " + total + " readLen : " + readLen);
out.flush();
} catch (IOException e) {
Logger.printExc(WallpaperDownloadTask.class, e);
throw e;
} finally {
out.close();
if (imageStream != null)
imageStream.close();
}
// // 验证一下是否GZip压缩
// try {
// String encoding = response.header("Content-Encoding");
// if (encoding != null && !TextUtils.isEmpty(encoding) &&
// "gzip".equals(encoding)) {
// File ttf = tempFile;
// tempFile = decodeGZipFile(tempFile);
// ttf.delete();
// Logger.w(TAG, "解压gzip文件, 解压前大小:" + total + ", 解压后:" + tempFile.length());
// }
// } catch (Throwable e) {
// Logger.printExc(WallpaperDownloadTask.class, e);
// }
} catch (Throwable e) {
Logger.printExc(WallpaperDownloadTask.class, e);
throw new TaskException("", mContext.getResources().getString(R.string.down_faild));
}
Logger.d(TAG, "File-Length = " + tempFile.length());
Logger.d(TAG, "下载文件成功,path = " + tempFile.getAbsolutePath());
// 重命名之前,对临时文件,做一次图片校验,用BitmapFactory解析一下
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(tempFile.getAbsolutePath(), opts);
// 如果解析的宽高度小于1,默认为非图片
Logger.d(TAG, "图片解析尺寸 %s x %s", opts.outWidth, opts.outHeight);
if (opts.outWidth < 1 && opts.outHeight < 1) {
throw new TaskException("", mContext.getResources().getString(R.string.down_faild));
}
Logger.d(TAG, "下载壁纸完成");
if (!tempFile.renameTo(file))
throw new TaskException("", mContext.getResources().getString(R.string.down_faild));
return file;
}
Aggregations