@Override
  public void onDownloadStart(
      final String url,
      final String userAgent,
      final String contentDisposition,
      final String mimetype,
      long contentLength) {
    String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
    DialogInterface.OnClickListener dialogClickListener =
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            switch (which) {
              case DialogInterface.BUTTON_POSITIVE:
                DownloadHandler.onDownloadStart(
                    mActivity, url, userAgent, contentDisposition, mimetype, false);
                break;

              case DialogInterface.BUTTON_NEGATIVE:
                break;
            }
          }
        };

    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); // dialog
    builder
        .setTitle(fileName)
        .setMessage(mActivity.getResources().getString(R.string.dialog_download))
        .setPositiveButton(
            mActivity.getResources().getString(R.string.action_download), dialogClickListener)
        .setNegativeButton(
            mActivity.getResources().getString(R.string.action_cancel), dialogClickListener)
        .show();
    Log.i(Constants.TAG, "Downloading" + fileName);
  }
 public static InputStream replaceHost(InputStream is, String srcUrl, String dstUrl) {
   if (is == null || !URLUtil.isValidUrl(srcUrl) || !URLUtil.isValidUrl(dstUrl)) {
     return null;
   }
   String srcHost = Uri.parse(srcUrl).getHost();
   Log.d("longer", "src:" + srcHost);
   String dstHost = Uri.parse(dstUrl).getHost();
   Log.d("longer", "dst:" + dstHost);
   BufferedReader br = new BufferedReader(new InputStreamReader(is));
   StringBuilder sb = new StringBuilder();
   String t;
   try {
     while ((t = br.readLine()) != null) {
       if (t.contains(srcHost)) {
         sb.append(t.replace(srcHost, dstHost)).append("\r\n");
       } else {
         sb.append(t).append("\r\n");
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       br.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   Log.d("longer", sb.toString());
   return new ByteArrayInputStream(sb.toString().getBytes());
 }
 private Downloader getDownloader(DownloadRequest request) {
   if (URLUtil.isHttpUrl(request.getSource()) || URLUtil.isHttpsUrl(request.getSource())) {
     return new HttpDownloader(request);
   }
   Log.e(TAG, "Could not find appropriate downloader for " + request.getSource());
   return null;
 }
Example #4
0
 public static String getFileNameFromURL(String url) {
   String fileNameWithExtension = null;
   String fileNameWithoutExtension = null;
   if (URLUtil.isValidUrl(url)) {
     fileNameWithExtension = URLUtil.guessFileName(url, null, null);
     if (fileNameWithExtension != null && !fileNameWithExtension.isEmpty()) {
       String[] f = fileNameWithExtension.split(".");
       if (f != null & f.length > 1) {
         fileNameWithoutExtension = f[0];
       }
     }
   }
   return fileNameWithExtension;
 }
Example #5
0
    public String getFileName() {
      if (fileName == null) {
        // 设置默认的文件名
        // eg.http://example.com/a/b/c.png
        // -->目录/a/b/c.png
        // eg.http://example.com/a/b/c
        // -->目录/a/b/c.png
        if (URLUtil.isValidUrl(url)) {
          URL encodeUrl = null;
          try {
            encodeUrl = new URL(url);
          } catch (MalformedURLException e) {
            e.printStackTrace();
          }
          String path = encodeUrl.getPath();
          Log.e(TAG, "url path is " + path);
          if (path != null && !path.equals("")) {
            // 判断后缀是否有.png
            int dotPos = path.lastIndexOf(".");
            if (dotPos != -1) {

              String suffix = path.substring(dotPos);
              if (!suffix.equals(".png")) {
                path += ".png";
              }
            } else {
              path += ".png";
            }
          }
          fileName = path;
        }
      }
      return fileName;
    }
 private WPEditImageSpan createWPEditImageSpan(Context context, MediaFile mediaFile) {
   if (!URLUtil.isNetworkUrl(mediaFile.getFileURL())) {
     return createWPEditImageSpanLocal(context, mediaFile);
   } else {
     return createWPEditImageSpanRemote(context, mediaFile);
   }
 }
  private CustomEngine getData() {
    CustomEngine data = new CustomEngine();
    data.setName(mEditTextName.getText().toString());
    data.setUpload_url(mEditTextUrl.getText().toString());
    data.setPost_file_key(mEditTextFileKey.getText().toString());
    data.setResult_open_action(mSpinner.getSelectedItemPosition());

    if (!URLUtil.isNetworkUrl(data.getUpload_url())) {
      data.setUpload_url("http://" + data.getUpload_url());
    }

    data.post_text_key.clear();
    data.post_text_value.clear();
    data.post_text_type.clear();

    for (int i = 0; i < mRecyclerView.getChildCount(); i++) {
      View view = mRecyclerView.getChildAt(i);
      if (view == null) continue;
      EditText key = (EditText) view.findViewById(R.id.editText_key);
      EditText value = (EditText) view.findViewById(R.id.editText_value);
      if (key != null && value != null) {
        data.post_text_key.add(key.getEditableText().toString());
        data.post_text_value.add(value.getEditableText().toString());
        data.post_text_type.add(0);
      }
    }
    return data;
  }
  private boolean IsFormValid() {
    CheckBoxPreference chkEnabled = (CheckBoxPreference) findPreference("opengts_enabled");
    EditTextPreference txtOpenGTSServer = (EditTextPreference) findPreference("opengts_server");
    EditTextPreference txtOpenGTSServerPort =
        (EditTextPreference) findPreference("opengts_server_port");
    ListPreference txtOpenGTSCommunicationMethod =
        (ListPreference) findPreference("opengts_server_communication_method");
    EditTextPreference txtOpenGTSServerPath =
        (EditTextPreference) findPreference("autoopengts_server_path");
    EditTextPreference txtOpenGTSDeviceId =
        (EditTextPreference) findPreference("opengts_device_id");

    return !chkEnabled.isChecked()
        || txtOpenGTSServer.getText() != null
            && txtOpenGTSServer.getText().length() > 0
            && txtOpenGTSServerPort.getText() != null
            && isNumeric(txtOpenGTSServerPort.getText())
            && txtOpenGTSCommunicationMethod.getValue() != null
            && txtOpenGTSCommunicationMethod.getValue().length() > 0
            && txtOpenGTSDeviceId.getText() != null
            && txtOpenGTSDeviceId.getText().length() > 0
            && URLUtil.isValidUrl(
                "http://"
                    + txtOpenGTSServer.getText()
                    + ":"
                    + txtOpenGTSServerPort.getText()
                    + txtOpenGTSServerPath.getText());
  }
 public void doDownload() {
   if (mIsCancelled) {
     // if the download has been cancelled, do not download
     // this image, but start the next one
     if (!queuedDownLoaderRequests.isEmpty()
         && runningDownLoaderRequests.size() < maxDownloads) {
       LoaderRequest d = queuedDownLoaderRequests.remove(0);
       d.doDownload();
     }
     return;
   }
   ImageView imageView = mImageViewRef.get();
   if (imageView != null
       && imageView.getTag(DRAWABLE_DOWNLOAD_TAG) == this
       && URLUtil.isNetworkUrl(uri)) {
     mDrawableDownloaderTask = new ApptentiveDownloaderTask(imageView, this);
     try {
       ApptentiveLog.v("ApptentiveAttachmentLoader doDownload: " + uri);
       // Conversation token is needed if the download url is a redirect link from an Apptentive
       // endpoint
       String conversationToken =
           ApptentiveInternal.getInstance().getApptentiveConversationToken();
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
         mDrawableDownloaderTask.executeOnExecutor(
             AsyncTask.THREAD_POOL_EXECUTOR, uri, diskCacheFilePath, conversationToken);
       } else {
         mDrawableDownloaderTask.execute(uri, diskCacheFilePath, conversationToken);
       }
     } catch (RejectedExecutionException e) {
     }
     runningDownLoaderRequests.add(this);
     filesBeingDownloaded.add(diskCacheFilePath);
   }
 }
Example #10
0
 /**
  * 根据服务器给过来的url启动Activity
  *
  * @param context
  * @param url
  */
 public static void startActivity(Context context, String url) {
   if (!TextUtils.isEmpty(url)) {
     Intent intent;
     if (url.contains(SCHEME)) {
       // 跳转内部页面
       // 事件统计
       String event = Uri.parse(url).getQueryParameter("event");
       if (!TextUtils.isEmpty(event)) {
         //                    UmengClickAgent.onEvent(context, event);
       }
       intent = SchemeUtil.getIntent(context, url);
     } else {
       if (URLUtil.isValidUrl(url)) {
         intent =
             new Intent(
                 SystemUtil.getApplicationPackageName(context) + BaseConstant.ACTION_WEB_VIEW);
         intent.putExtra(WebViewFragment.EXTRA_URL, url);
       } else {
         intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
       }
     }
     if (!(context instanceof Activity)) {
       intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     }
     try {
       context.startActivity(intent);
     } catch (ActivityNotFoundException e) { // // TODO: 跳转到首页
       //                context.startActivity(new Intent(Intent.ACTION_VIEW,
       // Uri.parse(getUri(context, R.string.path_main))));
       //                context.startActivity(new
       // Intent(SystemUtil.getApplicationPackageName(context) + BaseConstant.ACTION_MAIN));
       //                LogUtils.e("bacy->" + e);
     }
   }
 }
Example #11
0
 private String getDataSource(String path) throws IOException {
   if (!URLUtil.isNetworkUrl(path)) {
     return path;
   } else {
     URL url = new URL(path);
     URLConnection cn = url.openConnection();
     cn.connect();
     InputStream stream = cn.getInputStream();
     if (stream == null) throw new RuntimeException("stream is null");
     File temp = File.createTempFile("mediaplayertmp", "dat");
     temp.deleteOnExit();
     String tempPath = temp.getAbsolutePath();
     FileOutputStream out = new FileOutputStream(temp);
     byte buf[] = new byte[128];
     do {
       int numread = stream.read(buf);
       if (numread <= 0) break;
       out.write(buf, 0, numread);
     } while (true);
     try {
       stream.close();
     } catch (IOException ex) {
       Log.e(TAG, "error: " + ex.getMessage(), ex);
     }
     return tempPath;
   }
 }
Example #12
0
  /**
   * Replace {@link android.view.View.OnClickListener} with {@link
   * cl.monsoon.s1next.widget.TagHandler.ImageClickableSpan}.
   *
   * <p>See android.text.HtmlToSpannedConverter#startImg(android.text.SpannableStringBuilder,
   * org.xml.sax.Attributes, android.text.Html.ImageGetter)
   */
  private void handleImg(boolean opening, Editable output) {
    if (!opening) {
      int end = output.length();

      // \uFFFC: OBJECT REPLACEMENT CHARACTER
      int len = "\uFFFC".length();
      ImageSpan imageSpan = output.getSpans(end - len, end, ImageSpan.class)[0];

      String url = imageSpan.getSource();
      // replace \uFFFC with ImageSpan's source
      // in order to support url copy when selected
      output.replace(end - len, end, url);

      // image from server doesn't have domain
      // skip this because we don't want to
      // make this image (emoticon or something
      // others) clickable
      if (URLUtil.isNetworkUrl(url)) {

        output.removeSpan(imageSpan);
        // make this ImageSpan clickable
        output.setSpan(
            new ImageClickableSpan(mContext, imageSpan.getDrawable(), url),
            end - len,
            output.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      }
    }
  }
Example #13
0
  private String getMediafilename(FeedMedia media) {
    String filename;
    String titleBaseFilename = "";

    // Try to generate the filename by the item title
    if (media.getItem() != null && media.getItem().getTitle() != null) {
      String title = media.getItem().getTitle();
      // Delete reserved characters
      titleBaseFilename = title.replaceAll("[\\\\/%\\?\\*:|<>\"\\p{Cntrl}]", "");
      titleBaseFilename = titleBaseFilename.trim();
    }

    String URLBaseFilename =
        URLUtil.guessFileName(media.getDownload_url(), null, media.getMime_type());

    if (!titleBaseFilename.equals("")) {
      // Append extension
      final int FILENAME_MAX_LENGTH = 220;
      if (titleBaseFilename.length() > FILENAME_MAX_LENGTH) {
        titleBaseFilename = titleBaseFilename.substring(0, FILENAME_MAX_LENGTH);
      }
      filename =
          titleBaseFilename
              + FilenameUtils.EXTENSION_SEPARATOR
              + FilenameUtils.getExtension(URLBaseFilename);
    } else {
      // Fall back on URL file name
      filename = URLBaseFilename;
    }
    return filename;
  }
  /**
   * Decide the file name of the final download. The file extension is derived from the MIME type.
   *
   * @param url The full URL to the content that should be downloaded.
   * @param mimeType The MIME type of the content reported by the server.
   * @param contentDisposition Content-Disposition HTTP header, if present.
   * @return The best guess of the file name for the downloaded object.
   */
  @VisibleForTesting
  public static String fileName(String url, String mimeType, String contentDisposition) {
    // URLUtil#guessFileName will prefer the MIME type extension over
    // the file extension only if the latter is of a known MIME type.
    // Therefore for things like "file.php" with Content-Type PDF, it will
    // still generate file names like "file.php" instead of "file.pdf".
    // If that's the case, rebuild the file extension from the MIME type.
    String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
    int dotIndex = fileName.lastIndexOf('.');
    if (mimeType != null
        && !mimeType.isEmpty()
        && dotIndex > 1 // at least one char before the '.'
        && dotIndex < fileName.length()) { // '.' should not be the last char
      MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();

      String fileRoot = fileName.substring(0, dotIndex);
      String fileExtension = fileName.substring(dotIndex + 1);
      String fileExtensionMimeType = mimeTypeMap.getMimeTypeFromExtension(fileExtension);

      // If the file extension's official MIME type and {@code mimeType}
      // are the same, simply use the file extension.
      // If not, extension derived from {@code mimeType} is preferred.
      if (mimeType.equals(fileExtensionMimeType)) {
        fileName = fileRoot + "." + fileExtension;
      } else {
        String mimeExtension = mimeTypeMap.getExtensionFromMimeType(mimeType);

        if (mimeExtension != null && !mimeExtension.equals(fileExtension)) {
          fileName = fileRoot + "." + mimeExtension;
        }
      }
    }
    return fileName;
  }
  /*
   * follow editText entry as a url
   */
  private void addAsUrl(final String entry) {
    if (TextUtils.isEmpty(entry)) {
      return;
    }

    // normalize the url and prepend protocol if not supplied
    final String normUrl;
    if (!entry.contains("://")) {
      normUrl = UrlUtils.normalizeUrl("http://" + entry);
    } else {
      normUrl = UrlUtils.normalizeUrl(entry);
    }

    // if this isn't a valid URL, add original entry as a tag
    if (!URLUtil.isNetworkUrl(normUrl)) {
      addAsTag(entry);
      return;
    }

    // make sure it isn't already followed
    if (ReaderBlogTable.isFollowedBlogUrl(normUrl) || ReaderBlogTable.isFollowedFeedUrl(normUrl)) {
      ToastUtils.showToast(this, R.string.reader_toast_err_already_follow_blog);
      return;
    }

    // URL is valid, so follow it
    performAddUrl(normUrl);
  }
Example #16
0
 /**
  * Construct with JSON string. To support versions 0.1.0-0.1.3, this method can also accept a URL.
  *
  * @param json JSON options
  * @throws JSONException
  */
 public AjaxOptions(String json) throws JSONException {
   this();
   if (URLUtil.isValidUrl(json)) {
     this.url = json;
   } else {
     handleJSONOptions(new JSONObject(json));
   }
 }
  @Override
  public boolean shouldOverrideUrlLoading(final WebView view, String url) {
    if (DBG) {
      Log.d(LCAT, "url=" + url);
    }

    if (URLUtil.isAssetUrl(url) || URLUtil.isContentUrl(url) || URLUtil.isFileUrl(url)) {
      // go through the proxy to ensure we're on the UI thread
      webView.getProxy().setProperty("url", url, true);
      return true;
    } else if (url.startsWith(WebView.SCHEME_TEL)) {
      Log.i(LCAT, "Launching dialer for " + url);
      Intent dialer =
          Intent.createChooser(new Intent(Intent.ACTION_DIAL, Uri.parse(url)), "Choose Dialer");
      webView.getProxy().getTiContext().getActivity().startActivity(dialer);
      return true;
    } else if (url.startsWith(WebView.SCHEME_MAILTO)) {
      Log.i(LCAT, "Launching mailer for " + url);
      Intent mailer =
          Intent.createChooser(new Intent(Intent.ACTION_SENDTO, Uri.parse(url)), "Send Message");
      webView.getProxy().getTiContext().getActivity().startActivity(mailer);
      return true;
    } else if (url.startsWith(WebView.SCHEME_GEO)) {
      Log.i(LCAT, "Launching app for " + url);
      /*geo:latitude,longitude
      geo:latitude,longitude?z=zoom
      geo:0,0?q=my+street+address
      geo:0,0?q=business+near+city
      */
      Intent geoviewer =
          Intent.createChooser(new Intent(Intent.ACTION_VIEW, Uri.parse(url)), "Choose Viewer");
      webView.getProxy().getTiContext().getActivity().startActivity(geoviewer);
      return true;
    } else {
      String extension = MimeTypeMap.getFileExtensionFromUrl(url);
      String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
      if (mimeType != null) {
        return shouldHandleMimeType(mimeType, url);
      }

      if (DBG) {
        Log.e(LCAT, "NEED to Handle " + url);
      }
      return super.shouldOverrideUrlLoading(view, url);
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_webview);

    mWebView = (WebView) findViewById(R.id.webview);

    WebSettings settings = mWebView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setLoadWithOverviewMode(true);
    settings.setUseWideViewPort(true);

    mWebView.setWebViewClient(
        new WebViewClient() {
          @Override
          public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (URLUtil.isNetworkUrl(url)) {
              if (mLoadingProgressBar != null) {
                mLoadingProgressBar.setVisibility(View.VISIBLE);
                mLoadingProgressBar.startAnimation(
                    AnimationUtils.loadAnimation(WebViewActivity.this, R.anim.abc_fade_in));
              }
              view.loadUrl(url);
            } else {
              // Otherwise allow the OS to handle things like tel, mailto, etc.
              Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
              startActivity(intent);
            }
            return true;
          }

          @Override
          public void onPageFinished(WebView view, String url) {
            if (mLoadingProgressBar != null) {
              mLoadingProgressBar.setVisibility(View.GONE);
              mLoadingProgressBar.startAnimation(
                  AnimationUtils.loadAnimation(WebViewActivity.this, R.anim.abc_fade_out));
            }
          }
        });

    Intent intent = getIntent();
    if (intent != null) {
      String url = intent.getStringExtra(DATA_URL);
      if (URLUtil.isNetworkUrl(url)) {
        mWebView.loadUrl(url);
      }

      String title = intent.getStringExtra(DATA_TITLE);
      if (!TextUtils.isEmpty(title)) {
        setTitle(title);
      }
    }

    mLoadingProgressBar = getToolbar().findViewById(R.id.toolbar_progress_bar);
    mLoadingProgressBar.setVisibility(View.VISIBLE);
  }
Example #19
0
 public void loadURL(String url) {
   _showLoading();
   if (URLUtil.isNetworkUrl(url)) {
     web.loadUrl(url);
   } else {
     dismissLoading();
     showToast(context.getString(R.string.net_address_error));
   }
 }
Example #20
0
  /** Upgrading device firmware over the air (OTA). */
  public void upgradeFirmware(boolean isStatusCheck) {
    Log.i(TAG, "An upgrade has been requested");
    Context context = this.getApplicationContext();
    Preference.putBoolean(
        context,
        context.getResources().getString(R.string.firmware_status_check_in_progress),
        isStatusCheck);
    Preference.putString(
        context,
        context.getResources().getString(R.string.firmware_download_progress),
        String.valueOf(DEFAULT_STATE_INFO_CODE));
    Preference.putInt(
        context, context.getResources().getString(R.string.operation_id), operationId);

    String schedule = null;
    String server;
    if (command != null && !command.trim().isEmpty()) {
      try {
        JSONObject upgradeData = new JSONObject(command);
        if (!upgradeData.isNull(context.getResources().getString(R.string.alarm_schedule))) {
          schedule =
              (String) upgradeData.get(context.getResources().getString(R.string.alarm_schedule));
        }

        if (!upgradeData.isNull(context.getResources().getString(R.string.firmware_server))) {
          server =
              (String) upgradeData.get(context.getResources().getString(R.string.firmware_server));
          if (URLUtil.isValidUrl(server)) {
            Preference.putString(
                context, context.getResources().getString(R.string.firmware_server), server);
          }
        }
      } catch (JSONException e) {
        Log.e(TAG, "Firmware upgrade payload parsing failed." + e);
      }
    }
    if (schedule != null && !schedule.trim().isEmpty()) {
      Log.i(TAG, "Upgrade has been scheduled to " + schedule);
      Preference.putString(
          context, context.getResources().getString(R.string.alarm_schedule), schedule);
      try {
        AlarmUtils.setOneTimeAlarm(context, schedule, Constants.Operation.UPGRADE_FIRMWARE, null);
      } catch (ParseException e) {
        Log.e(TAG, "One time alarm time string parsing failed." + e);
      }
    } else {
      if (isStatusCheck) {
        Log.i(TAG, "Firmware status check is initiated by admin.");
      } else {
        Log.i(TAG, "Upgrade request initiated by admin.");
      }
      // Prepare for upgrade
      OTADownload otaDownload = new OTADownload(context);
      otaDownload.startOTA();
    }
  }
  private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
      // not ready for playback just yet, will try again later
      return;
    }
    // Tell the music playback service to pause
    // TODO: these constants need to be published somewhere in the framework.
    Intent i = new Intent("com.android.music.musicservicecommand");
    i.putExtra("command", "pause");
    getContext().sendBroadcast(i);

    if (mMediaPlayer != null) {
      mMediaPlayer.reset();
      mMediaPlayer.release();
      mMediaPlayer = null;
    }
    try {
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setOnPreparedListener(mPreparedListener);
      mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
      mIsPrepared = false;
      Log.v(TAG, "reset duration to -1 in openVideo");
      mDuration = -1;
      mMediaPlayer.setOnCompletionListener(mCompletionListener);
      mMediaPlayer.setOnErrorListener(mErrorListener);
      mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
      mCurrentBufferPercentage = 0;
      if (URLUtil.isAssetUrl(mUri.toString())) { // DST: 20090606 detect asset url
        AssetFileDescriptor afd = null;
        try {
          String path = mUri.toString().substring("file:///android_asset/".length());
          afd = getContext().getAssets().openFd(path);
          mMediaPlayer.setDataSource(
              afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        } finally {
          if (afd != null) {
            afd.close();
          }
        }
      } else {
        setDataSource();
      }
      mMediaPlayer.setDisplay(mSurfaceHolder);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mMediaPlayer.setScreenOnWhilePlaying(true);
      mMediaPlayer.prepareAsync();
      attachMediaController();
    } catch (IOException ex) {
      Log.w(TAG, "Unable to open content: " + mUri, ex);
      return;
    } catch (IllegalArgumentException ex) {
      Log.w(TAG, "Unable to open content: " + mUri, ex);
      return;
    }
  }
  @Override
  public boolean shouldOverrideUrlLoading(final WebView view, String url) {
    if (DBG) {
      Log.d(LCAT, "url=" + url);
    }

    if (URLUtil.isAssetUrl(url) || URLUtil.isContentUrl(url) || URLUtil.isFileUrl(url)) {
      TitaniumWebView twv = (TitaniumWebView) view;
      twv.loadFromSource(url, null);
      return true;
    } else if (URLUtil.isNetworkUrl(url)) {
      Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
      i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      view.getContext().startActivity(i);
      return true;
    } else {
      if (DBG) {
        Log.e(LCAT, "NEED to Handle " + url);
      }
    }

    return false;
  }
Example #23
0
  protected void initialize() throws IOException {
    try {
      mp = new MediaPlayer();
      String url = TiConvert.toString(proxy.getProperty(TiC.PROPERTY_URL));
      if (URLUtil.isAssetUrl(url)) {
        Context context = proxy.getTiContext().getTiApp();
        String path = url.substring(TiConvert.ASSET_URL.length());
        AssetFileDescriptor afd = null;
        try {
          afd = context.getAssets().openFd(path);
          // Why mp.setDataSource(afd) doesn't work is a problem for another day.
          // http://groups.google.com/group/android-developers/browse_thread/thread/225c4c150be92416
          mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        } catch (IOException e) {
          Log.e(LCAT, "Error setting file descriptor: ", e);
        } finally {
          if (afd != null) {
            afd.close();
          }
        }
      } else {
        Uri uri = Uri.parse(url);
        if (uri.getScheme().equals(TiC.PROPERTY_FILE)) {
          mp.setDataSource(uri.getPath());
        } else {
          remote = true;
          mp.setDataSource(url);
        }
      }

      mp.setLooping(looping);
      mp.setOnCompletionListener(this);
      mp.setOnErrorListener(this);
      mp.setOnInfoListener(this);
      mp.setOnBufferingUpdateListener(this);

      mp.prepare(); // Probably need to allow for Async
      setState(STATE_INITIALIZED);

      setVolume(volume);
      if (proxy.hasProperty(TiC.PROPERTY_TIME)) {
        setTime(TiConvert.toInt(proxy.getProperty(TiC.PROPERTY_TIME)));
      }
    } catch (Throwable t) {
      Log.w(LCAT, "Issue while initializing : ", t);
      release();
      setState(STATE_STOPPED);
    }
  }
    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
      ContentValues audioCat = AudioCatListActivity.this.audioCat.get(position);
      holder.txtCatName.setText(audioCat.getAsString("catName"));

      final File destination =
          new File(
              SmartUtils.getAnoopamMissionImageStorage()
                  + File.separator
                  + URLUtil.guessFileName(audioCat.getAsString("catImage"), null, null));
      final Uri downloadUri = Uri.parse(audioCat.getAsString("catImage").replaceAll(" ", "%20"));

      DataDownloadUtil.downloadImageFromServerAndRender(
          downloadUri, destination, holder.imgAudioCat);
    }
Example #25
0
  public void doNav() {

    String url = urlField.getText().toString();

    if (URLUtil.isValidUrl(url) == false) {
      url = "http://" + url;
    }

    urlField.setText(url);

    webView.requestFocus();

    webView.loadUrl(url);

    navbar.startAnimation(slideUp);
  }
  // Attempts to retrieve the xmlrpc url for a self-hosted site, in this order:
  // 1: Try to retrieve it by finding the ?rsd url in the site's header
  // 2: Take whatever URL the user entered to see if that returns a correct response
  // 3: Finally, just guess as to what the xmlrpc url should be
  private String getSelfHostedXmlrpcUrl(String url) {
    String xmlrpcUrl;

    // Convert IDN names to punycode if necessary
    url = UrlUtils.convertUrlToPunycodeIfNeeded(url);

    // Add http to the beginning of the URL if needed
    url = UrlUtils.addUrlSchemeIfNeeded(url, false);

    if (!URLUtil.isValidUrl(url)) {
      mErrorMsgId = org.wordpress.android.R.string.invalid_url_message;
      return null;
    }

    // Attempt to get the XMLRPC URL via RSD
    String rsdUrl;
    try {
      rsdUrl = UrlUtils.addUrlSchemeIfNeeded(getRsdUrl(url), false);
    } catch (SSLHandshakeException e) {
      if (!UrlUtils.getDomainFromUrl(url).endsWith("wordpress.com")) {
        mErroneousSslCertificate = true;
      }
      AppLog.w(T.NUX, "SSLHandshakeException failed. Erroneous SSL certificate detected.");
      return null;
    }

    try {
      if (rsdUrl != null) {
        xmlrpcUrl = UrlUtils.addUrlSchemeIfNeeded(ApiHelper.getXMLRPCUrl(rsdUrl), false);
        if (xmlrpcUrl == null) {
          xmlrpcUrl = UrlUtils.addUrlSchemeIfNeeded(rsdUrl.replace("?rsd", ""), false);
        }
      } else {
        xmlrpcUrl = UrlUtils.addUrlSchemeIfNeeded(getXmlrpcByUserEnteredPath(url), false);
      }
    } catch (SSLHandshakeException e) {
      if (!UrlUtils.getDomainFromUrl(url).endsWith("wordpress.com")) {
        mErroneousSslCertificate = true;
      }
      AppLog.w(T.NUX, "SSLHandshakeException failed. Erroneous SSL certificate detected.");
      return null;
    }

    return xmlrpcUrl;
  }
  private String findFirstUrl(@Nullable CharSequence text) {
    if (text == null) {
      return null;
    }

    final Matcher matcher =
        Pattern.compile(
                "\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))",
                Pattern.CASE_INSENSITIVE)
            .matcher(text);
    while (matcher.find()) {
      final String url = matcher.group();
      if (URLUtil.isValidUrl(url)) {
        return url;
      }
    }
    return null;
  }
 public void playAudioImpl(Bundle bundle, Activity activity) {
   PlayerProperties playerProperties =
       (PlayerProperties) bundle.getParcelable(IMWebView.PLAYER_PROPERTIES);
   String string = bundle.getString(IMWebView.EXPAND_URL);
   if (string == null) {
     string = AdTrackerConstants.BLANK;
   }
   if (!a(playerProperties.id, string, activity)) {
     return;
   }
   if ((string.length() != 0 && !URLUtil.isValidUrl(string))
       || (string.length() == 0 && !this.audioPlayerList.containsKey(playerProperties.id))) {
     this.a.raiseError("Request must specify a valid URL", "playAudio");
   } else if (this.audioplayer != null) {
     if (string.length() != 0) {
       this.audioplayer.setPlayData(playerProperties, string);
     }
     this.audioPlayerList.put(playerProperties.id, this.audioplayer);
     FrameLayout frameLayout = (FrameLayout) activity.findViewById(16908290);
     if (playerProperties.isFullScreen()) {
       LayoutParams layoutParams =
           new RelativeLayout.LayoutParams(
               WrapperFunctions.getParamFillParent(), WrapperFunctions.getParamFillParent());
       layoutParams.addRule(R.styleable.MapAttrs_zOrderOnTop);
       this.audioplayer.setLayoutParams(layoutParams);
       View relativeLayout = new RelativeLayout(activity);
       relativeLayout.setOnTouchListener(new g());
       relativeLayout.setBackgroundColor(-16777216);
       frameLayout.addView(
           relativeLayout,
           new RelativeLayout.LayoutParams(
               WrapperFunctions.getParamFillParent(), WrapperFunctions.getParamFillParent()));
       relativeLayout.addView(this.audioplayer);
       this.audioplayer.setBackGroundLayout(relativeLayout);
       this.audioplayer.requestFocus();
       this.audioplayer.setOnKeyListener(new c());
     } else {
       this.audioplayer.setLayoutParams(new LayoutParams(1, 1));
       frameLayout.addView(this.audioplayer);
     }
     this.audioplayer.setListener(new a(playerProperties));
     this.audioplayer.play();
   }
 }
Example #29
0
  @Override
  public void processProperties(TiDict d) {
    TiImageView view = getView();

    if (d.containsKey("images")) {
      Object o = d.get("images");
      if (o instanceof Object[]) {
        setImages((Object[]) o);
      }
    } else if (d.containsKey("url")) {
      Log.w(LCAT, "The url property of ImageView is deprecated, use image instead.");
      if (!d.containsKey("image")) {
        d.put("image", d.get("url"));
      }
    }
    if (d.containsKey("canScale")) {
      view.setCanScaleImage(TiConvert.toBoolean(d, "canScale"));
    }
    if (d.containsKey("enableZoomControls")) {
      view.setEnableZoomControls(TiConvert.toBoolean(d, "enableZoomControls"));
    }
    if (d.containsKey("image")) {
      Object image = d.get("image");
      if (image instanceof String) {
        String imageURL = TiConvert.toString(d, "image");
        if (URLUtil.isNetworkUrl(imageURL)) {
          synchronized (imageTokenGenerator) {
            token = imageTokenGenerator.incrementAndGet();
            getView().setImageDrawable(null);
            new BgImageLoader(getProxy().getTiContext(), null, null, token).load(imageURL);
          }
        } else {
          setImage(createBitmap(imageURL));
        }
      } else {
        setImage(createBitmap(image));
      }

    } else {
      getProxy().internalSetDynamicValue("image", null, false);
    }

    super.processProperties(d);
  }
 private boolean a(String str, String str2, Activity activity, Dimensions dimensions) {
   if (this.videoPlayer == null || !str.equalsIgnoreCase(this.videoPlayer.getPropertyID())) {
     return b(str, str2, activity);
   }
   playerState state = this.videoPlayer.getState();
   if (str.equalsIgnoreCase(this.videoPlayer.getPropertyID())) {
     String mediaURL = this.videoPlayer.getMediaURL();
     if (str2.length() == 0 || str2.equalsIgnoreCase(mediaURL)) {
       switch (d.a[state.ordinal()]) {
         case GoogleScorer.CLIENT_GAMES:
           this.videoPlayer.start();
           a(this.videoPlayer, dimensions);
           return false;
         case GoogleScorer.CLIENT_PLUS:
           a(this.videoPlayer, dimensions);
           return false;
         case IabHelper.BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE:
           if (!this.videoPlayer.getProperties().doLoop()) {
             this.videoPlayer.start();
           }
           a(this.videoPlayer, dimensions);
           return false;
         case GoogleScorer.CLIENT_APPSTATE:
           if (this.videoPlayer.isPrepared()) {
             this.videoPlayer.start();
           } else {
             this.videoPlayer.setAutoPlay(true);
           }
           a(this.videoPlayer, dimensions);
           return false;
         default:
           return false;
       }
     } else if (URLUtil.isValidUrl(str2)) {
       this.videoPlayer.releasePlayer(false);
       this.videoPlayer = new AVPlayer(activity, this.a);
     } else {
       this.a.raiseError("Request must specify a valid URL", "playVideo");
       return false;
     }
   }
   return true;
 }