예제 #1
0
 @Test
 public void testDecodingUsernameWithEncodings() {
   assertEquals("[email protected]:mypassword", URLUtils.decode("user%40gmail.com:mypassword"));
   assertEquals("[email protected]:mypassword", URLUtils.decode("[email protected]:mypassword"));
   assertEquals("user:mypassword", URLUtils.decode("user:mypassword"));
   assertEquals("[email protected]:mypass+word", URLUtils.decode("user%40gmail.com:mypass%2Bword"));
   assertNull(URLUtils.decode(null));
 }
예제 #2
0
 public synchronized PathMatcher addExactPath(final String path, final T handler) {
   if (path.isEmpty()) {
     throw UndertowMessages.MESSAGES.pathMustBeSpecified();
   }
   exactPathMatches.put(URLUtils.normalizeSlashes(path), handler);
   return this;
 }
예제 #3
0
  /** AKA scraping */
  public TorrentStatus getStatus() throws IOException {
    if (!isGetStatusSupported()) {
      throw new IllegalStateException("Get status (scraping) not supported on this tracker");
    }
    String path = announceUrl.getFile();
    int i = path.lastIndexOf('/');
    path = path.substring(0, i + 1) + "scrape" + path.substring(i + ANNOUNCE.length() + 1);

    GetMethod method = new GetMethod(path);
    method.setRequestHeader("User-Agent", "BlackBits/0.1");
    StringBuffer queryString =
        new StringBuffer(announceUrl.getQuery() == null ? "" : announceUrl.getQuery());
    queryString.append("info_hash=" + URLUtils.encode(infoHash.getBytes()));
    method.setQueryString(queryString.toString());
    httpClient.executeMethod(method);

    BDecoder decoder = new BDecoder(method.getResponseBodyAsStream());
    BDictionary dictionary = (BDictionary) decoder.decodeNext();
    BDictionary files = (BDictionary) dictionary.get("files");
    String key = (String) files.keySet().iterator().next();
    BDictionary info = (BDictionary) files.get(key);
    BLong seeders = (BLong) info.get("complete");
    BLong leechers = (BLong) info.get("incomplete");
    BLong numberOfDownloads = (BLong) info.get("downloaded");
    return new TorrentStatus(seeders.intValue(), leechers.intValue(), numberOfDownloads.intValue());
  }
예제 #4
0
  public synchronized PathMatcher removeExactPath(final String path) {
    if (path == null || path.isEmpty()) {
      throw UndertowMessages.MESSAGES.pathMustBeSpecified();
    }

    exactPathMatches.remove(URLUtils.normalizeSlashes(path));

    return this;
  }
예제 #5
0
  byte[] getByteBodyContents() {

    String body = (payload != null) ? payload : URLUtils.formURLEncodeMap(bodyParams);

    try {
      return body.getBytes(getCharset());
    } catch (UnsupportedEncodingException uee) {
      throw new OAuthException("Unsupported Charset: " + getCharset(), uee);
    }
  }
예제 #6
0
  /**
   * Get a {@link Map} of the query string parameters.
   *
   * @return a map containing the query string parameters
   * @throws OAuthException if the URL is not valid
   */
  public Map<String, String> getQueryStringParams() {
    try {
      Map<String, String> params = new HashMap<String, String>();
      String queryString = new URL(url).getQuery();

      params.putAll(URLUtils.queryStringToMap(queryString));
      params.putAll(this.querystringParams);

      return params;
    } catch (MalformedURLException mue) {
      throw new OAuthException("Malformed URL", mue);
    }
  }
예제 #7
0
  public void open() {
    try {
      URL url = new URL(m_url);

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(30 * 1000);
      conn.setConnectTimeout(30 * 1000);

      conn.setRequestMethod(m_method);

      if (m_token != null) conn.setRequestProperty("Authorization", m_token);

      if (m_body != null) {
        conn.setFixedLengthStreamingMode(m_body.length);
        conn.setRequestProperty("Content-Type", m_contentType);
        conn.setDoOutput(true);
      }

      if (m_responseListener != null) conn.setDoInput(true);

      if (m_body != null) {
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(m_body);
        wr.close();
      }

      Log.d(TAG, m_method + " " + url);

      m_response.clear();
      int resCode = conn.getResponseCode();
      switch (resCode) {
        case HttpURLConnection.HTTP_UNAUTHORIZED:
          if (m_responseListener != null) m_responseListener.onUnauthorized(m_url, m_token);
          else m_response.putString(RESPONSE_UNAUTHORIZED, m_url);
          break;

        default:
          InputStream is = conn.getInputStream();
          if (m_responseListener != null) m_responseListener.onResponse(resCode, is);
          else m_response.putString(RESPONSE_SUCCESS, URLUtils.convertStreamToString(is));
          is.close();
      }

      conn.disconnect();
    } catch (IOException e) {
      e.printStackTrace();
      if (m_responseListener != null) m_responseListener.onError(e);
      else m_response.putString(RESPONSE_ERROR, e.getMessage());
    }
  }
예제 #8
0
  private void createConnection() throws IOException {
    String effectiveUrl = URLUtils.appendParametersToQueryString(url, querystringParams);

    if (connection == null) {
      System.setProperty("http.keepAlive", connectionKeepAlive ? "true" : "false");

      URL url = new URL(effectiveUrl);
      connection =
          (HttpURLConnection) (proxy == null ? url.openConnection() : url.openConnection(proxy));

      connection.setConnectTimeout(connectTimeout);
      connection.setReadTimeout(readTimeout);
    }
  }
예제 #9
0
 private TrackerResponse sendEvent(
     long uploadedBytes, long downloadedBytes, long bytesLeftToDownload, String event)
     throws IOException, TrackerCommunicationException {
   GetMethod method = new GetMethod(announceUrl.getFile());
   method.setRequestHeader("User-Agent", "BlackBits/0.1");
   StringBuffer queryString =
       new StringBuffer(announceUrl.getQuery() == null ? "" : announceUrl.getQuery());
   queryString.append("info_hash=" + URLUtils.encode(infoHash.getBytes()));
   queryString.append("&peer_id=" + URLUtils.encode(localPeer.getId()));
   queryString.append("&port=" + localPeer.getPort());
   queryString.append("&uploaded=" + uploadedBytes);
   queryString.append("&downloaded=" + downloadedBytes);
   queryString.append("&left=" + bytesLeftToDownload);
   if (event != null) {
     queryString.append("&event=" + event);
   }
   if (localPeer.getAddress() != null) {
     queryString.append("&ip=" + localPeer.getAddress());
   }
   method.setQueryString(queryString.toString());
   httpClient.executeMethod(method);
   return decodeResponse(method);
 }
예제 #10
0
  public T getPrefixPath(final String path) {

    final String normalizedPath = URLUtils.normalizeSlashes(path);

    // enable the prefix path mechanism to return the default handler
    SubstringMap.SubstringMatch<T> match = paths.get(normalizedPath);
    if (PathMatcher.STRING_PATH_SEPARATOR.equals(normalizedPath) && match == null) {
      return this.defaultHandler;
    }
    if (match == null) {
      return null;
    }

    // return the value for the given path
    return match.getValue();
  }
예제 #11
0
  public synchronized PathMatcher removePrefixPath(final String path) {
    if (path == null || path.isEmpty()) {
      throw UndertowMessages.MESSAGES.pathMustBeSpecified();
    }

    final String normalizedPath = URLUtils.normalizeSlashes(path);

    if (PathMatcher.STRING_PATH_SEPARATOR.equals(normalizedPath)) {
      defaultHandler = null;
      return this;
    }

    paths.remove(normalizedPath);

    buildLengths();
    return this;
  }
예제 #12
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    String url = null;

    if (request instanceof HttpServletRequest) {
      url = ((HttpServletRequest) request).getRequestURL().toString();
    }
    String domain = URLUtils.getDomain(url);
    if (domain != "") {
      SystemConstant.setDOMAIN_URL(domain);
    }

    // all requests count into realtime charts
    SystemVisitorLog.count();

    if (URLUtils.shouldLog(url)) SystemVisitorLog.count(request.getRemoteAddr());

    if (SystemConstant.DOMAIN_URL.isEmpty()) {
      SystemConstant.DOMAIN_URL = request.getServerName();
      if (request.getServerPort() != 80) {
        SystemConstant.DOMAIN_URL += ":" + request.getServerPort();
      }
    }
    HttpSession session = ((HttpServletRequest) request).getSession();
    Object userAccount = session.getAttribute(ContextManager.KEY_ACCOUNT);
    Object userName = session.getAttribute(ContextManager.KEY_NAME);
    boolean logined = userAccount != null;

    SystemConstant.README_PATH =
        session.getServletContext().getRealPath(File.separator + "README.md");
    SystemConstant.ROOT = session.getServletContext().getRealPath(File.separator);

    if (!logined) {
      BucSSOUser user = SimpleUserUtil.getBucSSOUser((HttpServletRequest) request);
      // System.out.println("user:"******"user.getEmpId:" + user.getEmpId());
        // System.out.println("user.getLastName:" + user.getLastName());
        // System.out.println("user.emailAddr:" + user.getEmailAddr());
        // System.out.println("user.loginName:" + user.getLoginName());

        String emailPrefix =
            user.getEmailAddr().substring(0, user.getEmailAddr().indexOf("@alibaba"));
        // System.out.println("emailPrefix:" + emailPrefix);
        User rapUser = accountMgr.getUser(emailPrefix);
        if (rapUser == null) {
          // proceed register
          User newUser = new User();
          newUser.setAccount(emailPrefix);
          newUser.setPassword("RESERVED");
          String name = user.getNickNameCn();
          if (name == null || name.isEmpty()) {
            name = user.getLastName();
          }
          newUser.setName(name);
          newUser.setEmail(user.getEmailAddr());
          newUser.setRealname(user.getLastName());
          newUser.setEmpId(user.getEmpId());
          getAccountMgr().addUser(newUser);
          rapUser = accountMgr.getUser(emailPrefix);
          if (rapUser == null) {
            try {
              throw new Exception("user register failed!");
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }
        // proceed login
        String account = rapUser.getAccount();
        long userId = rapUser.getId();
        session.setAttribute(ContextManager.KEY_ACCOUNT, account);
        session.setAttribute(ContextManager.KEY_USER_ID, userId);
        session.setAttribute(ContextManager.KEY_NAME, rapUser.getName());
      }

    } else {
      if (URLUtils.shouldLog(url)) {
        User logUser = new User();
        logUser.setAccount((String) userAccount);
        logUser.setName((String) userName);
        SystemVisitorLog.count(logUser);
      }
    }

    chain.doFilter(request, response);
  }
예제 #13
0
 @Override
 public void onResponse(int resCode, InputStream is) {
   Log.d(TAG, "onResponse " + resCode + " " + URLUtils.convertStreamToString(is));
 }
예제 #14
0
 @Test
 public void testInvalidEncodedUsername() {
   thrown.expect(IllegalStateException.class);
   thrown.expectMessage("must be followed by two hex digits");
   URLUtils.decode("foo%");
 }
예제 #15
0
 public T getExactPath(final String path) {
   return exactPathMatches.get(URLUtils.normalizeSlashes(path));
 }
예제 #16
0
  public static List<TestURL> loadTestURLs(final String resource) {
    try {
      final List<TestURL> results = new ArrayList<TestURL>();
      final BufferedReader br;
      br =
          new BufferedReader(
              new InputStreamReader(TestURLLoader.class.getResourceAsStream(resource)));
      String line;
      while ((line = br.readLine()) != null) {
        if (line.isEmpty() || line.startsWith("--")) {
          continue;
        }
        String[] fields = line.split(" ");

        TestURL testURL = new TestURL();
        results.add(testURL);
        testURL.rawURL = normalize(fields[0]);

        if (fields.length > 1 && !fields[1].isEmpty()) {
          testURL.rawBaseURL = normalize(fields[1]);
          try {
            testURL.parsedBaseURL = URL.parse(testURL.rawBaseURL);
          } catch (GalimatiasParseException ex) {
            throw new RuntimeException("Exception while parsing test line: " + line, ex);
          }
        } else {
          // FIXME: This implies there are no tests with null base
          testURL.rawBaseURL = results.get(results.size() - 2).rawBaseURL;
          testURL.parsedBaseURL = results.get(results.size() - 2).parsedBaseURL;
        }

        if (fields.length < 2) {
          continue;
        }

        String scheme = "";
        String schemeData = "";
        String username = "";
        String password = null;
        Host host = null;
        int port = -1;
        String path = null;
        String query = null;
        String fragment = null;
        boolean isHierarchical = false;

        for (int i = 2; i < fields.length; i++) {
          final String field = normalize(fields[i]);
          if (field.length() < 2) {
            throw new RuntimeException("Malformed test: " + line);
          }
          final String value = field.substring(2);
          if (field.startsWith("s:")) {
            scheme = value;
            isHierarchical = URLUtils.isRelativeScheme(scheme);
          } else if (field.startsWith("u:")) {
            username = value;
          } else if (field.startsWith("pass:"******"h:")) {
            try {
              host = Host.parseHost(value);
            } catch (GalimatiasParseException ex) {
              throw new RuntimeException(ex);
            }
          } else if (field.startsWith("port:")) {
            port = Integer.parseInt(field.substring(5));
          } else if (field.startsWith("p:")) {
            path = value;
          } else if (field.startsWith("q:")) {
            query = value;
            // FIXME: Workaround for bad test data
            // TODO: https://github.com/w3c/web-platform-tests/issues/499
            if (query.startsWith("?")) {
              query = query.substring(1);
            }
          } else if (field.startsWith("f:")) {
            fragment = value;
            // FIXME: Workaround for bad test data
            if (fragment.startsWith("#")) {
              fragment = fragment.substring(1);
            }
          }
        }

        if (!isHierarchical) {
          schemeData = path;
          path = null;
        } else {
          final String defaultPortString = URLUtils.getDefaultPortForScheme(scheme);
          if (defaultPortString != null && port == Integer.parseInt(defaultPortString)) {
            port = -1;
          }
        }

        testURL.parsedURL =
            new URL(
                scheme,
                schemeData,
                username,
                password,
                host,
                port,
                path,
                query,
                fragment,
                isHierarchical);
      }
      return results;
    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }
  }