예제 #1
0
 /**
  * Stores the state of the whiteboard for a given deck.
  *
  * @param state 1 if the whiteboard should be shown, 0 otherwise
  */
 public static void storeWhiteboardState(Context context, long did, boolean whiteboardState) {
   int state = (whiteboardState) ? 1 : 0;
   openDBIfClosed(context);
   Cursor cur = null;
   try {
     cur = mMetaDb.rawQuery("SELECT _id FROM whiteboardState" + " WHERE did  = " + did, null);
     if (cur.moveToNext()) {
       mMetaDb.execSQL(
           "UPDATE whiteboardState "
               + "SET did = "
               + did
               + ", "
               + "state="
               + Integer.toString(state)
               + " "
               + "WHERE _id="
               + cur.getString(0)
               + ";");
       Timber.d("Store whiteboard state (%d) for deck %d", state, did);
     } else {
       mMetaDb.execSQL(
           "INSERT INTO whiteboardState (did, state) VALUES (?, ?)", new Object[] {did, state});
       Timber.d("Store whiteboard state (%d) for deck %d", state, did);
     }
   } catch (Exception e) {
     Timber.e(e, "Error storing whiteboard state in MetaDB ");
   } finally {
     if (cur != null && !cur.isClosed()) {
       cur.close();
     }
   }
 }
예제 #2
0
 /**
  * Stores a custom dictionary for a given deck.
  *
  * @param dictionary integer number of dictionary, -1 if not set (standard dictionary will be
  *     used)
  */
 public static void storeLookupDictionary(Context context, long did, int dictionary) {
   openDBIfClosed(context);
   Cursor cur = null;
   try {
     cur = mMetaDb.rawQuery("SELECT _id FROM customDictionary" + " WHERE did = " + did, null);
     if (cur.moveToNext()) {
       mMetaDb.execSQL(
           "UPDATE customDictionary "
               + "SET did = "
               + did
               + ", "
               + "dictionary="
               + Integer.toString(dictionary)
               + " "
               + "WHERE _id="
               + cur.getString(0)
               + ";");
       Timber.i("MetaDB:: Store custom dictionary (%d) for deck %d", dictionary, did);
     } else {
       mMetaDb.execSQL(
           "INSERT INTO customDictionary (did, dictionary) VALUES (?, ?)",
           new Object[] {did, dictionary});
       Timber.i("MetaDB:: Store custom dictionary (%d) for deck %d", dictionary, did);
     }
   } catch (Exception e) {
     Timber.e(e, "Error storing custom dictionary to MetaDB ");
   } finally {
     if (cur != null && !cur.isClosed()) {
       cur.close();
     }
   }
 }
  private synchronized void loadSubscriptions() {
    mEnabledExtensions = new ArrayList<>();
    mSubscriptions = new HashMap<>();
    mTokens = new HashMap<>();

    String serializedSubscriptions = mSharedPrefs.getString(PREF_SUBSCRIPTIONS, null);
    if (serializedSubscriptions == null) {
      setDefaultEnabledExtensions();
      return;
    }

    JSONArray jsonArray;
    try {
      jsonArray = new JSONArray(serializedSubscriptions);
    } catch (JSONException e) {
      Timber.e(e, "Deserializing subscriptions failed");
      return;
    }

    for (int i = 0; i < jsonArray.length(); i++) {
      String subscription = jsonArray.optString(i, null);
      if (subscription == null) {
        continue;
      }
      String[] arr = subscription.split("\\|", 2);
      ComponentName extension = ComponentName.unflattenFromString(arr[0]);
      String token = arr[1];
      mEnabledExtensions.add(extension);
      mSubscriptions.put(extension, token);
      mTokens.put(token, extension);
      Timber.d("Restored subscription: " + extension + " token: " + token);
    }
  }
예제 #4
0
 /**
  * Returns the language associated with the given deck, model and card model, for the given type.
  *
  * @param qa the part of the card for which to store the association, {@link
  *     #LANGUAGES_QA_QUESTION}, {@link #LANGUAGES_QA_ANSWER}, or {@link #LANGUAGES_QA_UNDEFINED}
  *     return the language associate with the type, as a two-characters, lowercase string, or the
  *     empty string if no association is defined
  */
 public static String getLanguage(Context context, long did, int ord, int qa) {
   openDBIfClosed(context);
   String language = "";
   Cursor cur = null;
   try {
     String query =
         "SELECT language FROM languages "
             + "WHERE did = "
             + did
             + " AND ord = "
             + ord
             + " AND qa = "
             + qa
             + " "
             + "LIMIT 1";
     cur = mMetaDb.rawQuery(query, null);
     Timber.v("getLanguage: %s", query);
     if (cur.moveToNext()) {
       language = cur.getString(0);
     }
   } catch (Exception e) {
     Timber.e(e, "Error fetching language ");
   } finally {
     if (cur != null && !cur.isClosed()) {
       cur.close();
     }
   }
   return language;
 }
  private void enableExtension(ComponentName extension) {
    if (extension == null) {
      Timber.e("enableExtension: empty extension");
    }

    if (mSubscriptions.containsKey(extension)) {
      // already subscribed
      Timber.d("enableExtension: already subscribed to " + extension);
      return;
    }

    // subscribe
    String token = UUID.randomUUID().toString();
    while (mTokens.containsKey(token)) {
      // create another UUID on collision
      /**
       * As the number of enabled extensions is rather low compared to the UUID number space we
       * shouldn't have to worry about this ever looping.
       */
      token = UUID.randomUUID().toString();
    }
    Timber.d("enableExtension: subscribing to " + extension);
    mSubscriptions.put(extension, token);
    mTokens.put(token, extension);
    mContext.startService(
        new Intent(IncomingConstants.ACTION_SUBSCRIBE)
            .setComponent(extension)
            .putExtra(IncomingConstants.EXTRA_SUBSCRIBER_COMPONENT, mSubscriberComponentName)
            .putExtra(IncomingConstants.EXTRA_TOKEN, token));
  }
  public void handlePublishedAction(String token, Action action) {
    if (TextUtils.isEmpty(token) || action == null) {
      // whoops, no token or action received
      Timber.d("handlePublishedAction: token or action empty");
      return;
    }

    synchronized (this) {
      if (!mTokens.containsKey(token)) {
        // we are not subscribed, ignore
        Timber.d("handlePublishedAction: token invalid, ignoring incoming action");
        return;
      }

      // check if action episode identifier is for an episode we requested actions for
      Map<ComponentName, Action> actionMap = sEpisodeActionsCache.get(action.getEntityIdentifier());
      if (actionMap == null) {
        // did not request actions for this episode, or is already out of cache (too late!)
        Timber.d(
            "handlePublishedAction: not interested in actions for "
                + action.getEntityIdentifier()
                + ", ignoring incoming action");
        return;
      }
      // store action for this episode
      ComponentName extension = mTokens.get(token);
      actionMap.put(extension, action);
    }

    // notify that actions for an episode were updated
    EventBus.getDefault().post(new EpisodeActionReceivedEvent(action.getEntityIdentifier()));
  }
예제 #7
0
  /*
   * onConnected is called when our Activity successfully connects to Google
   * Play services. onConnected indicates that an account was selected on the
   * device, that the selected account has granted any requested permissions
   * to our app and that we were able to establish a service connection to
   * Google Play services.
   */
  @Override
  public void onConnected(Bundle connectionHint) {
    // Reaching onConnected means we consider the user signed in.
    Timber.i(TAG, "onConnected");

    // Update the user interface to reflect that the user is signed in.
    mSignInButton.setEnabled(false);
    mSignOutButton.setEnabled(true);
    mRevokeButton.setEnabled(true);

    // Retrieve some profile information to personalize our app for the
    // user.
    Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);

    Timber.i("UserInfo[" + currentUser.toString() + "]");
    Timber.i("ImageUrl[" + currentUser.getImage().getUrl() + "]");

    // mStatus.setText(String.format(getResources().getString(R.string.signed_in_as),
    // currentUser.getDisplayName()));
    // Plus.PeopleApi.loadVisible(mGoogleApiClient,
    // null).setResultCallback(this);

    // Indicate that the sign in process is complete.
    mSignInProgress = STATE_DEFAULT;

    // on successful login move to wall feed activity
    startActivity(new Intent(this, WallFeedActivity.class));
    // startActivity(new Intent(this, DummyActivity.class));
    // startActivity(new Intent(this, NewPictureActivity.class));
    LoginActivity.this.finish();
  }
    @Override
    protected void onPostExecute(SocialTwitterApi.GetRequest api) {
      super.onPostExecute(api);
      if (isDetached() || getActivity() == null) {
        return;
      }

      if (api.isSuccessful()) {
        ArrayList<FeedTwitterStatus> feed = api.getResponseObj().getStatusList();
        Collections.sort(feed);
        if (mTweetList.size() == 0) {
          // 新規取得
          mTweetList.addAll(feed);
        } else {
          FeedTwitterStatus latestTweet = mTweetList.get(0);
          // 取得済みの最新ツイートより新しいものを追加
          int index = Collections.binarySearch(feed, latestTweet);
          if (index > 0) {
            mTweetList.addAll(0, feed.subList(0, index));
          } else if (index < 0) {
            // indexが-1の時全部最新ツイート
            // -2以下の場合がないと想定
            Timber.d("onPostExecute: latestTweetIndex in new feed" + index);
            mTweetList.addAll(0, feed);
          } else {
            Timber.d("onPostExecute: already added");
          }
        }
        mAdapter.notifyDataSetChanged();
      }

      mSwipeRefreshLayout.setRefreshing(false);
    }
예제 #9
0
 public static void initialize(Application app) {
   Timber.d("{analytics enabled} Enabling Crashlytics");
   Timber.d("{analytics enabled} Enabling Answers");
   Fabric fabric =
       new Fabric.Builder(app).kits(new Crashlytics(), new Answers()).debuggable(true).build();
   Fabric.with(fabric);
 }
  @Override
  public void onReceive(Context context, Intent intent) {
    Timber.v("onReceive: %s", intent);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    if (!prefs.getBoolean(SettingsFragment.PREF_TOGGLE_WITH_FLITCHIO, true)) {
      Timber.i("Toggling with Flitchio is disabled");

      return;
    }

    final int statusCode = intent.getIntExtra(EXTRA_STATUS, Status.UNKNOWN);

    switch (statusCode) {
      case Status.CONNECTED:
        Timber.i("Flitchio has connected");

        if (!ServiceUtils.isServiceRunning(context, FlitchioBindingService.class)) {
          context.startService(new Intent(context, FlitchioBindingService.class));
        }
        break;
      case Status.DISCONNECTED:
        Timber.i("Flitchio has disconnected");

        context.sendBroadcast(new Intent(FlitchioBindingService.ACTION_STOP_SERVICE));
        break;
      default:
        Timber.wtf("Invalid intent: " + intent);
    }
  }
  public List<WiFiApConfig> getSortedWifiApConfigsList() {
    App.getTraceUtils().startTrace(TAG, "getSortedWifiApConfigsList", Log.DEBUG);

    if (getWifiNetworkStatus().isEmpty()) {
      updateWifiApConfigs();
      App.getTraceUtils()
          .partialTrace(TAG, "getSortedWifiApConfigsList", "updateWifiApConfigs", Log.DEBUG);
    }

    List<WiFiApConfig> list = null;

    synchronized (wifiNetworkStatusLock) {
      list = new ArrayList<WiFiApConfig>(getWifiNetworkStatus().values());
      App.getTraceUtils()
          .partialTrace(TAG, "getSortedWifiApConfigsList", "new ArrayList", Log.DEBUG);

      try {
        Collections.sort(list);
      } catch (IllegalArgumentException e) {
        Timber.e("config_list", configListToDBG().toString());
        Timber.e(e, "Exception during sort of WiFiAPConfigs");
      }
    }

    App.getTraceUtils()
        .partialTrace(TAG, "getSortedWifiApConfigsList", "Collections.sort", Log.DEBUG);
    App.getTraceUtils().stopTrace(TAG, "getSortedWifiApConfigsList", Log.DEBUG);

    return list;
  }
 private void debugOutput(List<Feature> features) {
   Timber.i(String.format("Got %s features", features.size()));
   for (Feature feature : features) {
     if (feature != null) {
       Timber.i(
           String.format(
               "Got feature %s with %s properties and Geometry %s",
               feature.getId(),
               feature.getProperties() != null
                   ? feature.getProperties().entrySet().size()
                   : "<null>",
               feature.getGeometry() != null
                   ? feature.getGeometry().getClass().getSimpleName()
                   : "<null>"));
       if (feature.getProperties() != null) {
         for (Map.Entry<String, JsonElement> entry : feature.getProperties().entrySet()) {
           Timber.i(String.format("Prop %s - %s", entry.getKey(), entry.getValue()));
         }
       }
     } else {
       // TODO Question: Why not formatting here??
       Timber.i("Got NULL feature %s");
     }
   }
 }
예제 #13
0
 /**
  * Stores the current state of the widget.
  *
  * <p>It replaces any stored state for the widget.
  *
  * @param decks an array of {@link DeckStatus} objects, one for each of the know decks.
  */
 public static void storeWidgetStatus(Context context, DeckStatus[] decks) {
   openDBIfClosed(context);
   try {
     mMetaDb.beginTransaction();
     try {
       // First clear all the existing content.
       mMetaDb.execSQL("DELETE FROM widgetStatus");
       for (DeckStatus deck : decks) {
         mMetaDb.execSQL(
             "INSERT INTO widgetStatus(deckId, deckName, newCards, lrnCards, dueCards, progress, eta) "
                 + "VALUES (?, ?, ?, ?, ?, ?, ?)",
             new Object[] {
               deck.mDeckId,
               deck.mDeckName,
               deck.mNewCards,
               deck.mLrnCards,
               deck.mDueCards,
               deck.mProgress,
               deck.mEta
             });
       }
       mMetaDb.setTransactionSuccessful();
     } finally {
       mMetaDb.endTransaction();
     }
   } catch (IllegalStateException e) {
     Timber.e(e, "MetaDB.storeWidgetStatus: failed");
   } catch (SQLiteException e) {
     Timber.e(e, "MetaDB.storeWidgetStatus: failed");
     closeDB();
     Timber.i("MetaDB:: Trying to reset Widget: " + resetWidget(context));
   }
 }
  /**
   * 转换PB数据
   *
   * @param response
   * @param clazz
   * @param <T>
   * @return
   * @throws Exception
   */
  public <T> List<T> parseProtobufResponse(PAppResponse response, Class<?> clazz) throws Exception {

    List<T> list = new ArrayList<T>();
    if (response.getDataCount() > 0) {

      Timber.d("%s parseProtobufResponse start: %s", this, System.currentTimeMillis());

      Method parseFrom = null;
      try {
        parseFrom = clazz.getMethod("parseFrom", ByteString.class);
      } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException(
            "Expected a protobuf message but was " + clazz.getName());
      }

      for (ByteString bytes : response.getDataList()) {

        try {

          Object o = parseFrom.invoke(null, bytes);
          list.add((T) o);

        } catch (InvocationTargetException e) {
          throw new ConversionException(clazz.getName() + ".parseFrom() failed", e.getCause());
        } catch (IllegalAccessException e) {
          throw new AssertionError();
        }
      }

      Timber.d("%s parseProtobufResponse end: %s", this, System.currentTimeMillis());
    }

    return list;
  }
 @Override
 public void execute(Bundle args) {
   try {
     Collection<CategoryItem> categories = radioApi.listPrimaryCategories();
     // FileRadioApi implementation returns null due to IOException
     if (categories == null) {
       syncResult.stats.numIoExceptions++;
     } else {
       ContentResolver contentResolver = context.getContentResolver();
       Cursor cursor =
           contentResolver.query(
               CategoryColumns.CONTENT_URI, CategoryColumns.ALL_COLUMNS, null, null, null);
       try {
         contentResolver.applyBatch(
             context.getString(R.string.content_authority), prepareBatch(cursor, categories));
       } catch (RemoteException e) {
         Timber.e(e, "RemoteException while sync of categories");
       } catch (OperationApplicationException e) {
         Timber.e(e, "OperationApplicationException while sync of categories");
         throw new IllegalStateException(e);
       }
     }
   } catch (RetrofitError error) {
     Timber.e(error, "Failed to sync categories");
     syncResult.stats.numIoExceptions++;
   }
 }
예제 #16
0
  @Override
  public synchronized Observable<AccessToken> registerForAccessTokenUpdates(String code) {
    Timber.d("registerForAccessTokenUpdates");
    if (loadAccessTokenSubscription == null || loadAccessTokenSubscription.isUnsubscribed()) {
      Timber.d("no loading in progress, starting new one");
      loadAccessTokenSubscription =
          loadAccessTokenObservable(code)
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe(
                  new DefaultSubscriber<AccessToken>() {

                    @Override
                    public void onError(Throwable throwable) {
                      Timber.e("accessTokenSubject.onError");
                      accessTokenSubject.onError(throwable);
                    }

                    @Override
                    public void onNext(AccessToken data) {
                      Timber.d("accessTokenSubject.onNext: " + data);
                      // Caching accessToken data
                      accessToken = data;
                      accessTokenSubject.onNext(accessToken);
                    }
                  });
    }
    return accessTokenSubject.asObservable();
  }
 @Override
 public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
   super.onViewCreated(view, savedInstanceState);
   BaseApplication.getBus().post(new FragmentOnViewCreatedEvent());
   Timber.tag(TAG);
   Timber.d("onViewCreated");
 }
  @Override
  public void setCurrentConversation(
      IConversation conversation, ConversationChangeRequester conversationChangerSender) {
    if (conversation instanceof InboxLinkConversation) {
      conversation = inboxList.get(0);
    }

    if (conversation != null) {
      conversation.setArchived(false);
    }
    if (conversation != null) {
      Timber.i(
          "Set current conversation to %s, requester %s",
          conversation.getName(), conversationChangerSender);
    } else {
      Timber.i("Set current conversation to null, requester %s", conversationChangerSender);
    }
    this.conversationChangeRequester = conversationChangerSender;
    IConversation oldConversation =
        conversationChangerSender == ConversationChangeRequester.FIRST_LOAD
            ? null
            : selectedConversation;
    conversationsList.setSelectedConversation(conversation);

    if (oldConversation == null
        || (oldConversation != null
            && conversation != null
            && oldConversation.getId().equals(conversation.getId()))) {
      // Notify explicitly if the conversation doesn't change, the UiSginal notifies only when the
      // conversation changes
      notifyCurrentConversationHasChanged(oldConversation, conversation, conversationChangerSender);
    }
  }
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   BaseApplication.getBus().post(new FragmentOnCreateEvent());
   Timber.tag(TAG);
   Timber.d("onCreate");
   initOnCreateBody();
 }
 @Override
 public void onAttach(Context context) {
   super.onAttach(context);
   BaseApplication.getBus().post(new FragmentOnAttachEvent());
   Timber.tag(TAG);
   Timber.d("onAttach");
   initOnAttachBody();
 }
 @Override
 public void onLowMemory() {
   super.onLowMemory();
   BaseApplication.getBus().post(new FragmentOnLowMemoryEvent());
   Timber.tag(TAG);
   Timber.d("onLowMemory");
   initOnLowMemoryBody();
 }
 @Override
 public void onConfigurationChanged(Configuration newConfig) {
   super.onConfigurationChanged(newConfig);
   BaseApplication.getBus().post(new FragmentOnConfigurationChangedEvent());
   Timber.tag(TAG);
   Timber.d("onConfigurationChanged");
   initOnConfigurationChangedBody();
 }
 @Override
 public void onDestroyView() {
   super.onDestroyView();
   BaseApplication.getBus().post(new FragmentOnDestroyViewEvent());
   Timber.tag(TAG);
   Timber.d("onDestroyView");
   initOnDestroyViewBody();
 }
 @Override
 public void onPause() {
   super.onPause();
   BaseApplication.getBus().post(new FragmentOnPauseEvent());
   Timber.tag(TAG);
   Timber.d("onPause");
   initOnPauseBody();
 }
 @Override
 public void onPrepareOptionsMenu(Menu menu) {
   super.onPrepareOptionsMenu(menu);
   BaseApplication.getBus().post(new FragmentOnPrepareOptionsMenuEvent());
   Timber.tag(TAG);
   Timber.d("onPrepareOptionsMenu");
   initOnPrepareOptionsMenuBody();
 }
 @Override
 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
   super.onActivityCreated(savedInstanceState);
   BaseApplication.getBus().post(new FragmentOnActivityCreatedEvent());
   Timber.tag(TAG);
   Timber.d("onActivityCreated");
   initOnActivityCreatedBody();
 }
 @Override
 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
   super.onCreateOptionsMenu(menu, inflater);
   BaseApplication.getBus().post(new FragmentOnCreateOptionsMenuEvent());
   Timber.tag(TAG);
   Timber.d("onCreateOptionsMenu");
   initOnCreateOptionsMenuBody();
 }
예제 #28
0
 /** Load pois from assets and save them in the database. */
 public void savePoisFromAssets() {
   List<Poi> pois = poiAssetLoader.loadPoisFromAssets();
   Timber.d("Loaded %s poi, trying to insert them", pois.size());
   for (Poi poi : pois) {
     Timber.d("saving poi %s", poi);
     savePoi(poi);
     Timber.d("poi saved");
   }
 }
예제 #29
0
  @Override
  public void retrieveStaleApplications() {
    SubscriptionHelper.unsubscribe(retrievalSubscription);
    retrievalSubscription =
        interactor
            .getAppEntryList()
            .zipWith(
                interactor.getActiveApplicationPackageNames().toList(),
                (allEntries, packageNames) -> {
                  final Set<PadLockEntry.AllEntries> liveLocations = new HashSet<>();
                  final Set<String> stalePackageNames = new HashSet<>();
                  // Remove all active applications from the list of entries
                  for (final String packageName : packageNames) {
                    Timber.i("Look for package: %s", packageName);
                    final List<PadLockEntry.AllEntries> foundLocations = new ArrayList<>();
                    //noinspection Convert2streamapi
                    for (final PadLockEntry.AllEntries entry : allEntries) {
                      if (entry.packageName().equals(packageName)) {
                        foundLocations.add(entry);
                      }
                    }

                    liveLocations.addAll(foundLocations);
                  }

                  // Remove any found locations
                  for (final PadLockEntry.AllEntries liveLocation : liveLocations) {
                    Timber.d(
                        "Remove live location: %s %s",
                        liveLocation.packageName(), liveLocation.activityName());
                    allEntries.remove(liveLocation);
                  }

                  // The remaining entries in the database are stale
                  for (final PadLockEntry.AllEntries entry : allEntries) {
                    Timber.i(
                        "Stale database entry: %s %s", entry.packageName(), entry.activityName());
                    stalePackageNames.add(entry.packageName());
                  }

                  return stalePackageNames;
                })
            .flatMap(Observable::from)
            .sorted(String::compareToIgnoreCase)
            .subscribeOn(getSubscribeScheduler())
            .observeOn(getObserveScheduler())
            .subscribe(
                s -> getView(view -> view.onStaleApplicationRetrieved(s)),
                throwable -> {
                  Timber.e(throwable, "onError retrieveStaleApplications");
                  getView(View::onRetrievalComplete);
                },
                () -> {
                  SubscriptionHelper.unsubscribe(retrievalSubscription);
                  getView(View::onRetrievalComplete);
                });
  }
 @Override
 public void onStop() {
   super.onStop();
   BaseApplication.getBus().unregister(mActivityResultSubscriber);
   BaseApplication.getBus().post(new FragmentOnStopEvent());
   Timber.tag(TAG);
   Timber.d("onStop");
   initOnStopBody();
 }