Esempio n. 1
0
 private String[] findFonts() {
   ArrayList<File> dirs = new ArrayList<File>();
   File[] dataDirs = getDataDirectories("fonts", false, false);
   for (File dir : dataDirs) dirs.add(dir);
   File[] rootDirs = getStorageDirectories(false);
   for (File dir : rootDirs) dirs.add(new File(dir, "fonts"));
   dirs.add(new File(Environment.getRootDirectory(), "fonts"));
   ArrayList<String> fontPaths = new ArrayList<String>();
   for (File fontDir : dirs) {
     if (fontDir.isDirectory()) {
       log.v("Scanning directory " + fontDir.getAbsolutePath() + " for font files");
       // get font names
       String[] fileList =
           fontDir.list(
               new FilenameFilter() {
                 public boolean accept(File dir, String filename) {
                   String lc = filename.toLowerCase();
                   return (lc.endsWith(".ttf")
                       || lc.endsWith(".otf")
                       || lc.endsWith(".pfb")
                       || lc.endsWith(".pfa"))
                   //								&& !filename.endsWith("Fallback.ttf")
                   ;
                 }
               });
       // append path
       for (int i = 0; i < fileList.length; i++) {
         String pathName = new File(fontDir, fileList[i]).getAbsolutePath();
         fontPaths.add(pathName);
         log.v("found font: " + pathName);
       }
     }
   }
   return fontPaths.toArray(new String[] {});
 }
 /**
  * Send a VERBOSE message and log the exception.
  *
  * @param tag Used to identify the source of a log message. It usually identifies the class or
  *     activity where the log call occurs.
  * @param formatString The string you would like logged plus format specifiers.
  * @param tr An exception to log
  * @param args Variable number of Object args to be used as params to formatString.
  */
 public static void v(String tag, String formatString, Throwable tr, Object... args) {
   if (logger != null && isLoggingEnabled(tag, VERBOSE)) {
     try {
       logger.v(tag, String.format(formatString, args), tr);
     } catch (Exception e) {
       logger.v(tag, String.format("Unable to format log: %s", formatString), e);
     }
   }
 }
Esempio n. 3
0
 /**
  * Show progress dialog. (thread-safe)
  *
  * @param mainProgress is percent*100
  * @param msg is progress message
  */
 public void showProgress(final int mainProgress, final String msg) {
   final int progressId = ++nextProgressId;
   mProgressMessage = msg;
   mProgressPos = mainProgress;
   if (mainProgress == 10000) {
     // log.v("mainProgress==10000 : calling hideProgress");
     hideProgress();
     return;
   }
   log.v(
       "showProgress("
           + mainProgress
           + ", \""
           + msg
           + "\") is called : "
           + Thread.currentThread().getName());
   if (enable_progress) {
     mBackgroundThread.executeGUI(
         new Runnable() {
           public void run() {
             // show progress
             // log.v("showProgress() - in GUI thread");
             if (progressId != nextProgressId) {
               // log.v("showProgress() - skipping duplicate progress event");
               return;
             }
             if (mProgress == null) {
               // log.v("showProgress() - creating progress window");
               try {
                 if (mActivity != null && mActivity.isStarted()) {
                   mProgress = new ProgressDialog(mActivity);
                   mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                   if (progressIcon != null) mProgress.setIcon(progressIcon);
                   else mProgress.setIcon(R.drawable.cr3_logo);
                   mProgress.setMax(10000);
                   mProgress.setCancelable(false);
                   mProgress.setProgress(mainProgress);
                   mProgress.setTitle(
                       mActivity.getResources().getString(R.string.progress_please_wait));
                   mProgress.setMessage(msg);
                   mProgress.show();
                   progressShown = true;
                 }
               } catch (Exception e) {
                 Log.e("cr3", "Exception while trying to show progress dialog", e);
                 progressShown = false;
                 mProgress = null;
               }
             } else {
               mProgress.setProgress(mainProgress);
               mProgress.setMessage(msg);
               if (!mProgress.isShowing()) {
                 mProgress.show();
                 progressShown = true;
               }
             }
           }
         });
   }
 }
  private boolean verifyAccount(Account[] accountList, String username, String uniqueId) {
    if (!StringExtensions.IsNullOrBlank(username)) {
      return username.equalsIgnoreCase(accountList[0].name);
    }

    if (!StringExtensions.IsNullOrBlank(uniqueId)) {
      // Uniqueid for account at authenticator is not available with
      // Account
      UserInfo[] users;
      try {
        users = getBrokerUsers();
        UserInfo matchingUser = findUserInfo(uniqueId, users);
        return matchingUser != null;
      } catch (Exception e) {
        Logger.e(
            TAG,
            "VerifyAccount:" + e.getMessage(),
            "",
            ADALError.BROKER_AUTHENTICATOR_EXCEPTION,
            e);
      }

      Logger.v(TAG, "It could not check the uniqueid from broker. It is not using broker");
      return false;
    }

    // if username or uniqueid not specified, it should use the broker
    // account.
    return true;
  }
Esempio n. 5
0
 /** Hide progress dialog (if shown). (thread-safe) */
 public void hideProgress() {
   final int progressId = ++nextProgressId;
   log.v("hideProgress() - is called : " + Thread.currentThread().getName());
   // log.v("hideProgress() is called");
   mBackgroundThread.executeGUI(
       new Runnable() {
         public void run() {
           // hide progress
           //				log.v("hideProgress() - in GUI thread");
           if (progressId != nextProgressId) {
             //					Log.v("cr3",
             //							"hideProgress() - skipping duplicate progress event");
             return;
           }
           if (mProgress != null) {
             // if ( mProgress.isShowing() )
             // mProgress.hide();
             progressShown = false;
             progressIcon = null;
             if (mProgress.isShowing()) mProgress.dismiss();
             mProgress = null;
             //					log.v("hideProgress() - in GUI thread, finished");
           }
         }
       });
 }
  @Override
  public boolean canUseLocalCache() {
    boolean brokerSwitch = canSwitchToBroker();
    if (!brokerSwitch) {
      Logger.v(TAG, "It does not use broker");
      return true;
    }

    String packageName = mContext.getPackageName();
    if (verifySignature(packageName)) {
      Logger.v(TAG, "Broker installer can use local cache");
      return true;
    }

    return false;
  }
 protected void onActivityResult(int reqCode, int resCode, Intent it) {
   logger.v("responseCode:" + resCode + ", requestCode:" + reqCode);
   switch (reqCode) {
     case 1234:
       setName(it.getStringExtra("name"));
       break;
   }
 }
Esempio n. 8
0
  public void muteSpeaker(Context context, Speaker speaker, boolean enabled) {
    LOG.v((enabled ? "mute" : "unmute") + ": " + speaker.name);

    int index = Arrays.asList(speakers).indexOf(speaker);
    if (index >= 0) {
      api().command().muteZone(index, enabled).execute(context);
    }
  }
  @Test
  public void infoNotLogged() {
    String expectedTag = "TestTag";

    logger.v(expectedTag, "Hello %s", "World");

    assertNotLogged();
  }
Esempio n. 10
0
  public void setSpeakerVolume(Context context, Speaker speaker, int dB) {
    LOG.v("enable: " + speaker.name);

    int index = Arrays.asList(speakers).indexOf(speaker);
    if (index >= 0) {
      api().command().setZoneVolume(index, dB).execute(context);
    }
  }
  @Test
  public void verboseWithThrowableNotLogged() {
    Throwable t = new Throwable("Test Throwable");

    logger.v(t, tag, "Hello %s", "World");

    assertNotLogged();
  }
 @Override
 protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   initLayout();
   Logger.v(Logger.GLOBAL_TAG, "onCreate");
   Logger.d(Logger.GLOBAL_TAG, "onCreate");
   Logger.i(Logger.GLOBAL_TAG, "onCreate");
 }
Esempio n. 13
0
  public void mute(Context context) {
    LOG.v("mute");
    YamahaApi.Command cmd = api().command();

    for (int i = 0; i < speakers.length; ++i) {
      cmd.muteZone(i, true);
    }

    cmd.execute(context);
  }
 public void onClick(View arg0) {
   switch (arg0.getId()) {
     case R.id.ButtonOpen:
       logger.v("click : ButtonOpen");
       Intent it = new Intent(this, ConfigActivity.class);
       if (name != null) it.putExtra("name", name);
       this.startActivityForResult(it, 1234);
       break;
   }
 }
Esempio n. 15
0
  public void setInput(Context context, Input input) {
    LOG.v("setInput: " + input.name);
    YamahaApi.Command cmd = api().command();

    if (speakers.length > 1) {
      cmd.partyMode(true);
    }

    cmd.setInput(input.name);
    cmd.execute(context);
  }
  /**
   * Waits on AccountManager results, so it should not be called on main thread.
   *
   * @throws IOException
   * @throws AuthenticatorException
   * @throws OperationCanceledException
   */
  @Override
  public UserInfo[] getBrokerUsers()
      throws OperationCanceledException, AuthenticatorException, IOException {

    // Calling this on main thread will cause exception since this is
    // waiting on AccountManagerFuture
    if (Looper.myLooper() == Looper.getMainLooper()) {
      throw new IllegalArgumentException("Calling getBrokerUsers on main thread");
    }

    Account[] accountList =
        mAcctManager.getAccountsByType(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE);
    Bundle bundle = new Bundle();
    bundle.putBoolean(DATA_USER_INFO, true);

    if (accountList != null) {

      // get info for each user
      UserInfo[] users = new UserInfo[accountList.length];
      for (int i = 0; i < accountList.length; i++) {

        // Use AccountManager Api method to get extended user info
        AccountManagerFuture<Bundle> result =
            mAcctManager.updateCredentials(
                accountList[i],
                AuthenticationConstants.Broker.AUTHTOKEN_TYPE,
                bundle,
                null,
                null,
                null);
        Logger.v(TAG, "Waiting for the result");
        Bundle userInfoBundle = result.getResult();

        users[i] =
            new UserInfo(
                userInfoBundle.getString(AuthenticationConstants.Broker.ACCOUNT_USERINFO_USERID),
                userInfoBundle.getString(
                    AuthenticationConstants.Broker.ACCOUNT_USERINFO_GIVEN_NAME),
                userInfoBundle.getString(
                    AuthenticationConstants.Broker.ACCOUNT_USERINFO_FAMILY_NAME),
                userInfoBundle.getString(
                    AuthenticationConstants.Broker.ACCOUNT_USERINFO_IDENTITY_PROVIDER),
                userInfoBundle.getString(
                    AuthenticationConstants.Broker.ACCOUNT_USERINFO_USERID_DISPLAYABLE));
      }

      return users;
    }
    return null;
  }
  private boolean sendRequest(final URL queryUrl) throws MalformedURLException, JSONException {

    Logger.v(TAG, "Sending discovery request to:" + queryUrl);
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(WebRequestHandler.HEADER_ACCEPT, WebRequestHandler.HEADER_ACCEPT_JSON);

    // CorrelationId is used to track the request at the Azure services
    if (mCorrelationId != null) {
      headers.put(AuthenticationConstants.AAD.CLIENT_REQUEST_ID, mCorrelationId.toString());
      headers.put(AuthenticationConstants.AAD.RETURN_CLIENT_REQUEST_ID, "true");
    }

    HttpWebResponse webResponse = null;
    String errorCodes = "";
    try {
      ClientMetrics.INSTANCE.beginClientMetricsRecord(queryUrl, mCorrelationId, headers);
      webResponse = mWebrequestHandler.sendGet(queryUrl, headers);
      if (webResponse.getResponseException() == null) {
        ClientMetrics.INSTANCE.setLastError(null);
      } else {
        ClientMetrics.INSTANCE.setLastError(String.valueOf(webResponse.getStatusCode()));
      }

      // parse discovery response to find tenant info
      HashMap<String, String> discoveryResponse = parseResponse(webResponse);
      if (discoveryResponse.containsKey(AuthenticationConstants.OAuth2.ERROR_CODES)) {
        errorCodes = discoveryResponse.get(AuthenticationConstants.OAuth2.ERROR_CODES);
        ClientMetrics.INSTANCE.setLastError(errorCodes);
      }

      return (discoveryResponse != null
          && discoveryResponse.containsKey(TENANT_DISCOVERY_ENDPOINT));
    } catch (IllegalArgumentException exc) {
      Logger.e(TAG, exc.getMessage(), "", ADALError.DEVELOPER_AUTHORITY_CAN_NOT_BE_VALIDED, exc);
      throw exc;
    } catch (JSONException e) {
      Logger.e(TAG, "Json parsing error", "", ADALError.DEVELOPER_AUTHORITY_CAN_NOT_BE_VALIDED, e);
      throw e;
    } finally {
      ClientMetrics.INSTANCE.endClientMetricsRecord(
          ClientMetricsEndpointType.INSTANCE_DISCOVERY, mCorrelationId);
    }
  }
Esempio n. 18
0
 public static data fromJson(JSONObject jsonobject, JSONObject jsonobject1)
     throws JSONException, tion
 {
     if (jsonobject == null)
     {
         throw new JSONException("expression may not be null");
     }
     Iterator iterator = jsonobject.keys();
     String s = (String)iterator.next();
     jsonobject = jsonobject.getJSONArray(s);
     Logger.v((new StringBuilder()).append("Node is ").append(s).toString());
     if (iterator.hasNext())
     {
         throw new tion("Syntax error in rules, current level has more than one outer object.");
     } else
     {
         return fromKeywordAndArgs(s, jsonobject, jsonobject1);
     }
 }
  private boolean checkAccount(final AccountManager am, String username, String uniqueId) {
    AuthenticatorDescription[] authenticators = am.getAuthenticatorTypes();
    for (AuthenticatorDescription authenticator : authenticators) {
      if (authenticator.type.equals(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE)) {

        Account[] accountList =
            mAcctManager.getAccountsByType(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE);

        // Authenticator installed from Company portal
        // This supports only one account
        if (authenticator.packageName.equalsIgnoreCase(
            AuthenticationConstants.Broker.PACKAGE_NAME)) {
          // Adal should not connect if given username does not match
          if (accountList != null && accountList.length > 0) {
            return verifyAccount(accountList, username, uniqueId);
          }

          return false;

          // Check azure authenticator and allow calls for test
          // versions
        } else if (authenticator.packageName.equalsIgnoreCase(
                AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_PACKAGE_NAME)
            || authenticator.packageName.equalsIgnoreCase(
                AuthenticationSettings.INSTANCE.getBrokerPackageName())) {

          // Existing broker logic only connects to broker for token
          // requests if account exists. New version can allow to
          // add accounts through Adal.
          if (hasSupportToAddUserThroughBroker()) {
            Logger.v(TAG, "Broker supports to add user through app");
            return true;
          } else if (accountList != null && accountList.length > 0) {
            return verifyAccount(accountList, username, uniqueId);
          }
        }
      }
    }

    return false;
  }
  public Resources load(@Cache.Policy int policy) throws ExternalResourceException {
    buildUrl();

    Logger.i(ExternalResources.TAG, "Load configuration from url: " + url.build());

    final CacheControl cacheControl;
    switch (policy) {
      case Cache.POLICY_NONE:
        cacheControl = new CacheControl.Builder().noCache().noStore().build();
        break;
      case Cache.POLICY_OFFLINE:
        cacheControl = CacheControl.FORCE_CACHE;
        break;
      case Cache.POLICY_ALL:
      default:
        cacheControl = new CacheControl.Builder().build();
        break;
    }

    Logger.v(ExternalResources.TAG, "CachePolicy: " + policy);

    Request request = new Request.Builder().url(url.build()).cacheControl(cacheControl).build();

    try {
      Response response = client.newCall(request).execute();
      int responseCode = response.code();

      Logger.d(ExternalResources.TAG, "Response code: " + responseCode);
      if (responseCode >= 300) {
        response.body().close();
        throw new ResponseException(responseCode + " " + response.message(), policy, responseCode);
      }

      return converter.fromReader(response.body().charStream());
    } catch (IOException e) {
      throw new ExternalResourceException(e);
    }
  }
Esempio n. 21
0
 /**
  * Send a VERBOSE message.
  *
  * @param tag Used to identify the source of a log message. It usually identifies the class or
  *     activity where the log call occurs.
  * @param msg The message you would like logged.
  */
 public static void v(String tag, String msg) {
   if (logger != null && isLoggingEnabled(tag, VERBOSE)) {
     logger.v(tag, msg);
   }
 }
Esempio n. 22
0
 /**
  * Call this method (in GUI thread) to update views if directory content is changed outside.
  *
  * @param dir is directory with changed content
  */
 public void onDirectoryContentChanged(FileInfo dir) {
   log.v("onDirectoryContentChanged(" + dir.getPathName() + ")");
   onChange(dir, false);
 }
  /** Gets accessToken from Broker component. */
  @Override
  public AuthenticationResult getAuthTokenInBackground(final AuthenticationRequest request) {

    AuthenticationResult authResult = null;
    verifyNotOnMainThread();

    // if there is not any user added to account, it returns empty
    Account targetAccount = null;
    Account[] accountList =
        mAcctManager.getAccountsByType(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE);

    if (!TextUtils.isEmpty(request.getBrokerAccountName())) {
      targetAccount = findAccount(request.getBrokerAccountName(), accountList);
    } else {
      try {
        UserInfo[] users = getBrokerUsers();
        UserInfo matchingUser = findUserInfo(request.getUserId(), users);
        if (matchingUser != null) {
          targetAccount = findAccount(matchingUser.getDisplayableId(), accountList);
        }
      } catch (Exception e) {
        Logger.e(TAG, e.getMessage(), "", ADALError.BROKER_AUTHENTICATOR_IO_EXCEPTION, e);
      }
    }

    if (targetAccount != null) {
      Bundle brokerOptions = getBrokerOptions(request);

      // blocking call to get token from cache or refresh request in
      // background at Authenticator
      AccountManagerFuture<Bundle> result = null;
      try {
        // It does not expect activity to be launched.
        // AuthenticatorService is handling the request at
        // AccountManager.
        //
        result =
            mAcctManager.getAuthToken(
                targetAccount,
                AuthenticationConstants.Broker.AUTHTOKEN_TYPE,
                brokerOptions,
                false,
                null /*
                      * set to null to avoid callback
                      */,
                mHandler);

        // Making blocking request here
        Logger.v(TAG, "Received result from Authenticator");
        Bundle bundleResult = result.getResult();
        // Authenticator should throw OperationCanceledException if
        // token is not available
        authResult = getResultFromBrokerResponse(bundleResult);
      } catch (OperationCanceledException e) {
        Logger.e(TAG, "Authenticator cancels the request", "", ADALError.AUTH_FAILED_CANCELLED, e);
      } catch (AuthenticatorException e) {
        Logger.e(
            TAG,
            "Authenticator cancels the request",
            "",
            ADALError.BROKER_AUTHENTICATOR_NOT_RESPONDING);
      } catch (IOException e) {
        // Authenticator gets problem from webrequest or file read/write
        Logger.e(
            TAG,
            "Authenticator cancels the request",
            "",
            ADALError.BROKER_AUTHENTICATOR_IO_EXCEPTION);
      }

      Logger.v(TAG, "Returning result from Authenticator");
      return authResult;
    } else {
      Logger.v(TAG, "Target account is not found");
    }

    return null;
  }
  @Test
  public void verboseNotLogged() {
    logger.v(tag, "Hello %s", "World");

    assertNotLogged();
  }