private void trimToSize() throws IOException {
   while (size > maxSize) {
     //            Map.Entry<String, Entry> toEvict = lruEntries.eldest();
     final Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next();
     Logger.d(
         BitmapLoader.class.getSimpleName(),
         "清理缓存文件size=" + size + ",maxSize=" + maxSize + ",file=" + toEvict.getKey());
     remove(toEvict.getKey());
   }
 }
示例#2
0
  /**
   * 点赞
   *
   * @param statusId
   * @param like
   * @param cookie
   * @return
   * @throws TaskException
   */
  public LikeResultBean doLike(String statusId, boolean like, String cookie) throws TaskException {
    try {
      String url =
          like ? "http://m.weibo.cn/attitudesDeal/add" : "http://m.weibo.cn/attitudesDeal/delete";

      Map<String, String> cookieMap = new HashMap<String, String>();

      String[] cookieValues = cookie.split(";");
      for (String cookieValue : cookieValues) {
        String key = cookieValue.split("=")[0];
        String value = cookieValue.split("=")[1];

        cookieMap.put(key, value);
      }
      //            Logger.d(WeiboClientActivity.TAG, cookieMap);

      Connection connection = Jsoup.connect(url);
      connection
          .userAgent(
              "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:33.0) Gecko/20100101 Firefox/33.0")
          .referrer("http://m.weibo.cn/")
          .cookies(cookieMap)
          .data("id", statusId)
          .method(Connection.Method.POST);
      if (like) connection.data("attitude", "heart");

      String body = connection.execute().body();
      if (!TextUtils.isEmpty(body)) {
        Logger.d(TAG, body);

        if (body.indexOf("http://passport.weibo.cn/sso/crossdomain") != -1)
          throw new TaskException("-100", "未登录");
        else if (body.indexOf("<html") != -1) throw new TaskException("-100", "未登录");

        LikeResultBean likeBean = JSON.parseObject(body, LikeResultBean.class);
        if (likeBean.getOk() == 1) {
          return likeBean;
        } else if (likeBean.getOk() == -100) {
          throw new TaskException("-100", "未登录");
        } else {
          throw new TaskException("", likeBean.getMsg());
        }
      }
    } catch (Exception e) {
      if (e instanceof TaskException) throw (TaskException) e;

      e.printStackTrace();
    }

    throw new TaskException(TaskException.TaskError.timeout.toString());
  }
  private synchronized void completeEdit(Editor editor, boolean success) throws IOException {
    Entry entry = editor.entry;
    if (entry.currentEditor != editor) {
      throw new IllegalStateException();
    }

    // if this edit is creating the entry for the first time, every index
    // must have a value
    if (success && !entry.readable) {
      for (int i = 0; i < valueCount; i++) {
        if (!entry.getDirtyFile(i).exists()) {
          editor.abort();
          throw new IllegalStateException("edit didn't create file " + i);
        }
      }
    }

    for (int i = 0; i < valueCount; i++) {
      File dirty = entry.getDirtyFile(i);
      if (success) {
        if (dirty.exists()) {
          File clean = entry.getCleanFile(i);
          dirty.renameTo(clean);
          long oldLength = entry.lengths[i];
          long newLength = clean.length();
          entry.lengths[i] = newLength;
          size = size - oldLength + newLength;
        }
      } else {
        Logger.d(BitmapLoader.class.getSimpleName(), "completeEdit");
        deleteIfExists(dirty);
      }
    }

    redundantOpCount++;
    entry.currentEditor = null;
    if (entry.readable | success) {
      entry.readable = true;
      journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
      if (success) {
        entry.sequenceNumber = nextSequenceNumber++;
      }
    } else {
      lruEntries.remove(entry.key);
      journalWriter.write(REMOVE + ' ' + entry.key + '\n');
    }

    if (size > maxSize || journalRebuildRequired()) {
      executorService.submit(cleanupCallable);
    }
  }
示例#4
0
    @Override
    protected void onSuccess(WeiBoUser result) {
      super.onSuccess(result);

      Logger.d(TAG, "授权成功");

      BaiduAnalyzeUtils.onEvent("add_account", "添加授权账号");

      showMessage(R.string.account_auth_success);

      if (getActivity() != null) {
        getActivity().finish();
      }
    }
 private static void deleteIfExists(File file) throws IOException {
   //        try {
   //            Libcore.os.remove(file.getPath());
   //        } catch (ErrnoException errnoException) {
   //            if (errnoException.errno != OsConstants.ENOENT) {
   //                throw errnoException.rethrowAsIOException();
   //            }
   //        }
   Logger.d(BitmapLoader.class.getSimpleName(), "deleteIfExists file = " + file.getName());
   // FIXME 把删除文件的操作注释掉了
   //		if (file.exists() && !file.delete()) {
   //			throw new IOException();
   //		}
 }
 // TODO: this should specify paths as Strings rather than as Files
 public static void deleteContents(File dir) throws IOException {
   File[] files = dir.listFiles();
   if (files == null) {
     throw new IllegalArgumentException("not a directory: " + dir);
   }
   for (File file : files) {
     if (file.isDirectory()) {
       deleteContents(file);
     }
     if (!file.delete()) {
       throw new IOException("failed to delete file: " + file);
     }
     Logger.d(BitmapLoader.class.getSimpleName(), "deleteContents file = " + file.getName());
   }
 }
  private void readJournal() throws IOException {
    InputStream in = new BufferedInputStream(new FileInputStream(journalFile), IO_BUFFER_SIZE);
    try {
      String magic = readAsciiLine(in);
      String version = readAsciiLine(in);
      String appVersionString = readAsciiLine(in);
      String valueCountString = readAsciiLine(in);
      String blank = readAsciiLine(in);
      if (!MAGIC.equals(magic)
          || !VERSION_1.equals(version)
          || !Integer.toString(appVersion).equals(appVersionString)
          || !Integer.toString(valueCount).equals(valueCountString)
          || !"".equals(blank)) {
        Logger.d(
            BitmapLoader.TAG,
            "unexpected journal header: ["
                + magic
                + ", "
                + version
                + ", "
                + valueCountString
                + ", "
                + blank
                + "]");
        throw new IOException(
            "unexpected journal header: ["
                + magic
                + ", "
                + version
                + ", "
                + valueCountString
                + ", "
                + blank
                + "]");
      }

      while (true) {
        try {
          readJournalLine(readAsciiLine(in));
        } catch (EOFException endOfJournal) {
          endOfJournal.printStackTrace();
          break;
        }
      }
    } finally {
      closeQuietly(in);
    }
  }
示例#8
0
  /**
   * 触发一次离线,如果没有设置过离线分组,优先设置后再离线
   *
   * @param context
   */
  public static void toggleOffline(final Activity context) {
    if (!AppContext.isLogedin()) return;

    List<Group> groups =
        SinaDB.getOfflineSqlite()
            .select(new Extra(AppContext.getUser().getIdstr(), null), Group.class);
    if (groups.size() == 0) {
      Logger.d(TAG, "离线分组未设置过");

      new AlertDialogWrapper.Builder(context)
          .setMessage(R.string.offline_none_groups_remind)
          .setNegativeButton(R.string.cancel, null)
          .setPositiveButton(
              R.string.yes,
              new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                  showOfflineGroupsModifyDialog(
                      context,
                      new ArrayList<Group>(),
                      new OnOfflineGroupSetCallback() {

                        @Override
                        public void onChanged(List<Group> newGroups) {
                          // 设置离线分组
                          Logger.d(TAG, "设置离线分组%d个", newGroups.size());

                          if (newGroups.size() > 0) {
                            SinaDB.getOfflineSqlite().insert(getLoggedExtra(null), newGroups);

                            toggleOffline(context);
                          }
                        }
                      },
                      R.string.offline_groups_dialog);
                }
              })
          .show();
    } else {
      OfflineService.startOffline((ArrayList) groups);
    }
  }
 /**
  * Computes the initial size and collects garbage as a part of opening the cache. Dirty entries
  * are assumed to be inconsistent and will be deleted.
  */
 private void processJournal() throws IOException {
   deleteIfExists(journalFileTmp);
   for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) {
     Entry entry = i.next();
     if (entry.currentEditor == null) {
       for (int t = 0; t < valueCount; t++) {
         size += entry.lengths[t];
         Logger.d(BitmapLoader.class.getSimpleName(), entry.getCleanFile(0).getName());
       }
     } else {
       entry.currentEditor = null;
       for (int t = 0; t < valueCount; t++) {
         deleteIfExists(entry.getCleanFile(t));
         deleteIfExists(entry.getDirtyFile(t));
       }
       i.remove();
     }
   }
 }
  /**
   * Opens the cache in {@code directory}, creating a cache if none exists there.
   *
   * @param directory a writable directory
   * @param appVersion
   * @param valueCount the number of values per cache entry. Must be positive.
   * @param maxSize the maximum number of bytes this cache should use to store
   * @throws IOException if reading or writing the cache directory fails
   */
  public static LruDiskCache open(File directory, int appVersion, int valueCount, long maxSize)
      throws IOException {
    if (maxSize <= 0) {
      throw new IllegalArgumentException("maxSize <= 0");
    }
    if (valueCount <= 0) {
      throw new IllegalArgumentException("valueCount <= 0");
    }

    // prefer to pick up where we left off
    LruDiskCache cache = new LruDiskCache(directory, appVersion, valueCount, maxSize);
    if (cache.journalFile.exists()) {
      Logger.d(BitmapLoader.TAG, "journalFile exists");
      try {
        cache.readJournal();
        cache.refreshJournal();
        cache.processJournal();
        cache.journalWriter =
            new BufferedWriter(new FileWriter(cache.journalFile, true), IO_BUFFER_SIZE);
        return cache;
      } catch (IOException journalIsCorrupt) {
        journalIsCorrupt.printStackTrace();
        //                System.logW("DiskLruCache " + directory + " is corrupt: "
        //                        + journalIsCorrupt.getMessage() + ", removing");
        //				cache.delete();
        cache.journalFile.delete();
      }
    }

    // create a new empty cache
    directory.mkdirs();
    cache = new LruDiskCache(directory, appVersion, valueCount, maxSize);
    cache.rebuildJournal();
    cache.readJournal();
    cache.refreshJournal();
    cache.processJournal();
    return cache;
  }