@Override
 protected <T> T execute(SimpleType<T> resultType) throws Exception {
   InputStream is = conn.getInputStream();
   if (TextUtils.isEmpty(destFileDir)) {
     throw new RuntimeException("destFileDir must not be null");
   }
   File desFile = new File(destFileDir);
   if (!desFile.exists()) {
     desFile.mkdirs();
   }
   if (TextUtils.isEmpty(destFileName)) {
     destFileName = new File(url).getName();
   }
   FileOutputStream fos = new FileOutputStream(new File(destFileDir, destFileName));
   long flength = conn.getContentLength();
   sendProgress(flength, 0, false);
   byte[] buf = new byte[1024];
   int len;
   long current = 0;
   while ((len = is.read(buf)) != -1) {
     if (isCancel) {
       sendCancel();
       return null;
     }
     current += len;
     fos.write(buf, 0, len);
     sendProgress(flength, current, false);
   }
   fos.close();
   is.close();
   conn.disconnect();
   sendSuccess("200 OK");
   return null;
 }
示例#2
0
  /**
   * Helper to convert unknown or unmapped attachments to something useful based on filename
   * extensions. Imperfect, but helps.
   *
   * <p>If the given mime type is non-empty and anything other than "application/octet-stream", just
   * return it. (This is the most common case.) If the filename has a recognizable extension and it
   * converts to a mime type, return that. If the filename has an unrecognized extension, return
   * "application/extension" Otherwise return "application/octet-stream".
   *
   * @param fileName The given filename
   * @param mimeType The given mime type
   * @return A likely mime type for the attachment
   */
  public static String inferMimeType(String fileName, String mimeType) {
    // If the given mime type appears to be non-empty and non-generic - return it
    if (!TextUtils.isEmpty(mimeType) && !"application/octet-stream".equalsIgnoreCase(mimeType)) {
      return mimeType;
    }

    // Try to find an extension in the filename
    if (!TextUtils.isEmpty(fileName)) {
      int lastDot = fileName.lastIndexOf('.');
      String extension = null;
      if ((lastDot > 0) && (lastDot < fileName.length() - 1)) {
        extension = fileName.substring(lastDot + 1).toLowerCase();
      }
      if (!TextUtils.isEmpty(extension)) {
        // Extension found.  Look up mime type, or synthesize if none found.
        mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        if (mimeType == null) {
          mimeType = "application/" + extension;
        }
        return mimeType;
      }
    }

    // Fallback case - no good guess could be made.
    return "application/octet-stream";
  }
示例#3
0
  private void uploadLink(
      @Nullable String title, @Nullable String description, @NonNull String url) {
    LogUtil.v(TAG, "Received URL to upload");
    ApiClient client = new ApiClient(Endpoints.UPLOAD.getUrl(), ApiClient.HttpRequest.POST);

    FormEncodingBuilder builder = new FormEncodingBuilder().add("image", url).add("type", "URL");

    if (!TextUtils.isEmpty(title)) {
      builder.add("title", title);
    }

    if (!TextUtils.isEmpty(description)) {
      builder.add("description", description);
    }

    RequestBody body = builder.build();

    try {
      if (mNotificationId <= 0) mNotificationId = url.hashCode();
      onUploadStarted();
      JSONObject json = client.doWork(body);
      int status = json.getInt(ApiClient.KEY_STATUS);

      if (status == ApiClient.STATUS_OK) {
        handleResponse(json.getJSONObject(ApiClient.KEY_DATA));
      } else {
        onUploadFailed(title, description, url, false);
      }
    } catch (IOException | JSONException e) {
      LogUtil.e(TAG, "Error uploading url", e);
      onUploadFailed(title, description, url, false);
    }
  }
 @Test
 public void testIsEmpty() throws Exception {
   assertThat(TextUtils.isEmpty(null), equalTo(true));
   assertThat(TextUtils.isEmpty(""), equalTo(true));
   assertThat(TextUtils.isEmpty(" "), equalTo(false));
   assertThat(TextUtils.isEmpty("123"), equalTo(false));
 }
  public void setFromEpisode(TvEpisode episode) {
    Preconditions.checkNotNull(episode, "Episode cannot be null");

    tmdbId = episode.id;

    if (!TextUtils.isEmpty(episode.name)) {
      tmdbTitle = episode.name;
    }

    if (episode.air_date != null) {
      tmdbFirstAirDate = episode.air_date;
    }

    if (episode.episode_number != null) {
      episodeNumber = episode.episode_number;
    }

    tmdbRatingPercent = unbox(tmdbRatingPercent, episode.vote_average);
    tmdbRatingVotesAmount = unbox(tmdbRatingVotesAmount, episode.vote_count);

    if (!TextUtils.isEmpty(episode.overview)) {
      tmdbOverview = episode.overview;
    }

    seasonNumber = episode.season_number;

    if (!TextUtils.isEmpty(episode.still_path)) {
      stillUrl = episode.still_path;
    }
  }
示例#6
0
  public String createMessage(HttpClientErrorException ex) {
    String result = "";
    try {
      String responseBody = ex.getResponseBodyAsString();

      if (!TextUtils.isEmpty(responseBody)) {
        result = ex.getMessage() + ": " + responseBody;

        ErrorBody errorBody = mapper.readValue(ex.getResponseBodyAsByteArray(), ErrorBody.class);
        if (errorBody.fault != null) {
          result = ex.getMessage() + " " + errorBody.fault.reason + " " + errorBody.fault.detail;
        } else {
          ErrorBody.Fault fault =
              mapper.readValue(ex.getResponseBodyAsByteArray(), ErrorBody.Fault.class);
          if (fault != null) {
            result = ex.getMessage() + " " + fault.reason + " " + fault.detail;
          }
        }
      }
    } catch (Exception f) {
      result = f.getMessage();
    }

    if (TextUtils.isEmpty(result)) {
      result = ex.getMessage();
    }

    return result;
  }
 protected void updateMovieInfo() {
   mVideoWidth = mVideoHeight = mRotation = mBitrate = 0;
   mDuration = 0;
   mFrameRate = 0;
   String value = mMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
   if (!TextUtils.isEmpty(value)) {
     mVideoWidth = Integer.parseInt(value);
   }
   value = mMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
   if (!TextUtils.isEmpty(value)) {
     mVideoHeight = Integer.parseInt(value);
   }
   value = mMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
   if (!TextUtils.isEmpty(value)) {
     mRotation = Integer.parseInt(value);
   }
   value = mMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE);
   if (!TextUtils.isEmpty(value)) {
     mBitrate = Integer.parseInt(value);
   }
   value = mMetadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
   if (!TextUtils.isEmpty(value)) {
     mDuration = Long.parseLong(value) * 1000;
   }
 }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_movie_details, container, false);
    ButterKnife.bind(this, view);
    Movie movie = getActivity().getIntent().getParcelableExtra(MovieDetailsActivity.EXTRA_MOVIE);
    try {
      releaseDate.setText("" + movie.getReleaseDateYear());
    } catch (Exception e) {
      releaseDate.setVisibility(View.GONE);
    }
    ratings.setText("" + movie.getRatings() + "/10.0");
    String posterUrl =
        SpotifyStreamerConstants.getMoviePosterUrl(
            movie.getPoster(), SpotifyStreamerConstants.MoviePosterSize.W342);
    Picasso.with(getActivity()).load(posterUrl).into(poster);
    if (!TextUtils.isEmpty(movie.getSynopsis())) {
      synopsis.setText(movie.getSynopsis());
    }

    String trailerVideosUrl = SpotifyStreamerConstants.getMovieTrailerVideos(movie.getId());
    if (!TextUtils.isEmpty(trailerVideosUrl)) {
      FetchMovieTrailorAsyncTask fetchMovieTrailorAsyncTask = new FetchMovieTrailorAsyncTask(this);
      fetchMovieTrailorAsyncTask.execute(trailerVideosUrl);
    }
    String reviewUrl = SpotifyStreamerConstants.getMovieReview(movie.getId());
    if (!TextUtils.isEmpty(trailerVideosUrl)) {
      FetchMovieReviewsAsyncTask fetchMovieReviewAsyncTask = new FetchMovieReviewsAsyncTask(this);
      fetchMovieReviewAsyncTask.execute(reviewUrl);
    }
    return view;
  }
  /** 注册信息的判断 请求注册 */
  private void onJudge() {
    if (TextUtils.isEmpty(register_phone.getText().toString())
        || TextUtils.isEmpty(register_pass.getText().toString())
        || TextUtils.isEmpty(inputCode.getText().toString())) {
      showSmartToast(R.string.input_error, Toast.LENGTH_LONG);
      return;
    }
    if (!register_phone.getText().toString().equalsIgnoreCase(phone)) {
      SmartToast.showText(mActivity, "手机号不一致,请重新获取验证码!");
      return;
    }
    if (!register_passAgain.getText().toString().equals(register_pass.getText().toString())) {
      showSmartToast(R.string.pass_errors, Toast.LENGTH_LONG);
      return;
    }
    if (register_pass.getText().toString().length() < 6
        || register_pass.getText().toString().length() > 16) {
      showSmartToast(R.string.pass_error2, Toast.LENGTH_LONG);
      return;
    }

    if (!box.isChecked()) {
      SmartToast.showText(mActivity, "请同意协议");
      return;
    }
    if (verifyCode == null
        || !verifyCode.getMsgCode().equalsIgnoreCase(inputCode.getText().toString())) {
      toasetUtil.showInfo("请输入正确的验证码!");
      return;
    }
    requetType = 2;
    requestTask(2);
  }
示例#10
0
  protected static CharSequence buildTickerMessage(
      Context context, String address, String subject, String body) {
    String displayAddress = Contact.get(address, true).getName();

    StringBuilder buf =
        new StringBuilder(
            displayAddress == null ? "" : displayAddress.replace('\n', ' ').replace('\r', ' '));
    buf.append(':').append(' ');

    int offset = buf.length();
    if (!TextUtils.isEmpty(subject)) {
      subject = subject.replace('\n', ' ').replace('\r', ' ');
      buf.append(subject);
      buf.append(' ');
    }

    if (!TextUtils.isEmpty(body)) {
      body = body.replace('\n', ' ').replace('\r', ' ');
      buf.append(body);
    }

    SpannableString spanText = new SpannableString(buf.toString());
    spanText.setSpan(new StyleSpan(Typeface.BOLD), 0, offset, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return spanText;
  }
示例#11
0
 private void m1901h() {
   int i = 8;
   Object obj = 1;
   if (this.f1083k == null) {
     LayoutInflater.from(getContext()).inflate(R.abc_action_bar_title_item, this);
     this.f1083k = (LinearLayout) getChildAt(getChildCount() - 1);
     this.f1084l = (TextView) this.f1083k.findViewById(R.action_bar_title);
     this.f1085m = (TextView) this.f1083k.findViewById(R.action_bar_subtitle);
     if (this.f1086n != 0) {
       this.f1084l.setTextAppearance(getContext(), this.f1086n);
     }
     if (this.f1087o != 0) {
       this.f1085m.setTextAppearance(getContext(), this.f1087o);
     }
   }
   this.f1084l.setText(this.f1079g);
   this.f1085m.setText(this.f1080h);
   Object obj2 = !TextUtils.isEmpty(this.f1079g) ? 1 : null;
   if (TextUtils.isEmpty(this.f1080h)) {
     obj = null;
   }
   this.f1085m.setVisibility(obj != null ? 0 : 8);
   LinearLayout linearLayout = this.f1083k;
   if (!(obj2 == null && obj == null)) {
     i = 0;
   }
   linearLayout.setVisibility(i);
   if (this.f1083k.getParent() == null) {
     addView(this.f1083k);
   }
 }
示例#12
0
  public boolean memberOfTagData(String email, String tagId, String memberId) {
    Criterion criterion;
    if (!RemoteModel.isUuidEmpty(memberId) && !TextUtils.isEmpty(email)) {
      criterion =
          Criterion.or(
              TagMemberMetadata.USER_UUID.eq(email), TagMemberMetadata.USER_UUID.eq(memberId));
    } else if (!RemoteModel.isUuidEmpty(memberId)) {
      criterion = TagMemberMetadata.USER_UUID.eq(memberId);
    } else if (!TextUtils.isEmpty(email)) {
      criterion = TagMemberMetadata.USER_UUID.eq(email);
    } else {
      return false;
    }

    TodorooCursor<TagMetadata> count =
        query(
            Query.select(TagMetadata.ID)
                .where(
                    Criterion.and(
                        TagMetadataCriteria.withKey(TagMemberMetadata.KEY),
                        TagMetadata.TAG_UUID.eq(tagId),
                        criterion)));
    try {
      return count.getCount() > 0;
    } finally {
      //
    }
  }
示例#13
0
  /**
   * Retrieve the value of the selected sip uri
   *
   * @return the contact to call as a ToCall object containing account to use and number to call
   */
  public ToCall getValue() {
    String userName = dialUser.getText().toString();
    String toCall = "";
    Long accountToUse = null;
    if (TextUtils.isEmpty(userName)) {
      return null;
    }
    userName = userName.replaceAll("[ \t]", "");
    SipProfile acc = accountChooserButtonText.getSelectedAccount();
    if (acc != null) {
      accountToUse = acc.id;
      // If this is a sip account
      if (accountToUse > SipProfile.INVALID_ID) {
        if (Pattern.matches(".*@.*", userName)) {
          toCall = "sip:" + userName + "";
        } else if (!TextUtils.isEmpty(acc.getDefaultDomain())) {
          toCall = "sip:" + userName + "@" + acc.getDefaultDomain();
        } else {
          toCall = "sip:" + userName;
        }
      } else {
        toCall = userName;
      }
    } else {
      toCall = userName;
    }

    return new ToCall(accountToUse, toCall);
  }
  /**
   * customize cache
   *
   * @param context
   * @param memoryCacheSizeInKB How many memory should use. Will not be greater than 50% of free
   *     memory
   * @param defaultDiskCachePath Default image cache path. Absolute path or a relative path under
   *     cache directory. External cache first. If not specified, using {@link
   *     #DEFAULT_FILE_CACHE_DIR} under cache directory.
   * @param defaultDiskCacheSizeInKB Default disk cache size.
   * @param stableDiskCachePath Path for stable cache directory. Default is {@link
   *     #STABLE_FILE_CACHE_DIR}
   * @param stableDiskCacheSizeInKB Stable disk cache size.
   */
  public static void customizeCache(
      Context context,
      int memoryCacheSizeInKB,
      String defaultDiskCachePath,
      int defaultDiskCacheSizeInKB,
      String stableDiskCachePath,
      int stableDiskCacheSizeInKB) {

    // init memory cache first
    if (memoryCacheSizeInKB > 0) {
      int maxCacheSizeInKB = Math.round(0.5f * Runtime.getRuntime().maxMemory() / 1024);
      memoryCacheSizeInKB = Math.min(memoryCacheSizeInKB, maxCacheSizeInKB);
      sDefaultImageMemoryCache = new DefaultMemoryCache(memoryCacheSizeInKB);
    }

    if (defaultDiskCacheSizeInKB > 0 && !TextUtils.isEmpty(defaultDiskCachePath)) {
      ImageDiskCacheProvider imageFileProvider =
          getImageFileProvider(
              context, defaultDiskCachePath, defaultDiskCacheSizeInKB, DEFAULT_FILE_CACHE_DIR);
      if (imageFileProvider != null) {
        sDefaultImageProvider =
            new ImageProvider(context, getDefaultImageMemoryCache(), imageFileProvider);
      }
    }

    if (stableDiskCacheSizeInKB > 0 && !TextUtils.isEmpty(stableDiskCachePath)) {
      ImageDiskCacheProvider imageFileProvider =
          getImageFileProvider(
              context, stableDiskCachePath, stableDiskCacheSizeInKB, STABLE_FILE_CACHE_DIR);
      if (imageFileProvider != null) {
        sStableImageProvider =
            new ImageProvider(context, getDefaultImageMemoryCache(), imageFileProvider);
      }
    }
  }
示例#15
0
 public String getSimplifiedName() {
   String str2;
   if (this.mSimplifiedName == null) {
     if ((!TextUtils.isEmpty(this.mName)) || (TextUtils.isEmpty(this.mAddress))) break label74;
     int j = this.mAddress.indexOf('@');
     if (j == -1) break label67;
     str2 = this.mAddress.substring(0, j);
     this.mSimplifiedName = str2;
   }
   while (true) {
     return this.mSimplifiedName;
     label67:
     str2 = "";
     break;
     label74:
     if (!TextUtils.isEmpty(this.mName)) {
       for (int i = this.mName.indexOf(' '); (i > 0) && (this.mName.charAt(i - 1) == ','); i--) ;
       if (i < 1) ;
       for (String str1 = this.mName; ; str1 = this.mName.substring(0, i)) {
         this.mSimplifiedName = str1;
         break;
       }
     }
     LogUtils.w(LOG_TAG, "Unable to get a simplified name", new Object[0]);
     this.mSimplifiedName = "";
   }
 }
 @Override
 public Cursor query(
     Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
   Log.d(TAG, "Got query for " + uri);
   if (!TextUtils.isEmpty(selection)) {
     throw new IllegalArgumentException("selection not allowed for " + uri);
   }
   if (selectionArgs != null && selectionArgs.length != 0) {
     throw new IllegalArgumentException("selectionArgs not allowed for " + uri);
   }
   if (!TextUtils.isEmpty(sortOrder)) {
     throw new IllegalArgumentException("sortOrder not allowed for " + uri);
   }
   switch (uriMatcher.match(uri)) {
     case SEARCH_SUGGEST:
       String query = null;
       if (uri.getPathSegments().size() > 1) {
         query = uri.getLastPathSegment();
       }
       Log.d(TAG, "Got suggestions query for " + query);
       return getSuggestions(query);
     default:
       throw new IllegalArgumentException("Unknown URL " + uri);
   }
 }
    @Override
    public void run() {
      if (context == null) context = ZeroMusicApplication.getInstence();
      if (TextUtils.isEmpty(configName) || TextUtils.isEmpty(configKey)) {
        return;
      }

      SharedPreferences.Editor sharedata = context.getSharedPreferences(configName, 0).edit();
      if (configValue instanceof Integer) {
        sharedata.putInt(configKey, (Integer) configValue);
      } else if (configValue instanceof String) {
        sharedata.putString(configKey, (String) configValue);
      } else if (configValue instanceof Boolean) {
        sharedata.putBoolean(configKey, (Boolean) configValue);
      } else if (configValue instanceof Float) {
        sharedata.putFloat(configKey, (Float) configValue);
      } else if (configValue instanceof Long) {
        sharedata.putLong(configKey, (Long) configValue);
      }

      try {
        sharedata.commit();
        if (this.commit != null) {
          this.commit.onSharedataCommit(configKey, configValue);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
示例#18
0
 protected PlayDfeApiContext(
     Context context,
     AndroidAuthenticator authenticator,
     Cache cache,
     String appPackageName,
     String appVersionString,
     int apiVersion,
     Locale locale,
     String mccmnc,
     String clientId,
     String loggingId) {
   this.mHeaders = new HashMap();
   this.mContext = context;
   this.mAuthenticator = authenticator;
   this.mCache = cache;
   this.mHeaders.put(
       "X-DFE-Device-Id", Long.toHexString(((Long) PlayG.androidId.get()).longValue()));
   this.mHeaders.put("Accept-Language", locale.getLanguage() + "-" + locale.getCountry());
   if (!TextUtils.isEmpty(mccmnc)) {
     this.mHeaders.put("X-DFE-MCCMNC", mccmnc);
   }
   if (!TextUtils.isEmpty(clientId)) {
     this.mHeaders.put("X-DFE-Client-Id", clientId);
   }
   if (!TextUtils.isEmpty(clientId)) {
     this.mHeaders.put("X-DFE-Logging-Id", loggingId);
   }
   this.mHeaders.put(
       "User-Agent", makeUserAgentString(appPackageName, appVersionString, apiVersion));
   checkUrlRules();
 }
示例#19
0
 public static String constructNameFromElements(
     int nameOrderType,
     String familyName,
     String middleName,
     String givenName,
     String prefix,
     String suffix) {
   StringBuilder builder = new StringBuilder();
   String[] nameList = sortNameElements(nameOrderType, familyName, middleName, givenName);
   boolean first = true;
   if (!TextUtils.isEmpty(prefix)) {
     first = false;
     builder.append(prefix);
   }
   for (String namePart : nameList) {
     if (!TextUtils.isEmpty(namePart)) {
       if (first) {
         first = false;
       } else {
         builder.append(' ');
       }
       builder.append(namePart);
     }
   }
   if (!TextUtils.isEmpty(suffix)) {
     if (!first) {
       builder.append(' ');
     }
     builder.append(suffix);
   }
   return builder.toString();
 }
  /**
   * 比较版本号
   *
   * @param latestVersion 最新的版本号
   * @param curVersion 当前版本号
   * @return true:最新版本号大于当前版本号
   */
  public static boolean versionLarger(String latestVersion, String curVersion) {
    if (TextUtils.isEmpty(latestVersion) || TextUtils.isEmpty(curVersion)) {
      return false;
    }

    String[] latest = latestVersion.split("\\.");
    String[] cur = curVersion.split("\\.");

    if (latest.length != cur.length) {
      return false;
    }

    for (int i = 0; i < latest.length; i++) {
      try {
        int latestNum = Integer.parseInt(latest[i]);
        int curNum = Integer.parseInt(cur[i]);
        if (latestNum > curNum) {
          return true;
        }
      } catch (Exception e) {
        return false;
      }
    }
    return false;
  }
 @Override
 public void onClick(View v) {
   switch (v.getId()) {
     case R.id.shareqq_commit: // 提交
       final Bundle params = new Bundle();
       params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName.getText().toString());
       params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, title.getText().toString());
       params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION, summary.getText().toString());
       params.putString(GameAppOperation.TROOPBAR_ID, troopbarId.getText().toString());
       String srFileData = imageUrl.getText().toString();
       if (!TextUtils.isEmpty(srFileData)) {
         ArrayList<String> fileDataList = new ArrayList<String>();
         srFileData.replace(" ", "");
         String[] filePaths = srFileData.split(";");
         int size = filePaths.length;
         for (int i = 0; i < size; i++) {
           String path = filePaths[i].trim();
           if (!TextUtils.isEmpty(path)) {
             fileDataList.add(path);
           }
         }
         params.putStringArrayList(GameAppOperation.QQFAV_DATALINE_FILEDATA, fileDataList);
       }
       doShareToTroopBar(params);
       return;
     case R.id.radioBtn_local_image: // 本地图片
       startPickLocaleImage(this);
       return;
     default:
       break;
   }
 }
示例#22
0
  @Override
  public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
      case R.id.btn_register:
        if (TextUtils.isEmpty(mEtUserName.getText().toString().trim())) {
          mEtUserName.setShakeAnimation();
          Toast.makeText(mContext, "请输入用户名", Toast.LENGTH_SHORT).show();
          return;
        }
        if (TextUtils.isEmpty(mEtPassword.getText().toString().trim())) {
          mEtPassword.setShakeAnimation();
          Toast.makeText(mContext, "请输入密码", Toast.LENGTH_SHORT).show();
          return;
        }
        if (TextUtils.isEmpty(mEtEmail.getText().toString().trim())) {
          mEtEmail.setShakeAnimation();
          Toast.makeText(mContext, "请输入邮箱地址", Toast.LENGTH_SHORT).show();
          return;
        }
        if (!StringUtils.isValidEmail(mEtEmail.getText())) {
          mEtEmail.setShakeAnimation();
          Toast.makeText(mContext, "邮箱格式不正确", Toast.LENGTH_SHORT).show();
          return;
        }

        userProxy.setOnSignUpListener(this);
        LogUtils.i(TAG, "register begin....");
        userProxy.signUp(
            mEtUserName.getText().toString().trim(),
            ActivityUtil.Md5(mEtPassword.getText().toString().trim()),
            mEtEmail.getText().toString().trim());
        break;
    }
  }
  /**
   * Appends the given path to the UriBuilder's current path.
   *
   * @param path The path to append onto this UriBuilder's path.
   * @return this UriBuilder object. Useful for chaining.
   */
  public UriBuilder appendToPath(String path) {
    assert path != null;

    if (this.path == null) {
      this.path = new StringBuilder(path);
    } else {
      boolean endsWithSlash =
          TextUtils.isEmpty(this.path)
              ? false
              : this.path.charAt(this.path.length() - 1) == UriBuilder.FORWARD_SLASH;
      boolean pathIsEmpty = TextUtils.isEmpty(path);
      boolean beginsWithSlash = pathIsEmpty ? false : path.charAt(0) == UriBuilder.FORWARD_SLASH;

      if (endsWithSlash && beginsWithSlash) {
        if (path.length() > 1) {
          this.path.append(path.substring(1));
        }
      } else if (!endsWithSlash && !beginsWithSlash) {
        if (!pathIsEmpty) {
          this.path.append(UriBuilder.FORWARD_SLASH).append(path);
        }
      } else {
        this.path.append(path);
      }
    }

    return this;
  }
示例#24
0
  int queryPurchases(Inventory inv, String itemType) throws JSONException, RemoteException {
    // Query purchases
    logDebug("Querying owned items, item type: " + itemType);
    logDebug("Package name: " + mContext.getPackageName());
    boolean verificationFailed = false;
    String continueToken = null;

    do {
      logDebug("Calling getPurchases with continuation token: " + continueToken);
      Bundle ownedItems =
          mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken);

      int response = getResponseCodeFromBundle(ownedItems);
      logDebug("Owned items response: " + String.valueOf(response));
      if (response != BILLING_RESPONSE_RESULT_OK) {
        logDebug("getPurchases() failed: " + getResponseDesc(response));
        return response;
      }
      if (!ownedItems.containsKey(RESPONSE_INAPP_ITEM_LIST)
          || !ownedItems.containsKey(RESPONSE_INAPP_PURCHASE_DATA_LIST)
          || !ownedItems.containsKey(RESPONSE_INAPP_SIGNATURE_LIST)) {
        logError("Bundle returned from getPurchases() doesn't contain required fields.");
        return IABHELPER_BAD_RESPONSE;
      }

      ArrayList<String> ownedSkus = ownedItems.getStringArrayList(RESPONSE_INAPP_ITEM_LIST);
      ArrayList<String> purchaseDataList =
          ownedItems.getStringArrayList(RESPONSE_INAPP_PURCHASE_DATA_LIST);
      ArrayList<String> signatureList =
          ownedItems.getStringArrayList(RESPONSE_INAPP_SIGNATURE_LIST);

      for (int i = 0; i < purchaseDataList.size(); ++i) {
        String purchaseData = purchaseDataList.get(i);
        String signature = signatureList.get(i);
        String sku = ownedSkus.get(i);
        if (Security.verifyPurchase(mSignatureBase64, purchaseData, signature)) {
          logDebug("Sku is owned: " + sku);
          Purchase purchase = new Purchase(itemType, purchaseData, signature);

          if (TextUtils.isEmpty(purchase.getToken())) {
            logWarn("BUG: empty/null token!");
            logDebug("Purchase data: " + purchaseData);
          }

          // Record ownership and token
          inv.addPurchase(purchase);
        } else {
          logWarn("Purchase signature verification **FAILED**. Not adding item.");
          logDebug("   Purchase data: " + purchaseData);
          logDebug("   Signature: " + signature);
          verificationFailed = true;
        }
      }

      continueToken = ownedItems.getString(INAPP_CONTINUATION_TOKEN);
      logDebug("Continuation token: " + continueToken);
    } while (!TextUtils.isEmpty(continueToken));

    return verificationFailed ? IABHELPER_VERIFICATION_FAILED : BILLING_RESPONSE_RESULT_OK;
  }
示例#25
0
  private void decryptCredentials(DatabaseEntry entry, JSONObject jDatabase) {
    String databaseUsername, databasePassword = null;
    // if no encryption key or both username and password are empty, skip encryption
    if (!SettingsManager.getSyncSetting(SettingsManager.SyncKey.sync_credentials)
        || TextUtils.isEmpty(SettingsManager.getEc())
        || (TextUtils.isEmpty(databaseUsername = jDatabase.optString("database_username"))
            && TextUtils.isEmpty(databasePassword = jDatabase.optString("database_password"))))
      return;
    try {
      AesCbcWithIntegrity.SecretKeys keys = AesCbcWithIntegrity.keys(SettingsManager.getEc());

      if (!TextUtils.isEmpty(databaseUsername)) {
        AesCbcWithIntegrity.CipherTextIvMac cipherTextIvMac =
            new AesCbcWithIntegrity.CipherTextIvMac(databaseUsername);
        entry.databaseUsername = AesCbcWithIntegrity.decryptString(cipherTextIvMac, keys);
      }
      if (!TextUtils.isEmpty(databasePassword)) {
        AesCbcWithIntegrity.CipherTextIvMac cipherTextIvMac =
            new AesCbcWithIntegrity.CipherTextIvMac(databasePassword);
        entry.databasePassword = AesCbcWithIntegrity.decryptString(cipherTextIvMac, keys);
      }
    } catch (GeneralSecurityException | UnsupportedEncodingException e) {
      if (SettingsManager.DEBUG()) e.printStackTrace();
      // fail silently on any kind of error
      // user will see warning on database entry when restored without username/password
    }
  }
示例#26
0
  private void updateViews() {
    if (mTitle != null) {
      // Link the title to the entry URL
      SpannableString link = new SpannableString(mTitle);
      if (mUrl != null) {
        int start = 0;
        int end = mTitle.length();
        int flags = 0;
        link.setSpan(new URLSpan(mUrl), start, end, flags);
      }
      mTitleView.setText(link);

      // Show the content, or the summary if no content is available.
      String body =
          !TextUtils.isEmpty(mContent) ? mContent : !TextUtils.isEmpty(mSummary) ? mSummary : "";

      // Show the feed title in the window decorator.
      if (!TextUtils.isEmpty(mTitle)) {
        setTitle(mTitle);
      } else {
        Context context = getContext();
        setTitle(context.getText(R.string.atom_title_entry));
      }

      // Use loadDataWithBaseURL instead of loadData for unsanitized HTML:
      // http://code.google.com/p/android/issues/detail?id=1733
      mContentView.clearView();
      mContentView.loadDataWithBaseURL(null, body, MIME_TYPE, ENCODING, null);
    }
  }
示例#27
0
  public void attemptLogin() {
    String loginName = mNameView.getText().toString();
    String mPassword = mPasswordView.getText().toString();
    boolean cancel = false;
    View focusView = null;

    if (TextUtils.isEmpty(mPassword)) {
      Toast.makeText(this, getString(R.string.error_pwd_required), Toast.LENGTH_SHORT).show();
      focusView = mPasswordView;
      cancel = true;
    }

    if (TextUtils.isEmpty(loginName)) {
      Toast.makeText(this, getString(R.string.error_name_required), Toast.LENGTH_SHORT).show();
      focusView = mNameView;
      cancel = true;
    }

    if (cancel) {
      focusView.requestFocus();
    } else {
      showProgress(true);
      if (imService != null) {
        //				boolean userNameChanged = true;
        //				boolean pwdChanged = true;
        loginName = loginName.trim();
        mPassword = mPassword.trim();
        imService.getLoginManager().login(loginName, mPassword);
      }
    }
  }
示例#28
0
  private void loadDisk(DiskInfo diskInfo, boolean bootIt) {
    this.diskInfo = diskInfo;

    Analytics.trackEvent(
        getApplicationContext(), "Load disk", "" + diskInfo.key, "" + diskInfo.title, 0);

    diskImage = loadFile(new File(getFilesDir(), diskInfo.key));

    // Load the disc and do the disc-start stuff
    if (!TextUtils.isEmpty(diskInfo.bootCmd)) {
      if (bootIt) {
        bbcBreak(0);
      }
      bbcLoadDisc(diskImage, 0);
      keyboardTextWait = 20;
      doFakeKeys(diskInfo.bootCmd);
    } else {
      bbcLoadDisc(diskImage, (bootIt && TextUtils.isEmpty(diskInfo.bootCmd)) ? 1 : 0);
    }

    // Set the right controller for the disk
    ControllerInfo controllerInfo = Controllers.controllersForKnownDisks.get(diskInfo.key);
    if (controllerInfo == null) {
      controllerInfo = Controllers.DEFAULT_CONTROLLER;
    }
    setController(controllerInfo);

    // Show the controller overlay rather than the keyboard
    showKeyboard(KeyboardState.KEYBOARD);
  }
 public static void setUserID(
     Context paramContext,
     String paramString1,
     String paramString2,
     Gender paramGender,
     int paramInt) {
   if (!TextUtils.isEmpty(paramString1)) {
     if (TextUtils.isEmpty(paramString2)) {
       break label55;
     }
     label14:
     if ((paramInt <= 0) || (paramInt >= 200)) {
       break label67;
     }
   }
   for (; ; ) {
     f.a(paramContext).a(paramString1, paramString2, paramInt, paramGender.value);
     return;
     bj.c("MobclickAgent", "userID is null or empty");
     paramString1 = null;
     break;
     label55:
     bj.a("MobclickAgent", "id source is null or empty");
     paramString2 = null;
     break label14;
     label67:
     bj.a("MobclickAgent", "not a valid age!");
     paramInt = -1;
   }
 }
    /**
     * Creates a {@link ContentValues} object for insert or updating a Blog entry.
     *
     * <p>For <i>INSERT</i>, all values will be committed as is. <br>
     * For <i>UPDATE</i>, only values that are <B>NOT NULL</B> will be updated
     *
     * @param update True if this is an UPDATE action, false for INSERT
     * @param title Title of the blog
     * @param url Url of the blog
     * @param user Admin user of the blog
     * @param pass Password for the admin user
     * @return ContentValues for inserting/updating
     */
    public static ContentValues makeContentValues(
        boolean update, String title, String url, String user, String pass) {
      ContentValues values = new ContentValues();

      if (!update) {
        values.put(TITLE, title);
        values.put(URL, url);
        values.put(USER, user);
        values.put(PASS, pass);
      } else {
        if (!TextUtils.isEmpty(title)) {
          values.put(TITLE, title);
        }
        if (!TextUtils.isEmpty(url)) {
          values.put(URL, url);
        }
        if (!TextUtils.isEmpty(user)) {
          values.put(USER, user);
        }
        if (!TextUtils.isEmpty(pass)) {
          values.put(PASS, pass);
        }
      }

      return values;
    }