public boolean equals(SyncLogEntry entry) { Logger.e( "entry: " + entry.m_file_name + " tags: " + entry.m_tags + " hash: " + entry.m_hash_sum + " timestamp:" + entry.m_time_stamp); Logger.e( "this: " + this.m_file_name + " tags: " + this.m_tags + " hash: " + this.m_hash_sum + " timestamp:" + this.m_time_stamp); return this.m_file_name.equals(entry.m_file_name) && this.m_tags.equals(entry.m_tags) && this.m_hash_sum.equals(entry.m_hash_sum) && this.m_time_stamp.equals(entry.m_time_stamp); }
private boolean queryInstance(final URL authorizationEndpointUrl) { // It will query prod instance to verify the authority // construct query string for this instance URL queryUrl; boolean result = false; try { queryUrl = buildQueryString( TRUSTED_QUERY_INSTANCE, getAuthorizationCommonEndpoint(authorizationEndpointUrl)); result = sendRequest(queryUrl); } catch (MalformedURLException e) { Logger.e(TAG, "Invalid authority", "", ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL, e); result = false; } catch (JSONException e) { Logger.e(TAG, "Json parsing error", "", ADALError.DEVELOPER_AUTHORITY_CAN_NOT_BE_VALIDED, e); result = false; } if (result) { // it is validated addValidHostToList(authorizationEndpointUrl); } return result; }
/** * Send a ERROR 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 formatString The string you would like logged plus format specifiers. * @param args Variable number of Object args to be used as params to formatString. */ public static void e(String tag, String formatString, Object... args) { if (logger != null && isLoggingEnabled(tag, ERROR)) { try { logger.e(tag, String.format(formatString, args)); } catch (Exception e) { logger.e(tag, String.format("Unable to format log: %s", formatString), e); } } }
/** * Gets intent for authentication activity from Broker component to start from calling app's * activity to control the lifetime of the activity. */ @Override public Intent getIntentForBrokerActivity(final AuthenticationRequest request) { Intent intent = null; AccountManagerFuture<Bundle> result = null; try { // Callback is not passed since it is making a blocking call to get // intent. Activity needs to be launched from calling app // to get the calling app's metadata if needed at BrokerActivity. Bundle addAccountOptions = getBrokerOptions(request); result = mAcctManager.addAccount( AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE, AuthenticationConstants.Broker.AUTHTOKEN_TYPE, null, addAccountOptions, null, null, mHandler); // Making blocking request here Bundle bundleResult = result.getResult(); // Authenticator should throw OperationCanceledException if // token is not available intent = bundleResult.getParcelable(AccountManager.KEY_INTENT); // Add flag to this intent to signal that request is for broker // logic if (intent != null) { intent.putExtra( AuthenticationConstants.Broker.BROKER_REQUEST, AuthenticationConstants.Broker.BROKER_REQUEST); } } catch (OperationCanceledException e) { Logger.e(TAG, "Authenticator cancels the request", "", ADALError.AUTH_FAILED_CANCELLED, e); } catch (AuthenticatorException e) { // // TODO add retry logic since authenticator is not responding to // the request 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); } return intent; }
public static Object post(RequestModel model) { // Authenticator.setDefault(new Authenticator() { // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication (Loggerin, password.toCharArray()); // } // }); DefaultHttpClient client = new DefaultHttpClient(); String url = model.host.concat(model.context.getString(model.requestUrl)); Logger.e("NetUtil里面的post的URL", url); HttpPost post = new HttpPost(url); post.setHeader( "Authorization", "Basic " + Base64.encodeToString((Loggerin + ":" + password).getBytes(), Base64.NO_WRAP)); HttpParams params = new BasicHttpParams(); params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 8000); HttpConnectionParams.setSoTimeout(params, 8000); post.setParams(params); Object obj = null; try { if (model.requestDataMap != null) { HashMap<String, String> map = model.requestDataMap; List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); for (Map.Entry<String, String> entry : map.entrySet()) { BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue()); pairList.add(pair); } HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8"); post.setEntity(entity); } HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity(), "UTF-8"); Logger.e(NetUtil.class.getSimpleName() + "1", result); try { obj = model.jsonParser.parseJSON(result); } catch (Exception e) { Log.e(NetUtil.class.getSimpleName() + "2", e.getLocalizedMessage(), e); } return obj; } } catch (ClientProtocolException e) { Log.e(NetUtil.class.getSimpleName() + "5", e.getLocalizedMessage(), e); } catch (IOException e) { Log.e(NetUtil.class.getSimpleName() + "6", e.getLocalizedMessage(), e); } return null; }
public static void initImageLoaderConfig(Context context) { try { File cacheDir = StorageUtils.getOwnCacheDirectory( context, CommonUtil.getSavePath(SysConstant.FILE_SAVE_TYPE_IMAGE)); File reserveCacheDir = StorageUtils.getCacheDirectory(context); int maxMemory = (int) (Runtime.getRuntime().maxMemory()); // 使用最大可用内存值的1/8作为缓存的大小。 int cacheSize = maxMemory / 8; DisplayMetrics metrics = new DisplayMetrics(); WindowManager mWm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); mWm.getDefaultDisplay().getMetrics(metrics); IMImageLoaderConfig = new ImageLoaderConfiguration.Builder(context) .memoryCacheExtraOptions(metrics.widthPixels, metrics.heightPixels) .threadPriority(Thread.NORM_PRIORITY - 2) // .denyCacheImageMultipleSizesInMemory() .memoryCache(new UsingFreqLimitedMemoryCache(cacheSize)) .diskCacheFileNameGenerator(new Md5FileNameGenerator()) .tasksProcessingOrder(QueueProcessingType.LIFO) .diskCacheExtraOptions(metrics.widthPixels, metrics.heightPixels, null) .diskCache( new UnlimitedDiscCache(cacheDir, reserveCacheDir, new Md5FileNameGenerator())) .diskCacheSize(1024 * 1024 * 1024) .diskCacheFileCount(1000) .build(); IMImageLoadInstance = ImageLoader.getInstance(); IMImageLoadInstance.init(IMImageLoaderConfig); } catch (Exception e) { logger.e(e.toString()); } }
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; }
private void updateFromPreference() { Logger.d("Service updateFromPreference called"); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); try { powerManager.setBatteryThresh( Integer.parseInt( prefs.getString( getString(R.string.batteryMinThresPrefKey), String.valueOf(Config.DEFAULT_BATTERY_THRESH_PRECENT)))); this.setCheckinInterval( Integer.parseInt( prefs.getString( getString(R.string.checkinIntervalPrefKey), String.valueOf(Config.DEFAULT_CHECKIN_INTERVAL_SEC / 3600))) * 3600); updateStatus(); Logger.i( "Preference set from SharedPreference: " + "checkinInterval=" + checkinIntervalSec + ", minBatThres= " + powerManager.getBatteryThresh()); } catch (ClassCastException e) { Logger.e("exception when casting preference values", e); } }
/** * 调用的时候要判断是否为空 * * @param model * @return */ public static Object get(RequestModel model) { // Authenticator.setDefault(new Authenticator() { // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication (Loggerin, password.toCharArray()); // } // }); DefaultHttpClient client = new DefaultHttpClient(); String url = model.host.concat(model.context.getString(model.requestUrl)); StringBuffer sb = new StringBuffer(); sb.append(url); String afterSign = addGetParams(model.requestDataMap); sb.append(afterSign); Logger.e("get请求方法", "最后的请求地址是 == " + sb.toString()); String u = sb.toString(); u = u.replace(" ", "%20"); HttpGet get = new HttpGet(u); get.setHeader( "Authorization", "Basic " + Base64.encodeToString((Loggerin + ":" + password).getBytes(), Base64.NO_WRAP)); HttpParams params = new BasicHttpParams(); params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 8000); HttpConnectionParams.setSoTimeout(params, 8000); get.setParams(params); Object obj = null; try { HttpResponse response = client.execute(get); if (response == null) { Logger.e("get", "response == null"); } if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity(), "UTF-8"); Logger.i(NetUtil.class.getSimpleName() + "get3", result); try { obj = model.jsonParser.parseJSON(result); } catch (JSONException e) { Log.e(NetUtil.class.getSimpleName() + "4", e.getLocalizedMessage(), e); } return obj; } } catch (Exception e) { e.printStackTrace(); } return null; }
public static JSONObject buildSensorJson(HashMap<String, BaseSensor> sensorMap, long frameNo) { try { JSONObject jsonObject = new JSONObject(); jsonObject.put("frameNo", frameNo); for (Entry<String, BaseSensor> entry : sensorMap.entrySet()) { try { jsonObject.put(entry.getKey(), entry.getValue().getJsonResult()); } catch (JSONException e) { Logger.e(LOGTAG, "Exception with Writing Sensor " + entry.getKey()); } } return jsonObject; } catch (JSONException je) { Logger.e(LOGTAG, "Exception with buildSensorJson"); return null; } }
public static String encode(String url) { try { return URLEncoder.encode(url, "UTF-8"); } catch (UnsupportedEncodingException e) { Logger.e(e); } return url; }
public boolean isExpiried(String param, long expTime) { TestParam p = map.get(param); if (p == null) { Logger.e(this, "can not find param for name: " + param); return true; } return (p.createdTime + expTime) < System.currentTimeMillis(); }
@Test public void errorLoggedCorrectly() { String expectedMessage = "Hello World"; logger.e(tag, "Hello %s", "World"); assertLogged(ERROR, tag, expectedMessage, null); }
@Test public void errorWithThrowableLoggedCorrectly() { String expectedMessage = "Hello World"; Throwable t = new Throwable("Test Throwable"); logger.e(t, tag, "Hello %s", "World"); assertLogged(ERROR, tag, expectedMessage, t); }
public byte[] loadResourceBytes(int id) { try { InputStream is = this.mActivity.getResources().openRawResource(id); return loadResourceBytes(is); } catch (Exception e) { log.e("cannot load resource"); return null; } }
public String loadFileUtf8(File file) { try { InputStream is = new FileInputStream(file); return loadResourceUtf8(is); } catch (Exception e) { log.e("cannot load resource from file " + file); return null; } }
public static void closeStream(Closeable is) { try { if (is != null) { is.close(); is = null; } } catch (Exception e) { Logger.e(TAG, "closeStream(" + is + ")", e); } }
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); } }
public static boolean isPermissionAllowed(String permission) { try { return A.getApp() .checkPermission( permission, android.os.Binder.getCallingPid(), android.os.Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED; } catch (Exception e) { Logger.e(TAG, "isPermissionAllowed(" + permission + ")", e); return false; } }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preference); try { Preference prefAppVersionName = findPreference("pref_app_version_name"); prefAppVersionName.setSummary( getPackageManager().getPackageInfo(getPackageName(), 0).versionName); } catch (Exception e) { Logger.e(e); } }
public static byte[] loadResourceBytes(File f) { if (f == null || !f.isFile() || !f.exists()) return null; FileInputStream is = null; try { is = new FileInputStream(f); byte[] res = loadResourceBytes(is); return res; } catch (IOException e) { log.e("Cannot open file " + f); } return null; }
/** * Submit a MeasurementTask to the scheduler. Caller of this method can broadcast an intent with * MEASUREMENT_ACTION to start the measurement immediately. */ public boolean submitTask(MeasurementTask task) { try { // Immediately handles measurements created by user if (task.getDescription().priority == MeasurementTask.USER_PRIORITY) { return this.taskQueue.add(task); } if (taskQueue.size() >= Config.MAX_TASK_QUEUE_SIZE || pendingTasks.size() >= Config.MAX_TASK_QUEUE_SIZE) { return false; } // Automatically notifies the scheduler waiting on taskQueue.take() return this.taskQueue.add(task); } catch (NullPointerException e) { Logger.e("The task to be added is null"); return false; } catch (ClassCastException e) { Logger.e("cannot compare this task against existing ones"); return false; } }
public static byte[] loadResourceBytes(InputStream is) { try { int available = is.available(); if (available <= 0) return null; byte buf[] = new byte[available]; if (is.read(buf) != available) throw new IOException("Resource not read fully"); is.close(); return buf; } catch (Exception e) { log.e("cannot load resource"); return null; } }
/** 清除缓存 */ public static void clearCache() { try { if (IMImageLoadInstance != null) { IMImageLoadInstance.clearMemoryCache(); IMImageLoadInstance.clearDiskCache(); } if (null != avatarOptionsMaps) { avatarOptionsMaps.clear(); } } catch (Exception e) { logger.e(e.toString()); } }
public static DisplayImageOptions getAvatarOptions(int corner, int defaultRes) { try { if (defaultRes <= 0) { defaultRes = R.drawable.tt_default_user_portrait_corner; } if (avatarOptionsMaps.containsKey(defaultRes)) { Map<Integer, DisplayImageOptions> displayOption = avatarOptionsMaps.get(defaultRes); if (displayOption.containsKey(corner)) { return displayOption.get(corner); } } DisplayImageOptions newDisplayOption = null; if (corner == CIRCLE_CORNER) { newDisplayOption = new DisplayImageOptions.Builder() .showImageOnFail(defaultRes) .showImageForEmptyUri(defaultRes) .cacheInMemory(true) .resetViewBeforeLoading(true) .displayer(new CircleBitmapDisplayer()) .build(); } else { if (corner < 0) { corner = 0; } newDisplayOption = new DisplayImageOptions.Builder() .showImageOnLoading(defaultRes) .showImageForEmptyUri(defaultRes) .showImageOnFail(defaultRes) .cacheInMemory(true) .cacheOnDisk(true) .considerExifParams(true) .imageScaleType(ImageScaleType.EXACTLY) .bitmapConfig(Bitmap.Config.RGB_565) .resetViewBeforeLoading(false) // .displayer(new FadeInBitmapDisplayer(200)) .displayer(new RoundedBitmapDisplayer(corner)) .build(); } Map<Integer, DisplayImageOptions> cornerDisplayOptMap = new HashMap<Integer, DisplayImageOptions>(); cornerDisplayOptMap.put(corner, newDisplayOption); avatarOptionsMaps.put(defaultRes, cornerDisplayOptMap); return newDisplayOption; } catch (Exception e) { logger.e(e.toString()); return null; } }
public static void displayImage( ImageView imageView, String resourceUri, int defaultResId, int roundPixel) { Logger logger = Logger.getLogger(IMUIHelper.class); logger.d( "displayimage#displayImage resourceUri:%s, defeaultResourceId:%d", resourceUri, defaultResId); if (resourceUri == null) { resourceUri = ""; } boolean showDefaultImage = !(defaultResId <= 0); if (TextUtils.isEmpty(resourceUri) && !showDefaultImage) { logger.e("displayimage#, unable to display image"); return; } DisplayImageOptions options; if (showDefaultImage) { options = new DisplayImageOptions.Builder() .showImageOnLoading(defaultResId) .showImageForEmptyUri(defaultResId) .showImageOnFail(defaultResId) .cacheInMemory(true) .cacheOnDisk(true) .considerExifParams(true) .displayer(new RoundedBitmapDisplayer(roundPixel)) .imageScaleType(ImageScaleType.EXACTLY) . // 改善OOM bitmapConfig(Bitmap.Config.RGB_565) . // 改善OOM build(); } else { options = new DisplayImageOptions.Builder() .cacheInMemory(true) .cacheOnDisk(true) . // considerExifParams(true). // displayer(new RoundedBitmapDisplayer(roundPixel)). // imageScaleType(ImageScaleType.EXACTLY).// 改善OOM // bitmapConfig(Bitmap.Config.RGB_565).// 改善OOM build(); } ImageLoader.getInstance().displayImage(resourceUri, imageView, options, null); }
private boolean verifySignature(final String brokerPackageName) { try { PackageInfo info = mContext .getPackageManager() .getPackageInfo(brokerPackageName, PackageManager.GET_SIGNATURES); if (info != null && info.signatures != null) { // Broker App can be signed with multiple certificates. It will // look all of them until it finds the correct one for ADAL // broker. for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); String tag = Base64.encodeToString(md.digest(), Base64.NO_WRAP); // Company portal(Intune) app and Azure authenticator app // have authenticator. if (tag.equals(mBrokerTag) || tag.equals(AuthenticationConstants.Broker.AZURE_AUTHENTICATOR_APP_SIGNATURE)) { return true; } } } } catch (NameNotFoundException e) { Logger.e( TAG, "Broker related package does not exist", "", ADALError.BROKER_PACKAGE_NAME_NOT_FOUND); } catch (NoSuchAlgorithmException e) { Logger.e(TAG, "Digest SHA algorithm does not exists", "", ADALError.DEVICE_NO_SUCH_ALGORITHM); } catch (Exception e) { Logger.e(TAG, "Error in verifying signature", "", ADALError.BROKER_VERIFICATION_FAILED, e); } return false; }
public String loadResourceUtf8(InputStream is) { try { int available = is.available(); if (available <= 0) return null; byte buf[] = new byte[available]; if (is.read(buf) != available) throw new IOException("Resource not read fully"); is.close(); String utf8 = new String(buf, 0, available, "UTF8"); return utf8; } catch (Exception e) { log.e("cannot load resource"); return null; } }
public static synchronized String hashString(String data) { try { if (data == null || data.length() == 0) return ""; if (md == null) { md = MessageDigest.getInstance("SHA1"); } md.update(data.getBytes()); return bytesToHex(md.digest()); } catch (Exception e) { Logger.e(TAG, "hashString(" + data + ")", e); } return new String(); }
public static float getDpPixels(Context context, float pixels) { try { if (density == -1.0f) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); density = metrics.density; densityDpi = metrics.densityDpi; // Logger.i(TAG, "density:" + density); } return density * pixels; } catch (Exception e) { Logger.e(TAG, "getDpPixels(" + pixels + "), e:" + e); e.printStackTrace(); return pixels; } }