private void fillData(@Nullable Intent intent, @NonNull TextView textView) {
    Uri data = intent == null ? null : intent.getData();
    if (data == null) {
      textView.setText(Printer.EMPTY);
      return;
    }

    Truss truss = new Truss();
    Printer.append(truss, "raw", data);
    Printer.append(truss, "scheme", data.getScheme());
    Printer.append(truss, "host", data.getHost());
    Printer.append(truss, "port", data.getPort());
    Printer.append(truss, "path", data.getPath());
    Printer.appendKey(truss, "query");
    boolean query = false;
    if (data.isHierarchical()) {
      for (String queryParameterName : data.getQueryParameterNames()) {
        Printer.appendSecondary(
            truss, queryParameterName, data.getQueryParameter(queryParameterName));
        query = true;
      }
    }
    if (!query) {
      Printer.appendValue(truss, null);
    }
    Printer.append(truss, "fragment", data.getFragment());
    textView.setText(truss.build());
  }
コード例 #2
0
  /** @return a uri which can be used for logging (i.e. with credentials masked) */
  public String getStoreUriForLogging() {
    Uri uri = Uri.parse(this.uri);
    String userInfo = uri.getUserInfo();

    if (!TextUtils.isEmpty(userInfo) && userInfo.contains(":")) {
      String[] parts = userInfo.split(":", 2);
      userInfo = parts[0] + ":" + (parts[1].replaceAll(".", "X"));
      String host = uri.getHost();
      if (uri.getPort() != -1) {
        host += ":" + uri.getPort();
      }
      return uri.buildUpon().encodedAuthority(userInfo + "@" + host).toString();
    } else {
      return uri.toString();
    }
  }
コード例 #3
0
ファイル: Whitelist.java プロジェクト: rstn40/arsnova-mobile
 public boolean matches(Uri uri) {
   try {
     return ((scheme == null || scheme.matcher(uri.getScheme()).matches())
         && (host == null || host.matcher(uri.getHost()).matches())
         && (port == null || port.equals(uri.getPort()))
         && (path == null || path.matcher(uri.getPath()).matches()));
   } catch (Exception e) {
     LOG.d(TAG, e.toString());
     return false;
   }
 }
コード例 #4
0
  public static ShadowsocksConfig parse(String proxyInfo) throws Exception {
    ShadowsocksConfig config = new ShadowsocksConfig();
    Uri uri = Uri.parse(proxyInfo);
    if (uri.getPort() == -1) {
      String base64String = uri.getHost();
      proxyInfo =
          "ss://" + new String(Base64.decode(base64String.getBytes("ASCII"), Base64.DEFAULT));
      uri = Uri.parse(proxyInfo);
    }

    String userInfoString = uri.getUserInfo();
    if (userInfoString != null) {
      String[] userStrings = userInfoString.split(":");
      config.EncryptMethod = userStrings[0];
      if (userStrings.length >= 2) {
        config.Password = userStrings[1];
      }
    }
    config.ServerAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    config.Encryptor = EncryptorFactory.createEncryptorByConfig(config);
    return config;
  }
コード例 #5
0
ファイル: XpraActivity.java プロジェクト: svn2github/Xpra
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.setContentView(R.layout.draggable);
    this.mDragController = new DragController(this);
    this.setupViews();
    Log.i(this.TAG, "onCreate(" + savedInstanceState + ")");

    Intent intent = this.getIntent();
    Uri uri = intent.getData();
    if (uri != null) {
      Log.e(this.TAG, "onCreate(" + savedInstanceState + ") parsing uri: " + uri);
      this.host = uri.getHost();
      this.port = uri.getPort();
      String pwd = uri.getQueryParameter("password");
      try {
        this.password = pwd == null ? null : pwd.getBytes("UTF-8");
      } catch (UnsupportedEncodingException e) {
        Log.e(this.TAG, "onCreate(" + savedInstanceState + ") failed to parse password as UTF-8");
      }
    } else {
      Bundle extras = getIntent().getExtras();
      if (extras == null) {
        Log.e(this.TAG, "onCreate(" + savedInstanceState + ") missing extras");
        this.finish();
        return;
      }
      this.host = extras.getString(PARAM_HOST);
      this.port = extras.getInt(PARAM_PORT);
      this.password = extras.getByteArray(PARAM_PASSWORD);
    }
    Log.i(this.TAG, "onCreate(" + savedInstanceState + ") target: " + this.host + ":" + this.port);
    if (this.host == null || this.host.length() == 0 || this.port <= 0) {
      Log.e(
          this.TAG,
          "onCreate(" + savedInstanceState + ") invalid target: " + this.host + ":" + this.port);
      this.toast(
          "Invalid target specified: " + this.host + ":" + this.port + ", cannot launch Xpra");
      this.finish();
      return;
    }
    MemoryInfo info = new MemoryInfo();
    ActivityManager activityManager =
        (ActivityManager) this.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
    if (activityManager != null) {
      activityManager.getMemoryInfo(info);
      Log.i(this.TAG, "onCreate(" + savedInstanceState + ") memory info=" + info);
    }
  }
コード例 #6
0
  // Added to detect HTTP redirects before we hand off to MediaPlayer
  // See: http://code.google.com/p/android/issues/detail?id=10810
  private void setDataSource() {
    try {
      if (mUri.getScheme().equals("http") || mUri.getScheme().equals("https")) {
        // Media player doesn't handle redirects, try to follow them here
        while (true) {
          // java.net.URL doesn't handle rtsp
          if (mUri.getScheme() != null && mUri.getScheme().equals("rtsp")) break;

          URL url = new URL(mUri.toString());
          HttpURLConnection cn = (HttpURLConnection) url.openConnection();
          cn.setInstanceFollowRedirects(false);
          String location = cn.getHeaderField("Location");
          if (location != null) {
            String host = mUri.getHost();
            int port = mUri.getPort();
            String scheme = mUri.getScheme();
            mUri = Uri.parse(location);
            if (mUri.getScheme() == null) {
              // Absolute URL on existing host/port/scheme
              if (scheme == null) {
                scheme = "http";
              }
              String authority = port == -1 ? host : host + ":" + port;
              mUri = mUri.buildUpon().scheme(scheme).encodedAuthority(authority).build();
            }
          } else {
            break;
          }
        }
      }
      mMediaPlayer.setDataSource(getContext(), mUri);
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SecurityException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalStateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #7
0
  /* (non-Javadoc)
   * @see org.appcelerator.titanium.module.ITitaniumHttpClient#open(java.lang.String, java.lang.String)
   */
  public void open(String method, String url) throws MethodNotSupportedException {
    if (DBG) {
      Log.d(LCAT, "open request method=" + method + " url=" + url);
    }
    TitaniumWebView wv = softWebView.get();
    if (wv != null) {
      me.syncId = wv.registerLock();
    }

    request = new DefaultHttpRequestFactory().newHttpRequest(method, url);
    Uri uri = Uri.parse(url);
    host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    if (uri.getUserInfo() != null) {
      credentials = new UsernamePasswordCredentials(uri.getUserInfo());
    }
    setReadyState(READY_STATE_LOADING, syncId);
    setRequestHeader("User-Agent", userAgent);
    setRequestHeader("X-Requested-With", "XMLHttpRequest");
  }
コード例 #8
0
ファイル: FileHelper.java プロジェクト: mtparet/apg
  /**
   * Get a file path from a Uri.
   *
   * <p>from https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/
   * afilechooser/utils/FileUtils.java
   *
   * @param context
   * @param uri
   * @return
   * @author paulburke
   */
  public static String getPath(Context context, Uri uri) {

    Log.d(
        Constants.TAG + " File -",
        "Authority: "
            + uri.getAuthority()
            + ", Fragment: "
            + uri.getFragment()
            + ", Port: "
            + uri.getPort()
            + ", Query: "
            + uri.getQuery()
            + ", Scheme: "
            + uri.getScheme()
            + ", Host: "
            + uri.getHost()
            + ", Segments: "
            + uri.getPathSegments().toString());

    if ("content".equalsIgnoreCase(uri.getScheme())) {
      String[] projection = {"_data"};
      Cursor cursor = null;

      try {
        cursor = context.getContentResolver().query(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow("_data");
        if (cursor.moveToFirst()) {
          return cursor.getString(column_index);
        }
      } catch (Exception e) {
        // Eat it
      }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
      return uri.getPath();
    }

    return null;
  }
コード例 #9
0
  public void open(String method, String url) {
    if (DBG) {
      Log.d(LCAT, "open request method=" + method + " url=" + url);
    }

    this.method = method;

    String cleanUrl = url;
    if (url.startsWith("http")) {
      int beginQ = url.indexOf('?');
      if (beginQ > 7 && url.length() > beginQ) {
        String left = url.substring(0, beginQ);
        String right = url.substring(beginQ + 1);
        // first decoding below, in case it's partially encoded already.
        cleanUrl = Uri.encode(Uri.decode(left), ":/") + "?" + Uri.encode(Uri.decode(right), "&=#");
      } else {
        cleanUrl = Uri.encode(Uri.decode(url), ":/#");
      }
    }

    uri = Uri.parse(cleanUrl);

    host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    if (uri.getUserInfo() != null) {
      credentials = new UsernamePasswordCredentials(uri.getUserInfo());
    }
    setReadyState(READY_STATE_OPENED);
    setRequestHeader("User-Agent", (String) proxy.getDynamicValue("userAgent"));
    // Causes Auth to Fail with twitter and other size apparently block X- as well
    // Ticket #729, ignore twitter for now
    if (!uri.getHost().contains("twitter.com")) {
      setRequestHeader("X-Requested-With", "XMLHttpRequest");
    } else {
      Log.i(LCAT, "Twitter: not sending X-Requested-With header");
    }
  }
コード例 #10
0
  private void parseMessage(String message) {
    if (!message.startsWith(JS_BRIDGE_PROTOCOL_SCHEMA)) {
      return;
    }
    // ------->
    // rock://LoginHandler:8888/Add?{msg:'我是小三',data:{userName:'******',passWord:'******'}}
    Uri uri = Uri.parse(message);
    mClassName = uri.getHost();
    mPort = String.valueOf(uri.getPort());

    String path = uri.getPath();
    if (!TextUtils.isEmpty(path)) {
      mMethodName = path.replace("/", "");
    } else {
      mMethodName = "";
    }

    try {
      mParams = new JSONObject(uri.getQuery());
    } catch (JSONException e) {
      e.printStackTrace();
      mParams = new JSONObject();
    }
  }
コード例 #11
0
  public FavDialog(Context c, Favorite f_, FavsAdapter owner_) {
    try {
      owner = owner_;
      f = f_;
      uri = f.getUri();
      if (uri == null) return;
      LayoutInflater factory = LayoutInflater.from(c);
      View fdv = factory.inflate(R.layout.server, null);
      if (fdv == null) return;
      View bb = fdv.findViewById(R.id.buttons_block);
      bb.setVisibility(View.GONE);
      View cb = fdv.findViewById(R.id.comment_block);
      cb.setVisibility(View.VISIBLE);
      ce = (EditText) cb.findViewById(R.id.comment_edit);
      ce.setText(f.getComment());

      pe = (EditText) fdv.findViewById(R.id.path_edit);
      String path = uri.getPath();
      /*
      String quer = uri.getQuery();
      if( quer != null )
          path += "?" + quer;
      String frag = uri.getFragment();
      if( frag != null )
          path += "#" + frag;
      */
      pe.setText(path);

      String schm = uri.getScheme();
      View sb = fdv.findViewById(R.id.server_block);
      View db = fdv.findViewById(R.id.domainbrowse_block);
      View ib = fdv.findViewById(R.id.credentials_block);
      View fb = fdv.findViewById(R.id.ftp_block);

      sftp = "sftp".equals(schm);
      ftp = "ftp".equals(schm);
      smb = "smb".equals(schm);
      if (ftp || smb || sftp) {
        se = (EditText) sb.findViewById(R.id.server_edit);
        String host = uri.getHost();
        if (host != null) {
          int port = uri.getPort();
          if (port > 0) host += ":" + port;
          se.setText(host);
        }
        if (ftp || sftp) {
          db.setVisibility(View.GONE);
        }
        String username = f.getUserName();

        if (smb && username != null) {
          int sep = username.indexOf('\\');
          if (sep < 0) sep = username.indexOf(';');
          de = (EditText) ib.findViewById(R.id.domain_edit);
          if (sep >= 0) {
            de.setText(username.substring(0, sep));
            username = username.substring(sep + 1);
          }
        }
        ue = (EditText) ib.findViewById(R.id.username_edit);
        ue.setText(username);
        we = (EditText) ib.findViewById(R.id.password_edit);
        we.setText(f.getPassword());
        fb.setVisibility(ftp ? View.VISIBLE : View.GONE);
        if (ftp) {
          en = (Spinner) fb.findViewById(R.id.encoding);
          ArrayAdapter<CharSequence> adapter =
              ArrayAdapter.createFromResource(
                  c, R.array.encoding, android.R.layout.simple_spinner_item);
          adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
          en.setAdapter(adapter);
          try {
            String enc_s = uri.getQueryParameter("e");
            if (Utils.str(enc_s) && !"Default".equals(enc_s)) {
              for (int i = 0; i < adapter.getCount(); i++)
                if (adapter.getItem(i).toString().indexOf(enc_s) == 0) {
                  en.setSelection(i);
                  break;
                }
            }
          } catch (Exception e) {
            Log.e(TAG, "", e);
          }
          active_ftp_cb = (CheckBox) fb.findViewById(R.id.active);
          String a_s = uri.getQueryParameter("a");
          active_ftp_cb.setChecked("true".equals(a_s));
        }
      } else {
        sb.setVisibility(View.GONE);
        db.setVisibility(View.GONE);
        ib.setVisibility(View.GONE);
        fb.setVisibility(View.GONE);
      }

      new AlertDialog.Builder(c)
          .setTitle(c.getString(R.string.fav_dialog))
          .setView(fdv)
          .setPositiveButton(R.string.dialog_ok, this)
          .setNegativeButton(R.string.dialog_cancel, this)
          .show();
    } catch (Exception e) {
      Log.e(TAG, null, e);
    }
  }
コード例 #12
0
ファイル: News.java プロジェクト: quangnguyennq/android
  String getAdditionInfo(String url) {
    String s = "";
    if (url.contains("bongda")) {
      try {
        HtmlCleaner cleaner = new HtmlCleaner();
        String id = url.substring(url.lastIndexOf("/"));
        id = id.substring(1, id.indexOf("."));
        Uri ss = Uri.parse("http://m.bongdaplus.vn/Story.aspx?sid=" + id);

        URI fine =
            new URI(
                ss.getScheme(),
                ss.getUserInfo(),
                ss.getHost(),
                ss.getPort(),
                ss.getPath(),
                ss.getQuery(),
                ss.getFragment());
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
        HttpGet httpget = new HttpGet(fine);
        httpget.addHeader(
            "user-agent", "Mozilla/5.0 (Linux; U; Android 2.3.3) Gecko/20100101 Firefox/8.0");
        httpget.addHeader("accept-language", "en-us,en;q=0.5");
        HttpResponse response = httpclient.execute(httpget);
        InputStream binaryreader = new BufferedInputStream(response.getEntity().getContent());
        BufferedReader buf = new BufferedReader(new InputStreamReader(binaryreader));
        String sss;
        StringBuilder sb = new StringBuilder();
        while ((sss = buf.readLine()) != null) {
          sb.append(sss);
        }

        //	    		URL u = new URL(ss.getScheme(), ss.getHost(), ss.getPort(), ss.getPath());
        TagNode root = cleaner.clean(sb.toString());
        TagNode div = root.findElementByAttValue("class", "story-body", true, false);
        TagNode[] child = div.getElementsByName("strong", true);
        for (int i = 0; i < child.length; i++) child[i].removeFromTree();
        child = div.getElementsByAttValue("class", "listing", true, false);
        for (int i = 0; i < child.length; i++) child[i].removeFromTree();
        child = div.getElementsByName("ul", true);
        for (int i = 0; i < child.length; i++) child[i].removeFromTree();
        child = div.getElementsByName("img", true);
        for (int i = 0; i < child.length; i++)
          child[i].setAttribute("style", "width: 100%; height: auto;");
        s = cleaner.getInnerHtml(div);
        if (s.indexOf("VideoPlaying(") > 0) {
          int x = s.indexOf("VideoPlaying(");
          int st = s.indexOf("'", x);
          int en = s.indexOf("'", st + 1);
          String urlvideo = "http://bongdaplus.vn" + s.substring(st + 1, en);
          s = s + "<a href=\"" + urlvideo + "\"> Video </a></br></br>";
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (url.contains("teamtalk")) {
      try {
        HtmlCleaner cleaner = new HtmlCleaner();
        Uri ss = Uri.parse(url);
        URL u = new URL(ss.getScheme(), ss.getHost(), ss.getPort(), ss.getPath());
        TagNode root = cleaner.clean(u);
        TagNode div = root.findElementByAttValue("class", "tt-article-text", true, false);
        TagNode[] child = div.getElementsByName("p", true);
        for (int i = 0; i < child.length; i++)
          if (child[i].hasAttribute("class") || child[i].hasAttribute("style"))
            child[i].removeFromTree();
        child = div.getElementsByName("img", true);
        for (int i = 0; i < child.length; i++)
          child[i].setAttribute("style", "max-width: 80%; height: auto;");
        s = cleaner.getInnerHtml(div);
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (url.contains("licheuro")) {
      try {
        HtmlCleaner cleaner = new HtmlCleaner();
        Uri ss = Uri.parse(url);
        URL u = new URL(ss.getScheme(), ss.getHost(), ss.getPort(), ss.getPath());
        TagNode root = cleaner.clean(u);
        TagNode div = root.findElementByAttValue("class", "entry", true, false);

        TagNode[] child = div.getElementsByName("span", true);
        for (int i = 0; i < child.length; i++) child[i].removeFromTree();
        child = div.getElementsByName("strong", true);
        for (int i = 0; i < child.length; i++) {
          child[i].getParent().addChildren(child[i].getChildren());
          child[i].getParent().addChild(child[i].getText());
          child[i].removeFromTree();
        }
        child = div.getElementsByName("h1", true);
        for (int i = 0; i < child.length; i++) {
          child[i].getParent().addChildren(child[i].getChildren());
          child[i].getParent().addChild(child[i].getText());
          child[i].removeFromTree();
        }
        child = div.getElementsByAttValue("class", "boxpost", true, true);
        for (int i = 0; i < child.length; i++) child[i].removeFromTree();
        child = div.getElementsByAttValue("class", "ratingblock ", true, true);
        for (int i = 0; i < child.length; i++) child[i].removeFromTree();
        child = div.getElementsByName("iframe", true);
        for (int i = 0; i < child.length; i++) child[i].removeFromTree();
        child = div.getElementsByName("blockqoute", true);
        for (int i = 0; i < child.length; i++) {
          child[i].getParent().addChildren(child[i].getChildren());
          child[i].removeFromTree();
        }

        child = div.getElementsByAttValue("class", "dd_outer", true, true);
        for (int i = 0; i < child.length; i++) child[i].removeFromTree();
        child = div.getElementsByAttValue("id", "fb-root", true, true);
        for (int i = 0; i < child.length; i++) child[i].removeFromTree();
        child = div.getElementsByAttValue("id", "fbSEOComments", true, true);
        for (int i = 0; i < child.length; i++) child[i].removeFromTree();
        child = div.getElementsByAttValue("id", "ajax_comments_wrapper", true, true);
        for (int i = 0; i < child.length; i++) child[i].removeFromTree();
        child = div.getElementsByName("table", true);
        for (int i = 0; i < child.length; i++) {
          child[i].setAttribute("style", "max-width: 100%; height: auto;");
          child[i].setAttribute("width", "100%");
        }
        child = div.getElementsByName("script", true);
        for (int i = 0; i < child.length; i++) child[i].removeFromTree();
        child = div.getElementsByName("img", true);
        for (int i = 0; i < child.length; i++)
          child[i].setAttribute("style", "max-width: 80%; height: auto;");
        s = cleaner.getInnerHtml(div);
        if (s.indexOf("\"file\":") > 0) {
          int x = s.indexOf("\"file\":");
          int st = s.indexOf("http", x);
          int en = s.indexOf("\"", st + 1);
          String urlvideo = s.substring(st, en);
          s = s + "<a href=\"" + urlvideo + "\"> Video </a></br></br>";
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    System.out.println(s);
    return s;
  }
コード例 #13
0
  void parseFromUri(Uri dataUri) {
    Log.i(TAG, "Parsing VNC URI.");
    if (dataUri == null) {
      m_isReadyForConnection = false;
      m_saved = true;
      return;
    }

    String host = dataUri.getHost();
    if (host != null) {
      setAddress(host);

      // by default, the connection name is the host name
      String nickName = getNickname();
      if (Utils.isNullOrEmptry(nickName)) {
        setNickname(host);
      }

      // default to use same host for ssh
      if (Utils.isNullOrEmptry(getSshServer())) {
        setSshServer(host);
      }
    }

    final int PORT_NONE = -1;
    int port = dataUri.getPort();
    if (port != PORT_NONE) {
      if (!isValidPort(port))
        throw new IllegalArgumentException("The specified VNC port is not valid.");
      setPort(port);
    }

    // handle legacy android-vnc-viewer parsing vnc://host:port/colormodel/password
    List<String> path = dataUri.getPathSegments();
    if (path.size() >= 1) {
      setColorModel(path.get(0));
    }

    if (path.size() >= 2) {
      setPassword(path.get(1));
    }

    // query based parameters
    String connectionName = dataUri.getQueryParameter(Constants.PARAM_CONN_NAME);

    if (connectionName != null) {
      setNickname(connectionName);
    }

    ArrayList<String> supportedUserParams =
        new ArrayList<String>() {
          {
            add(Constants.PARAM_RDP_USER);
            add(Constants.PARAM_SPICE_USER);
            add(Constants.PARAM_VNC_USER);
          }
        };
    for (String userParam : supportedUserParams) {
      String username = dataUri.getQueryParameter(userParam);
      if (username != null) {
        setUserName(username);
        break;
      }
    }

    ArrayList<String> supportedPwdParams =
        new ArrayList<String>() {
          {
            add(Constants.PARAM_RDP_PWD);
            add(Constants.PARAM_SPICE_PWD);
            add(Constants.PARAM_VNC_PWD);
          }
        };
    for (String pwdParam : supportedPwdParams) {
      String password = dataUri.getQueryParameter(pwdParam);
      if (password != null) {
        setPassword(password);
        break;
      }
    }

    setKeepPassword(false); // we should not store the password unless it is encrypted

    String securityTypeParam = dataUri.getQueryParameter(Constants.PARAM_SECTYPE);
    int secType = 0; // invalid
    if (securityTypeParam != null) {
      secType = Integer.parseInt(securityTypeParam); // throw if invalid
      switch (secType) {
        case Constants.SECTYPE_NONE:
        case Constants.SECTYPE_VNC:
          setConnectionType(Constants.CONN_TYPE_PLAIN);
          break;
        case Constants.SECTYPE_INTEGRATED_SSH:
          setConnectionType(Constants.CONN_TYPE_SSH);
          break;
        case Constants.SECTYPE_ULTRA:
          setConnectionType(Constants.CONN_TYPE_ULTRAVNC);
          break;
        case Constants.SECTYPE_TLS:
          setConnectionType(Constants.CONN_TYPE_ANONTLS);
          break;
        case Constants.SECTYPE_VENCRYPT:
          setConnectionType(Constants.CONN_TYPE_VENCRYPT);
          break;
        case Constants.SECTYPE_TUNNEL:
          setConnectionType(Constants.CONN_TYPE_STUNNEL);
          break;
        default:
          throw new IllegalArgumentException(
              "The specified security type is invalid or unsupported.");
      }
    }

    // ssh parameters
    String sshHost = dataUri.getQueryParameter(Constants.PARAM_SSH_HOST);
    if (sshHost != null) {
      setSshServer(sshHost);
    }

    String sshPortParam = dataUri.getQueryParameter(Constants.PARAM_SSH_PORT);
    if (sshPortParam != null) {
      int sshPort = Integer.parseInt(sshPortParam);
      if (!isValidPort(sshPort))
        throw new IllegalArgumentException("The specified SSH port is not valid.");
      setSshPort(sshPort);
    }

    String sshUser = dataUri.getQueryParameter(Constants.PARAM_SSH_USER);
    if (sshUser != null) {
      setSshUser(sshUser);
    }

    String sshPassword = dataUri.getQueryParameter(Constants.PARAM_SSH_PWD);
    if (sshPassword != null) {
      setSshPassword(sshPassword);
    }

    // security hashes
    String idHashAlgParam = dataUri.getQueryParameter(Constants.PARAM_ID_HASH_ALG);
    if (idHashAlgParam != null) {
      int idHashAlg = Integer.parseInt(idHashAlgParam); // throw if invalid
      switch (idHashAlg) {
        case Constants.ID_HASH_MD5:
        case Constants.ID_HASH_SHA1:
        case Constants.ID_HASH_SHA256:
          setIdHashAlgorithm(idHashAlg);
          break;
        default:
          // we are given a bad parameter
          throw new IllegalArgumentException(
              "The specified hash algorithm is invalid or unsupported.");
      }
    }

    String idHash = dataUri.getQueryParameter(Constants.PARAM_ID_HASH);
    if (idHash != null) {
      setIdHash(idHash);
    }

    // color model
    String colorModelParam = dataUri.getQueryParameter(Constants.PARAM_COLORMODEL);
    if (colorModelParam != null) {
      int colorModel = Integer.parseInt(colorModelParam); // throw if invalid
      switch (colorModel) {
        case Constants.COLORMODEL_BLACK_AND_WHITE:
          setColorModel(COLORMODEL.C2.nameString());
          break;
        case Constants.COLORMODEL_GREYSCALE:
          setColorModel(COLORMODEL.C4.nameString());
          break;
        case Constants.COLORMODEL_8_COLORS:
          setColorModel(COLORMODEL.C8.nameString());
          break;
        case Constants.COLORMODEL_64_COLORS:
          setColorModel(COLORMODEL.C64.nameString());
          break;
        case Constants.COLORMODEL_256_COLORS:
          setColorModel(COLORMODEL.C256.nameString());
          break;
          // use the best currently available model
        case Constants.COLORMODEL_16BIT:
          setColorModel(COLORMODEL.C24bit.nameString());
          break;
        case Constants.COLORMODEL_24BIT:
          setColorModel(COLORMODEL.C24bit.nameString());
          break;
        case Constants.COLORMODEL_32BIT:
          setColorModel(COLORMODEL.C24bit.nameString());
          break;
        default:
          // we are given a bad parameter
          throw new IllegalArgumentException(
              "The specified color model is invalid or unsupported.");
      }
    }
    String saveConnectionParam = dataUri.getQueryParameter(Constants.PARAM_SAVE_CONN);
    boolean saveConnection = true;
    if (saveConnectionParam != null) {
      saveConnection = Boolean.parseBoolean(saveConnectionParam); // throw if invalid
    }

    // if we are going to save the connection, we will do so here
    // it may make sense to confirm overwriting data but is probably unnecessary
    if (saveConnection) {
      Database database = new Database(c);
      save(database.getWritableDatabase());
      database.close();
      m_saved = true;
    }

    // we do not currently use API keys

    // check if we need to show data-entry screen
    // it may be possible to prompt for data later
    m_isReadyForConnection = true;
    if (Utils.isNullOrEmptry(getAddress())) {
      m_isReadyForConnection = false;
      Log.i(TAG, "URI missing remote address.");
    }

    int connType = getConnectionType();
    if (secType == Constants.SECTYPE_VNC
        || connType == Constants.CONN_TYPE_STUNNEL
        || connType == Constants.CONN_TYPE_SSH) {
      // we can infer a password is required
      // while we could have implemented tunnel/ssh without one
      // the user can supply a blank value and the server will not
      // request it and it is better to support the common case
      if (Utils.isNullOrEmptry(getPassword())) {
        m_isReadyForConnection = false;
        Log.i(TAG, "URI missing VNC password.");
      }
    }
    if (connType == Constants.CONN_TYPE_SSH) {
      // the below should not occur
      if (Utils.isNullOrEmptry(getSshServer())) m_isReadyForConnection = false;
      // we probably need either a username/password or a key
      // however the main screen doesn't validate this
    }
    // some other types probably require a username/password
    // however main screen doesn't validate this
  }
コード例 #14
0
ファイル: FileUtils.java プロジェクト: aggarwal59/MyExpenses
  /**
   * Get a file path from a Uri. This will get the the path for Storage Access Framework Documents,
   * as well as the _data field for the MediaStore and other file-based ContentProviders.<br>
   * <br>
   * Callers should only use this for display purposes and not for accessing the file directly via
   * the file system
   *
   * @param context The context.
   * @param uri The Uri to query.
   * @see #isLocal(String)
   * @see #getFile(Context, Uri)
   * @author paulburke
   */
  @TargetApi(Build.VERSION_CODES.KITKAT)
  public static String getPath(final Context context, final Uri uri) {

    if (DEBUG)
      Log.d(
          TAG + " File -",
          "Authority: "
              + uri.getAuthority()
              + ", Fragment: "
              + uri.getFragment()
              + ", Port: "
              + uri.getPort()
              + ", Query: "
              + uri.getQuery()
              + ", Scheme: "
              + uri.getScheme()
              + ", Host: "
              + uri.getHost()
              + ", Segments: "
              + uri.getPathSegments().toString());

    // DocumentProvider
    if (isDocumentUri(context, uri)) {
      // ExternalStorageProvider
      if (isExternalStorageDocument(uri)) {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];

        if ("primary".equalsIgnoreCase(type)) {
          String path = Environment.getExternalStorageDirectory().getPath();
          if (split.length > 1) {
            path += "/" + split[1];
          }
          return path;
        }
        // there is no documented way of returning a path to a file on non primary storage.
        // so what we do is displaying the documentId to the user which is better than just null
        return docId;
      }
      // DownloadsProvider
      else if (isDownloadsDocument(uri)) {

        final String id = DocumentsContract.getDocumentId(uri);
        final Uri contentUri =
            ContentUris.withAppendedId(
                Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

        return getDataColumn(context, contentUri, null, null);
      }
      // MediaProvider
      else if (isMediaDocument(uri)) {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];

        Uri contentUri = null;
        if ("image".equals(type)) {
          contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if ("video".equals(type)) {
          contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if ("audio".equals(type)) {
          contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }

        final String selection = "_id=?";
        final String[] selectionArgs = new String[] {split[1]};

        return getDataColumn(context, contentUri, selection, selectionArgs);
      }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

      // Return the remote address
      if (isGooglePhotosUri(uri)) return uri.getLastPathSegment();

      return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
      return uri.getPath();
    }

    return null;
  }