Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
category:
- String manipulation
- Parser
from: http://rosettacode.org/wiki/URL_parser

View file

@ -0,0 +1,55 @@
URLs are strings with a simple syntax:
scheme://[username:password@]domain[:port]/path?query_string#fragment_id
;Task:
Parse a well-formed URL to retrieve the relevant information:   '''scheme''', '''domain''', '''path''', ...
Note:   this task has nothing to do with [[URL encoding]] or [[URL decoding]].
According to the standards, the characters:
:::: &nbsp; <big><big> ! * ' ( ) ; : @ & = + $ , / ? % # [ ] </big></big>
only need to be percent-encoded &nbsp; ('''%''') &nbsp; in case of possible confusion.
Also note that the '''path''', '''query''' and '''fragment''' are case sensitive, even if the '''scheme''' and '''domain''' are not.
The way the returned information is provided (set of variables, array, structured, record, object,...)
is language-dependent and left to the programmer, but the code should be clear enough to reuse.
Extra credit is given for clear error diagnostics.
* &nbsp; Here is the official standard: &nbsp; &nbsp; https://tools.ietf.org/html/rfc3986,
* &nbsp; and here is a simpler &nbsp; BNF: &nbsp; &nbsp; http://www.w3.org/Addressing/URL/5_URI_BNF.html.
;Test cases:
According to T. Berners-Lee
'''<nowiki>foo://example.com:8042/over/there?name=ferret#nose</nowiki>''' &nbsp; &nbsp; should parse into:
::* &nbsp; scheme = foo
::* &nbsp; domain = example.com
::* &nbsp; port = :8042
::* &nbsp; path = over/there
::* &nbsp; query = name=ferret
::* &nbsp; fragment = nose
'''<nowiki>urn:example:animal:ferret:nose</nowiki>''' &nbsp; &nbsp; should parse into:
::* &nbsp; scheme = urn
::* &nbsp; path = example:animal:ferret:nose
'''other URLs that must be parsed include:'''
:* &nbsp; <nowiki> jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true </nowiki>
:* &nbsp; <nowiki> ftp://ftp.is.co.za/rfc/rfc1808.txt </nowiki>
:* &nbsp; <nowiki> http://www.ietf.org/rfc/rfc2396.txt#header1 </nowiki>
:* &nbsp; <nowiki> ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two </nowiki>
:* &nbsp; <nowiki> mailto:John.Doe@example.com </nowiki>
:* &nbsp; <nowiki> news:comp.infosystems.www.servers.unix </nowiki>
:* &nbsp; <nowiki> tel:+1-816-555-1212 </nowiki>
:* &nbsp; <nowiki> telnet://192.0.2.16:80/ </nowiki>
:* &nbsp; <nowiki> urn:oasis:names:specification:docbook:dtd:xml:4.1.2 </nowiki>
<br><br>

View file

@ -0,0 +1,38 @@
PR read "uriParser.a68" PR
PROC test uri parser = ( STRING uri )VOID:
BEGIN
URI result := parse uri( uri );
print( ( uri, ":", newline ) );
IF NOT ok OF result
THEN
# the parse failed #
print( ( " ", error OF result, newline ) )
ELSE
# parsed OK #
print( ( " scheme: ", scheme OF result, newline ) );
IF userinfo OF result /= "" THEN print( ( " userinfo: ", userinfo OF result, newline ) ) FI;
IF host OF result /= "" THEN print( ( " host: ", host OF result, newline ) ) FI;
IF port OF result /= "" THEN print( ( " port: ", port OF result, newline ) ) FI;
IF path OF result /= "" THEN print( ( " path: ", path OF result, newline ) ) FI;
IF query OF result /= "" THEN print( ( " query: ", query OF result, newline ) ) FI;
IF fragment id OF result /= "" THEN print( ( " fragment id: ", fragment id OF result, newline ) ) FI
FI;
print( ( newline ) )
END # test uri parser # ;
BEGIN test uri parser( "foo://example.com:8042/over/there?name=ferret#nose" )
; test uri parser( "urn:example:animal:ferret:nose" )
; test uri parser( "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true" )
; test uri parser( "ftp://ftp.is.co.za/rfc/rfc1808.txt" )
; test uri parser( "http://www.ietf.org/rfc/rfc2396.txt#header1" )
; test uri parser( "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two" )
; test uri parser( "mailto:John.Doe@example.com" )
; test uri parser( "news:comp.infosystems.www.servers.unix" )
; test uri parser( "tel:+1-816-555-1212" )
; test uri parser( "telnet://192.0.2.16:80/" )
; test uri parser( "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" )
; test uri parser( "ssh://alice@example.com" )
; test uri parser( "https://bob:pass@example.com/place" )
; test uri parser( "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" )
END

View file

@ -0,0 +1,67 @@
with Ada.Text_IO;
with AWS.URL;
with AWS.Parameters;
with AWS.Containers.Tables;
procedure URL_Parser is
procedure Parse (URL : in String) is
use AWS.URL, Ada.Text_IO;
use AWS.Containers.Tables;
procedure Put_Cond (Item : in String;
Value : in String;
When_Not : in String := "") is
begin
if Value /= When_Not then
Put (" "); Put (Item); Put_Line (Value);
end if;
end Put_Cond;
Obj : Object;
List : Table_Type;
begin
Put_Line ("Parsing " & URL);
Obj := Parse (URL);
List := Table_Type (AWS.Parameters.List'(AWS.URL.Parameters (Obj)));
Put_Cond ("Scheme: ", Protocol_Name (Obj));
Put_Cond ("Domain: ", Host (Obj));
Put_Cond ("Port: ", Port (Obj), When_Not => "0");
Put_Cond ("Path: ", Path (Obj));
Put_Cond ("File: ", File (Obj));
Put_Cond ("Query: ", Query (Obj));
Put_Cond ("Fragment: ", Fragment (Obj));
Put_Cond ("User: ", User (Obj));
Put_Cond ("Password: ", Password (Obj));
if List.Count /= 0 then
Put_Line (" Parameters:");
end if;
for Index in 1 .. List.Count loop
Put (" "); Put (Get_Name (List, N => Index));
Put (" "); Put ("'" & Get_Value (List, N => Index) & "'");
New_Line;
end loop;
New_Line;
end Parse;
begin
Parse ("foo://example.com:8042/over/there?name=ferret#nose");
Parse ("urn:example:animal:ferret:nose");
Parse ("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true");
Parse ("ftp://ftp.is.co.za/rfc/rfc1808.txt");
Parse ("http://www.ietf.org/rfc/rfc2396.txt#header1");
Parse ("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two");
Parse ("mailto:John.Doe@example.com");
Parse ("news:comp.infosystems.www.servers.unix");
Parse ("tel:+1-816-555-1212");
Parse ("telnet://192.0.2.16:80/");
Parse ("urn:oasis:names:specification:docbook:dtd:xml:4.1.2");
Parse ("ssh://alice@example.com");
Parse ("https://bob:pass@example.com/place");
Parse ("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64");
end URL_Parser;

View file

@ -0,0 +1,42 @@
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
on parseURLString(URLString)
set output to {URLString}
set indent to tab & "• "
set componentsObject to current application's class "NSURLComponents"'s componentsWithString:(URLString)
repeat with thisKey in {"scheme", "user", "password", "host", "port", "path", "query", "fragment"}
set thisValue to (componentsObject's valueForKey:(thisKey))
if (thisValue is not missing value) then set end of output to indent & thisKey & (" = " & thisValue)
end repeat
return join(output, linefeed)
end parseURLString
on join(listOfText, delimiter)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delimiter
set output to listOfText as text
set AppleScript's text item delimiters to astid
return output
end join
-- Test code:
local output, URLString
set output to {}
repeat with URLString in {"foo://example.com:8042/over/there?name=ferret#nose", ¬
"urn:example:animal:ferret:nose", ¬
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", ¬
"ftp://ftp.is.co.za/rfc/rfc1808.txt", ¬
"http://www.ietf.org/rfc/rfc2396.txt#header1", ¬
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", ¬
"mailto:John.Doe@example.com", ¬
"news:comp.infosystems.www.servers.unix", ¬
"tel:+1-816-555-1212", ¬
"telnet://192.0.2.16:80/", ¬
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2", ¬
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"}
set end of output to parseURLString(URLString's contents)
end repeat
return join(output, linefeed & linefeed)

View file

@ -0,0 +1,61 @@
"foo://example.com:8042/over/there?name=ferret#nose
scheme = foo
host = example.com
port = 8042
path = /over/there
query = name=ferret
fragment = nose
urn:example:animal:ferret:nose
scheme = urn
path = example:animal:ferret:nose
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
scheme = jdbc
path = mysql://test_user:ouupppssss@localhost:3306/sakila
query = profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
scheme = ftp
host = ftp.is.co.za
path = /rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
scheme = http
host = www.ietf.org
path = /rfc/rfc2396.txt
fragment = header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
scheme = ldap
host = [2001:db8::7]
path = /c=GB
query = objectClass=one&objectClass=two
mailto:John.Doe@example.com
scheme = mailto
path = John.Doe@example.com
news:comp.infosystems.www.servers.unix
scheme = news
path = comp.infosystems.www.servers.unix
tel:+1-816-555-1212
scheme = tel
path = +1-816-555-1212
telnet://192.0.2.16:80/
scheme = telnet
host = 192.0.2.16
port = 80
path = /
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
scheme = urn
path = oasis:names:specification:docbook:dtd:xml:4.1.2
http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64
scheme = http
host = example.com
path = /
query = a=1&b=2+2&c=3&c=4&d=encoded"

View file

@ -0,0 +1,34 @@
using System;
namespace RosettaUrlParse
{
class Program
{
static void ParseUrl(string url)
{
var u = new Uri(url);
Console.WriteLine("URL: {0}", u.AbsoluteUri);
Console.WriteLine("Scheme: {0}", u.Scheme);
Console.WriteLine("Host: {0}", u.DnsSafeHost);
Console.WriteLine("Port: {0}", u.Port);
Console.WriteLine("Path: {0}", u.LocalPath);
Console.WriteLine("Query: {0}", u.Query);
Console.WriteLine("Fragment: {0}", u.Fragment);
Console.WriteLine();
}
static void Main(string[] args)
{
ParseUrl("foo://example.com:8042/over/there?name=ferret#nose");
ParseUrl("urn:example:animal:ferret:nose");
ParseUrl("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true");
ParseUrl("ftp://ftp.is.co.za/rfc/rfc1808.txt");
ParseUrl("http://www.ietf.org/rfc/rfc2396.txt#header1");
ParseUrl("ldap://[2001:db8::7]/c=GB?objectClass?one");
ParseUrl("mailto:John.Doe@example.com");
ParseUrl("news:comp.infosystems.www.servers.unix");
ParseUrl("tel:+1-816-555-1212");
ParseUrl("telnet://192.0.2.16:80/");
ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2");
}
}
}

View file

@ -0,0 +1,32 @@
require "uri"
examples = ["foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"https://bob:password@[::1]/place?a=1&b=2%202"]
examples.each do |example|
puts "Parsing \"#{example}\":"
url = URI.parse example
{% for name in ["scheme", "host", "hostname", "port", "path", "userinfo",
"user", "password", "fragment", "query"] %}
unless url.{{name.id}}.nil?
puts " {{name.id}}: \"#{url.{{name.id}}}\""
end
{% end %}
unless url.query_params.empty?
puts " query_params:"
url.query_params.each do |k, v|
puts " #{k}: \"#{v}\""
end
end
puts
end

View file

@ -0,0 +1,21 @@
test_cases = [
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh://alice@example.com",
"https://bob:pass@example.com/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"
]
Enum.each(test_cases, fn str ->
IO.puts "\n#{str}"
IO.inspect URI.parse(str)
end)

View file

@ -0,0 +1,30 @@
open System
open System.Text.RegularExpressions
let writeline n v = if String.IsNullOrEmpty(v) then () else printfn "%-15s %s" n v
let toUri = fun s -> Uri(s.ToString())
let urisFromString = (Regex(@"\S+").Matches) >> Seq.cast >> (Seq.map toUri)
urisFromString """
foo://example.com:8042/over/there?name=ferret#nose
urn:example:animal:ferret:nose
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass?one
mailto:John.Doe@example.com
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
"""
|> Seq.iter (fun u ->
writeline "\nURI:" (u.ToString())
writeline " scheme:" (u.Scheme)
writeline " host:" (u.Host)
writeline " port:" (if u.Port < 0 then "" else u.Port.ToString())
writeline " path:" (u.AbsolutePath)
writeline " query:" (if u.Query.Length > 0 then u.Query.Substring(1) else "")
writeline " fragment:" (if u.Fragment.Length > 0 then u.Fragment.Substring(1) else "")
)

View file

@ -0,0 +1,75 @@
package main
import (
"fmt"
"log"
"net"
"net/url"
)
func main() {
for _, in := range []string{
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh://alice@example.com",
"https://bob:pass@example.com/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64",
} {
fmt.Println(in)
u, err := url.Parse(in)
if err != nil {
log.Println(err)
continue
}
if in != u.String() {
fmt.Printf("Note: reassmebles as %q\n", u)
}
printURL(u)
}
}
func printURL(u *url.URL) {
fmt.Println(" Scheme:", u.Scheme)
if u.Opaque != "" {
fmt.Println(" Opaque:", u.Opaque)
}
if u.User != nil {
fmt.Println(" Username:", u.User.Username())
if pwd, ok := u.User.Password(); ok {
fmt.Println(" Password:", pwd)
}
}
if u.Host != "" {
if host, port, err := net.SplitHostPort(u.Host); err == nil {
fmt.Println(" Host:", host)
fmt.Println(" Port:", port)
} else {
fmt.Println(" Host:", u.Host)
}
}
if u.Path != "" {
fmt.Println(" Path:", u.Path)
}
if u.RawQuery != "" {
fmt.Println(" RawQuery:", u.RawQuery)
m, err := url.ParseQuery(u.RawQuery)
if err == nil {
for k, v := range m {
fmt.Printf(" Key: %q Values: %q\n", k, v)
}
}
}
if u.Fragment != "" {
fmt.Println(" Fragment:", u.Fragment)
}
}

View file

@ -0,0 +1,29 @@
import java.net.URI
[
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2"
].each { String url ->
// magic happens here
URI u = url.toURI()
// Results displayed here
println """
|Parsing $url
| scheme = ${u.scheme}
| domain = ${u.host}
| port = ${(u.port + 1) ? u.port : 'default' }
| path = ${u.path ?: u.schemeSpecificPart}
| query = ${u.query}
| fragment = ${u.fragment}""".stripMargin()
}

View file

@ -0,0 +1,75 @@
module Main (main) where
import Data.Foldable (for_)
import Network.URI
( URI
, URIAuth
, parseURI
, uriAuthority
, uriFragment
, uriPath
, uriPort
, uriQuery
, uriRegName
, uriScheme
, uriUserInfo
)
uriStrings :: [String]
uriStrings =
[ "https://bob:pass@example.com/place"
, "foo://example.com:8042/over/there?name=ferret#nose"
, "urn:example:animal:ferret:nose"
, "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"
, "ftp://ftp.is.co.za/rfc/rfc1808.txt"
, "http://www.ietf.org/rfc/rfc2396.txt#header1"
, "ldap://[2001:db8::7]/c=GB?objectClass?one"
, "mailto:John.Doe@example.com"
, "news:comp.infosystems.www.servers.unix"
, "tel:+1-816-555-1212"
, "telnet://192.0.2.16:80/"
, "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"
]
trimmedUriScheme :: URI -> String
trimmedUriScheme = init . uriScheme
trimmedUriUserInfo :: URIAuth -> Maybe String
trimmedUriUserInfo uriAuth =
case uriUserInfo uriAuth of
[] -> Nothing
userInfo -> if last userInfo == '@' then Just (init userInfo) else Nothing
trimmedUriPath :: URI -> String
trimmedUriPath uri = case uriPath uri of '/' : t -> t; p -> p
trimmedUriQuery :: URI -> Maybe String
trimmedUriQuery uri = case uriQuery uri of '?' : t -> Just t; _ -> Nothing
trimmedUriFragment :: URI -> Maybe String
trimmedUriFragment uri = case uriFragment uri of '#' : t -> Just t; _ -> Nothing
main :: IO ()
main = do
for_ uriStrings $ \uriString -> do
case parseURI uriString of
Nothing -> putStrLn $ "Could not parse" ++ uriString
Just uri -> do
putStrLn uriString
putStrLn $ " scheme = " ++ trimmedUriScheme uri
case uriAuthority uri of
Nothing -> return ()
Just uriAuth -> do
case trimmedUriUserInfo uriAuth of
Nothing -> return ()
Just userInfo -> putStrLn $ " user-info = " ++ userInfo
putStrLn $ " domain = " ++ uriRegName uriAuth
putStrLn $ " port = " ++ uriPort uriAuth
putStrLn $ " path = " ++ trimmedUriPath uri
case trimmedUriQuery uri of
Nothing -> return ()
Just query -> putStrLn $ " query = " ++ query
case trimmedUriFragment uri of
Nothing -> return ()
Just fragment -> putStrLn $ " fragment = " ++ fragment
putStrLn ""

View file

@ -0,0 +1,47 @@
split=:1 :0
({. ; ] }.~ 1+[)~ i.&m
)
uriparts=:3 :0
'server fragment'=. '#' split y
'sa query'=. '?' split server
'scheme authpath'=. ':' split sa
scheme;authpath;query;fragment
)
queryparts=:3 :0
(0<#y)#<;._1 '?',y
)
authpathparts=:3 :0
if. '//' -: 2{.y do.
split=. <;.1 y
(}.1{::split);;2}.split
else.
'';y
end.
)
authparts=:3 :0
if. '@' e. y do.
'userinfo hostport'=. '@' split y
else.
hostport=. y [ userinfo=.''
end.
if. '[' = {.hostport do.
'host_t port_t'=. ']' split hostport
assert. (0=#port_t)+.':'={.port_t
(':' split userinfo),(host_t,']');}.port_t
else.
(':' split userinfo),':' split hostport
end.
)
taskparts=:3 :0
'scheme authpath querystring fragment'=. uriparts y
'auth path'=. authpathparts authpath
'user creds host port'=. authparts auth
query=. queryparts querystring
export=. ;:'scheme user creds host port path query fragment'
(#~ 0<#@>@{:"1) (,. do each) export
)

View file

@ -0,0 +1,96 @@
taskparts 'foo://example.com:8042/over/there?name=ferret#nose'
┌────────┬─────────────┐
│scheme │foo │
├────────┼─────────────┤
│host │example.com │
├────────┼─────────────┤
│port │8042 │
├────────┼─────────────┤
│path │/over/there │
├────────┼─────────────┤
│query │┌───────────┐│
│ ││name=ferret││
│ │└───────────┘│
├────────┼─────────────┤
│fragment│nose │
└────────┴─────────────┘
taskparts 'urn:example:animal:ferret:nose'
┌──────┬──────────────────────────┐
│scheme│urn │
├──────┼──────────────────────────┤
│path │example:animal:ferret:nose│
└──────┴──────────────────────────┘
taskparts 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true'
┌──────┬──────────────────────────────────────────────────┐
│scheme│jdbc │
├──────┼──────────────────────────────────────────────────┤
│path │mysql://test_user:ouupppssss@localhost:3306/sakila│
├──────┼──────────────────────────────────────────────────┤
│query │┌───────────────┐ │
│ ││profileSQL=true│ │
│ │└───────────────┘ │
└──────┴──────────────────────────────────────────────────┘
taskparts 'ftp://ftp.is.co.za/rfc/rfc1808.txt'
┌──────┬────────────────┐
│scheme│ftp │
├──────┼────────────────┤
│host │ftp.is.co.za │
├──────┼────────────────┤
│path │/rfc/rfc1808.txt│
└──────┴────────────────┘
taskparts 'http://www.ietf.org/rfc/rfc2396.txt#header1'
┌────────┬────────────────┐
│scheme │http │
├────────┼────────────────┤
│host │www.ietf.org │
├────────┼────────────────┤
│path │/rfc/rfc2396.txt│
├────────┼────────────────┤
│fragment│header1 │
└────────┴────────────────┘
taskparts 'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two'
┌──────┬─────────────────────────────────┐
│scheme│ldap │
├──────┼─────────────────────────────────┤
│host │[2001:db8::7] │
├──────┼─────────────────────────────────┤
│path │/c=GB │
├──────┼─────────────────────────────────┤
│query │┌───────────────────────────────┐│
│ ││objectClass=one&objectClass=two││
│ │└───────────────────────────────┘│
└──────┴─────────────────────────────────┘
taskparts 'mailto:John.Doe@example.com'
┌──────┬────────────────────┐
│scheme│mailto │
├──────┼────────────────────┤
│path │John.Doe@example.com│
└──────┴────────────────────┘
taskparts 'news:comp.infosystems.www.servers.unix'
┌──────┬─────────────────────────────────┐
│scheme│news │
├──────┼─────────────────────────────────┤
│path │comp.infosystems.www.servers.unix│
└──────┴─────────────────────────────────┘
taskparts 'tel:+1-816-555-1212'
┌──────┬───────────────┐
│scheme│tel │
├──────┼───────────────┤
│path │+1-816-555-1212│
└──────┴───────────────┘
taskparts 'telnet://192.0.2.16:80/'
┌──────┬──────────┐
│scheme│telnet │
├──────┼──────────┤
│host │192.0.2.16│
├──────┼──────────┤
│port │80 │
├──────┼──────────┤
│path │/ │
└──────┴──────────┘
taskparts 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2'
┌──────┬───────────────────────────────────────────────┐
│scheme│urn │
├──────┼───────────────────────────────────────────────┤
│path │oasis:names:specification:docbook:dtd:xml:4.1.2│
└──────┴───────────────────────────────────────────────┘

View file

@ -0,0 +1,14 @@
taskparts 'mysql://test_user:ouupppssss@localhost:3306/sakila'
┌──────┬──────────┐
│scheme│mysql │
├──────┼──────────┤
│user │test_user │
├──────┼──────────┤
│pass │ouupppssss│
├──────┼──────────┤
│host │localhost │
├──────┼──────────┤
│port │3306 │
├──────┼──────────┤
│path │/sakila │
└──────┴──────────┘

View file

@ -0,0 +1,32 @@
taskparts 'ssh://alice@example.com'
┌──────┬───────────┐
│scheme│ssh │
├──────┼───────────┤
│user │alice │
├──────┼───────────┤
│host │example.com│
└──────┴───────────┘
taskparts 'https://bob:pass@example.com/place'
┌──────┬───────────┐
│scheme│https │
├──────┼───────────┤
│user │bob │
├──────┼───────────┤
│creds │pass │
├──────┼───────────┤
│host │example.com│
├──────┼───────────┤
│path │/place │
└──────┴───────────┘
taskparts 'http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64'
┌──────┬───────────────────────────────────────────┐
│scheme│http │
├──────┼───────────────────────────────────────────┤
│host │example.com │
├──────┼───────────────────────────────────────────┤
│path │/ │
├──────┼───────────────────────────────────────────┤
│query │┌─────────────────────────────────────────┐│
│ ││a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64││
│ │└─────────────────────────────────────────┘│
└──────┴───────────────────────────────────────────┘

View file

@ -0,0 +1,6 @@
URI uri;
try {
uri = new URI("foo://example.com:8042/over/there?name=ferret#nose");
} catch (URISyntaxException exception) {
/* invalid URI */
}

View file

@ -0,0 +1 @@
uri.getScheme()

View file

@ -0,0 +1,40 @@
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class MailTo {
private final To to;
private List<Field> fields;
public MailTo(String string) {
if (string == null)
throw new NullPointerException();
if (string.isBlank() || !string.toLowerCase().startsWith("mailto:"))
throw new IllegalArgumentException("Requires 'mailto' scheme");
string = string.substring(string.indexOf(':') + 1);
/* we can use the 'URLDecoder' class to decode any entities */
string = URLDecoder.decode(string, StandardCharsets.UTF_8);
/* the address and fields are separated by a '?' */
int indexOf = string.indexOf('?');
String[] address;
if (indexOf == -1)
address = string.split("@");
else {
address = string.substring(0, indexOf).split("@");
string = string.substring(indexOf + 1);
/* each field is separated by a '&' */
String[] fields = string.split("&");
String[] field;
this.fields = new ArrayList<>(fields.length);
for (String value : fields) {
field = value.split("=");
this.fields.add(new Field(field[0], field[1]));
}
}
to = new To(address[0], address[1]);
}
record To(String user, String host) { }
record Field(String name, String value) { }
}

View file

@ -0,0 +1,46 @@
(function (lstURL) {
var e = document.createElement('a'),
lstKeys = [
'hash',
'host',
'hostname',
'origin',
'pathname',
'port',
'protocol',
'search'
],
fnURLParse = function (strURL) {
e.href = strURL;
return lstKeys.reduce(
function (dct, k) {
dct[k] = e[k];
return dct;
}, {}
);
};
return JSON.stringify(
lstURL.map(fnURLParse),
null, 2
);
})([
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh://alice@example.com",
"https://bob:pass@example.com/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"
]);

View file

@ -0,0 +1,142 @@
[
{
"hash": "#nose",
"host": "example.com:8042",
"hostname": "example.com",
"origin": "foo://example.com:8042",
"pathname": "/over/there",
"port": "8042",
"protocol": "foo:",
"search": "?name=ferret"
},
{
"hash": "",
"host": "",
"hostname": "",
"origin": "urn://",
"pathname": "example:animal:ferret:nose",
"port": "",
"protocol": "urn:",
"search": ""
},
{
"hash": "",
"host": "",
"hostname": "",
"origin": "jdbc://",
"pathname": "mysql://test_user:ouupppssss@localhost:3306/sakila",
"port": "",
"protocol": "jdbc:",
"search": "?profileSQL=true"
},
{
"hash": "",
"host": "ftp.is.co.za",
"hostname": "ftp.is.co.za",
"origin": "ftp://ftp.is.co.za",
"pathname": "/rfc/rfc1808.txt",
"port": "",
"protocol": "ftp:",
"search": ""
},
{
"hash": "#header1",
"host": "www.ietf.org",
"hostname": "www.ietf.org",
"origin": "http://www.ietf.org",
"pathname": "/rfc/rfc2396.txt",
"port": "",
"protocol": "http:",
"search": ""
},
{
"hash": "",
"host": "[2001:db8::7]",
"hostname": "[2001:db8::7]",
"origin": "ldap://[2001:db8::7]",
"pathname": "/c=GB",
"port": "",
"protocol": "ldap:",
"search": "?objectClass=one&objectClass=two"
},
{
"hash": "",
"host": "",
"hostname": "",
"origin": "mailto://",
"pathname": "John.Doe@example.com",
"port": "",
"protocol": "mailto:",
"search": ""
},
{
"hash": "",
"host": "",
"hostname": "",
"origin": "news://",
"pathname": "comp.infosystems.www.servers.unix",
"port": "",
"protocol": "news:",
"search": ""
},
{
"hash": "",
"host": "",
"hostname": "",
"origin": "tel://",
"pathname": "+1-816-555-1212",
"port": "",
"protocol": "tel:",
"search": ""
},
{
"hash": "",
"host": "192.0.2.16:80",
"hostname": "192.0.2.16",
"origin": "telnet://192.0.2.16:80",
"pathname": "/",
"port": "80",
"protocol": "telnet:",
"search": ""
},
{
"hash": "",
"host": "",
"hostname": "",
"origin": "urn://",
"pathname": "oasis:names:specification:docbook:dtd:xml:4.1.2",
"port": "",
"protocol": "urn:",
"search": ""
},
{
"hash": "",
"host": "example.com",
"hostname": "example.com",
"origin": "ssh://example.com",
"pathname": "",
"port": "",
"protocol": "ssh:",
"search": ""
},
{
"hash": "",
"host": "example.com",
"hostname": "example.com",
"origin": "https://example.com",
"pathname": "/place",
"port": "",
"protocol": "https:",
"search": ""
},
{
"hash": "",
"host": "example.com",
"hostname": "example.com",
"origin": "http://example.com",
"pathname": "/",
"port": "",
"protocol": "http:",
"search": "?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"
}
]

View file

@ -0,0 +1,21 @@
# See Appendix B of RFC 3986
def URL:
capture("^((?<scheme>[^:/?#]+):)?(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?");
# The authority could be of the form: [username:password@]domain[:port]
def authority:
capture( "^((?<username>[^:@/]*):(?<password>[^@]*)@)?(?<domain>[^:?]*)(:(?<port>[0-9]*))?$" );
# The following filter first parses a valid URL into the five basic
# components, producing a JSON object with five keys; if the "authority"
# field can be futher parsed by `authority`, it is replaced by the
# corresponding JSON object.
def uri:
URL
| if .authority
then (.authority|authority) as $authority
| if $authority then .authority |= $authority
else .
end
else .
end;

View file

@ -0,0 +1,17 @@
def tests:
"foo://example.com:8042/over/there?name=ferret&color=grey#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2"
;
# For brevity, drop the `null`s:
tests
| [., (uri | (.. | select(.==null)) |= empty) ]

View file

@ -0,0 +1,54 @@
using Printf, URIParser
const FIELDS = names(URI)
function detailview(uri::URI, indentlen::Int=4)
indent = " "^indentlen
s = String[]
for f in FIELDS
d = string(getfield(uri, f))
!isempty(d) || continue
f != :port || d != "0" || continue
push!(s, @sprintf("%s%s: %s", indent, string(f), d))
end
join(s, "\n")
end
test = ["foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"This is not a URI!",
"ssh://alice@example.com",
"https://bob:pass@example.com/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"]
isfirst = true
for st in test
if isfirst
isfirst = false
else
println()
end
println("Attempting to parse\n \"", st, "\" as a URI:")
uri = try
URI(st)
catch
println("URIParser failed to parse this URI, is it OK?")
continue
end
print("This URI is parsable ")
if isvalid(uri)
println("and appears to be valid.")
else
println("but may be invalid.")
end
println(detailview(uri))
end

View file

@ -0,0 +1,50 @@
// version 1.1.2
import java.net.URL
import java.net.MalformedURLException
fun parseUrl(url: String) {
var u: URL
var scheme: String
try {
u = URL(url)
scheme = u.protocol
}
catch (ex: MalformedURLException) {
val index = url.indexOf(':')
scheme = url.take(index)
u = URL("http" + url.drop(index))
}
println("Parsing $url")
println(" scheme = $scheme")
with(u) {
if (userInfo != null) println(" userinfo = $userInfo")
if (!host.isEmpty()) println(" domain = $host")
if (port != -1) println(" port = $port")
if (!path.isEmpty()) println(" path = $path")
if (query != null) println(" query = $query")
if (ref != null) println(" fragment = $ref")
}
println()
}
fun main(args: Array<String>){
val urls = arrayOf(
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh://alice@example.com",
"https://bob:pass@example.com/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"
)
for (url in urls) parseUrl(url)
}

View file

@ -0,0 +1,27 @@
local url = require('socket.url')
local tests = {
'foo://example.com:8042/over/there?name=ferret#nose',
'urn:example:animal:ferret:nose',
'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto:John.Doe@example.com',
'news:comp.infosystems.www.servers.unix',
'tel:+1-816-555-1212',
'telnet://192.0.2.16:80/',
'urn:oasis:names:specification:docbook:dtd:xml:4.1.2'
}
for _, test in ipairs(tests) do
local parsed = url.parse(test)
io.write('URI: ' .. test .. '\n')
for k, v in pairs(parsed) do
io.write(string.format(' %s: %s\n', k, v))
end
io.write('\n')
end

View file

@ -0,0 +1,166 @@
Module checkit {
any=lambda (z$)->{=lambda z$ (a$)->instr(z$,a$)>0}
one=lambda (z$)->{=lambda z$ (a$)->z$=a$}
number$="0123456789"
series=Lambda -> {
func=Array([])
=lambda func (&line$, &res$)->{
if line$="" then exit
k=each(func)
def p=0,ok as boolean
while k {
ok=false : p++ : f=array(k)
if not f(mid$(line$,p,1)) then exit
ok=true
}
if ok then res$=left$(line$, p) : line$=mid$(line$, p+1)
=ok
}
}
is_any=lambda series, any (c$) ->series(any(c$))
is_one=lambda series, one (c$) ->series(one(c$))
Is_Alpha=series(lambda (a$)-> a$ ~ "[a-zA-Z]")
Is_digit=series(any(number$))
Is_hex=any(number$+"abcdefABCDEF")
optionals=Lambda -> {
func=Array([])
=lambda func (&line$, &res$)->{
k=each(func)
def ok as boolean
while k {
f=array(k)
if f(&line$,&res$) then ok=true : exit
}
=ok
}
}
repeated=Lambda (func)-> {
=lambda func (&line$, &res$)->{
def ok as boolean, a$
res$=""
do {
sec=len(line$)
if not func(&line$,&a$) then exit
res$+=a$
ok=true
} until line$="" or sec=len(line$)
=ok
}
}
oneAndoptional=lambda (func1, func2) -> {
=lambda func1, func2 (&line$, &res$)->{
def ok as boolean, a$
res$=""
if not func1(&line$,&res$) then exit
if func2(&line$,&a$) then res$+=a$
=True
}
}
many=Lambda -> {
func=Array([])
=lambda func (&line$, &res$)->{
k=each(func)
def p=0,ok as boolean, acc$
oldline$=line$
while k {
ok=false
res$=""
if line$="" then exit
f=array(k)
if not f(&line$,&res$) then exit
acc$+=res$
ok=true
}
if not ok then {line$=oldline$} else res$=acc$
=ok
}
}
is_safe=series(any("$-_@.&"))
Is_extra=series(any("!*'(),"+chr$(34)))
Is_Escape=series(any("%"), is_hex, is_hex)
\\Is_reserved=series(any("=;/#?: "))
is_xalpha=optionals(Is_Alpha, is_digit, is_safe, is_extra, is_escape)
is_xalphas=oneAndoptional(is_xalpha,repeated(is_xalpha))
is_xpalpha=optionals(is_xalpha, is_one("+"))
is_xpalphas=oneAndoptional(is_xpalpha,repeated(is_xpalpha))
Is_ialpha=oneAndoptional(Is_Alpha,repeated(is_xpalphas))
is_fragmentid=lambda is_xalphas (&lines$, &res$) -> {
=is_xalphas(&lines$, &res$)
}
is_search=oneAndoptional(is_xalphas, repeated(many(series(one("+")), is_xalphas)))
is_void=lambda (f)-> {
=lambda f (&oldline$, &res$)-> {
line$=oldline$
if f(&line$, &res$) then {oldline$=line$ } else res$=""
=true
}
}
is_scheme=is_ialpha
is_path=repeated(oneAndoptional(is_void(is_xpalphas), series(one("/"))))
is_uri=oneAndoptional(many(is_scheme, series(one(":")), is_path), many(series(one("?")),is_search))
is_fragmentaddress=oneAndoptional(is_uri, many(series(one("#")),is_fragmentid ))
data "foo://example.com:8042/over/there?name=ferret#nose"
data "urn:example:animal:ferret:nose"
data "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true "
data "ftp://ftp.is.co.za/rfc/rfc1808.txt"
data "http://www.ietf.org/rfc/rfc2396.txt#header1"
data "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"
data "mailto:John.Doe@example.com"
data "tel:+1-816-555-1212"
data "telnet://192.0.2.16:80/"
data "urn:oasis:names:specification:docbook:dtd:xml:4.1.2"
while not empty {
read What$
pen 15 {
Print What$
}
a$=""
If is_scheme(&What$, &a$) Then Print "Scheme=";a$ : What$=mid$(What$,2)
If is_path(&What$, &a$) Then {
count=0
while left$(a$, 1)="/" { a$=mid$(a$,2): count++}
if count>1 then {
domain$=leftpart$(a$+"/", "/")
a$=rightpart$(a$,"/")
if domain$<>"" Then Print "Domain:";Domain$
if a$<>"" Then Print "Path:";a$
} else.if left$(What$,1) =":" then {
Print "path:";a$+What$: What$=""
} Else Print "Data:"; a$
}
if left$(What$,1) =":" then {
is_number=repeated(is_digit)
What$=mid$(What$,2): If is_number(&What$, &a$) Then Print "Port:";a$
if not left$(What$,1)="/" then exit
If is_path(&What$, &a$) Then {
while left$(a$, 1)="/" { a$=mid$(a$,2)}
if a$<>"" Then Print "Path:";a$
}
}
if left$(What$, 1)="?" then {
What$=mid$(What$,2)
If is_search(&What$, &a$) Then {
v$=""
if left$(What$, 1)="=" then {
What$=mid$(What$,2)
If is_search(&What$, &v$) Then Print "Query:";a$;"=";v$
} else Print "Query:";a$
}
}
While left$(What$, 1)="#" {
What$=mid$(What$,2)
if not is_xalphas(&What$, &a$) Then exit
Print "fragment:";a$
}
if What$<>"" Then Print "Data:"; What$
}
}
Checkit

View file

@ -0,0 +1,41 @@
module Checkit {
Stack New {
Data "foo://example.com:8042/over/there?name=ferret#nose", "urn:example:animal:ferret:nose"
Data "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt"
Data "http://www.ietf.org/rfc/rfc2396.txt#header1", "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"
Data "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212"
Data "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://alice@example.com"
Data "https://bob:pass@example.com/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"
a=Array([])
}
function prechar$(a$, b$) {
if a$<>"" then {=quote$(b$+a$)} else ={""}
}
z=each(a)
document s$="["+{
}
While z {
a$=array$(z)
s1$={ "uri": }+quote$(a$)+{,
"authority": }+ quote$(string$(a$ as URLAuthority))+{,
"userInfo": }+ quote$(string$(a$ as URLUserInfo))+{,
"scheme": }+quote$(string$(a$ as URLScheme))+{,
"hostname": }+quote$(string$(a$ as UrlHost))+{,
"Port": }+quote$(string$(a$ as UrlPort))+{,
"pathname": }+quote$(string$(a$ as UrlPath))+{,
"search": }+prechar$(string$(a$ as URLpart 6),"?")+{,
"hash": }+prechar$(string$(a$ as UrlFragment),"#")+{
}
s$=" {"+{
}+s1$+" }"
\\ z^ is the iteraror's counter (z is an iterator of a, a touple - array in M2000)
if z^<len(a)-1 then s$=" ," ' append to document
s$={
}
}
s$="]"
Print "Press any keyboard key or mouse key to continue scrolling"
Report s$
Clipboard s$
}
Checkit

View file

@ -0,0 +1 @@
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]

View file

@ -0,0 +1,41 @@
import uri, strformat
proc printUri(url: string) =
echo url
let res = parseUri(url)
if res.scheme != "":
echo &"\t Scheme: {res.scheme}"
if res.hostname != "":
echo &"\tHostname: {res.hostname}"
if res.username != "":
echo &"\tUsername: {res.username}"
if res.password != "":
echo &"\tPassword: {res.password}"
if res.path != "":
echo &"\t Path: {res.path}"
if res.query != "":
echo &"\t Query: {res.query}"
if res.port != "":
echo &"\t Port: {res.port}"
if res.anchor != "":
echo &"\t Anchor: {res.anchor}"
if res.opaque:
echo &"\t Opaque: {res.opaque}"
let urls = ["foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh://alice@example.com",
"https://bob:pass@example.com/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"]
for url in urls:
printUri(url)

View file

@ -0,0 +1,26 @@
use Web.HTTP;
class Test {
function : Main(args : String[]) ~ Nil {
urls := [
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64:"];
each(i : urls) {
url := Url->New(urls[i]);
if(url->Parsed()) {
url->ToString()->PrintLine();
};
};
}
}

View file

@ -0,0 +1,22 @@
<?php
$urls = array(
'foo://example.com:8042/over/there?name=ferret#nose',
'urn:example:animal:ferret:nose',
'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto:John.Doe@example.com',
'news:comp.infosystems.www.servers.unix',
'tel:+1-816-555-1212',
'telnet://192.0.2.16:80/',
'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',
);
foreach ($urls AS $url) {
$p = parse_url($url);
echo $url, PHP_EOL;
print_r($p);
echo PHP_EOL;
}

View file

@ -0,0 +1,28 @@
#!/usr/bin/perl
use warnings;
use strict;
use URI;
for my $uri (do { no warnings 'qw';
qw( foo://example.com:8042/over/there?name=ferret#nose
urn:example:animal:ferret:nose
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:John.Doe@example.com
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
)}) {
my $u = 'URI'->new($uri);
print "$uri\n";
for my $part (qw( scheme path fragment authority host port query )) {
eval { my $parsed = $u->$part;
print "\t", $part, "\t", $parsed, "\n" if defined $parsed;
};
}
}

View file

@ -0,0 +1,37 @@
(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #000000;">url</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show_url_details</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">uri</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">uri</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">parse_url</span><span style="color: #0000FF;">(</span><span style="color: #000000;">uri</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">desc</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">url_element_desc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s : %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">desc</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span>
<span style="color: #008000;">"foo://example.com:8042/over/there?name=ferret#nose"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"urn:example:animal:ferret:nose"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"ftp://ftp.is.co.za/rfc/rfc1808.txt"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"http://www.ietf.org/rfc/rfc2396.txt#header1"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"mailto:John.Doe@example.com"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"news:comp.infosystems.www.servers.unix"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"tel:+1-816-555-1212"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"telnet://192.0.2.16:80/"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"urn:oasis:names:specification:docbook:dtd:xml:4.1.2"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"ssh://alice@example.com"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"https://bob:pass@example.com/place"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"</span>
<span style="color: #0000FF;">}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">show_url_details</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--

View file

@ -0,0 +1,43 @@
function Get-ParsedUrl
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[System.Uri]
$InputObject
)
Process
{
foreach ($url in $InputObject)
{
$url | Select-Object -Property Scheme,
@{Name="Domain"; Expression={$_.Host}},
Port,
@{Name="Path" ; Expression={$_.LocalPath}},
Query,
Fragment,
AbsolutePath,
AbsoluteUri,
Authority,
HostNameType,
IsDefaultPort,
IsFile,
IsLoopback,
PathAndQuery,
Segments,
IsUnc,
OriginalString,
DnsSafeHost,
IdnHost,
IsAbsoluteUri,
UserEscaped,
UserInfo
}
}
}

View file

@ -0,0 +1,17 @@
[string[]]$urls = @'
foo://example.com:8042/over/there?name=ferret#nose
urn:example:animal:ferret:nose
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:John.Doe@example.com
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
'@ -split [Environment]::NewLine
$parsedUrls = $urls | Get-ParsedUrl
$parsedUrls | Select-Object -Property Scheme, Port, Domain, Path, Query, Fragment | Format-Table

View file

@ -0,0 +1,14 @@
import urllib.parse as up # urlparse for Python v2
url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1#fragment')
print('url.scheme = ', url.scheme)
print('url.netloc = ', url.netloc)
print('url.hostname = ', url.hostname)
print('url.port = ', url.port)
print('url.path = ', url.path)
print('url.params = ', url.params)
print('url.query = ', url.query)
print('url.fragment = ', url.fragment)
print('url.username = ', url.username)
print('url.password = ', url.password)

View file

@ -0,0 +1,27 @@
library(urltools)
urls <- c("foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh://alice@example.com",
"https://bob:pass@example.com/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64")
for (an_url in urls) {
parsed <- url_parse(an_url)
cat(an_url,"\n")
for (idx in 1:ncol(parsed)) {
if (!is.na(parsed[[idx]])) {
cat(colnames(parsed)[[idx]],"\t:",parsed[[idx]],"\n")
}
}
cat("\n")
}

View file

@ -0,0 +1,36 @@
#lang racket/base
(require racket/match net/url)
(define (debug-url-string U)
(match-define (url s u h p pa? (list (path/param pas prms) ...) q f) (string->url U))
(printf "URL: ~s~%" U)
(printf "-----~a~%" (make-string (string-length (format "~s" U)) #\-))
(when #t (printf "scheme: ~s~%" s))
(when u (printf "user: ~s~%" u))
(when h (printf "host: ~s~%" h))
(when p (printf "port: ~s~%" p))
;; From documentation link in text:
;; > For Unix paths, the root directory is not included in `path';
;; > its presence or absence is implicit in the path-absolute? flag.
(printf "path-absolute?: ~s~%" pa?)
(printf "path bits: ~s~%" pas)
;; prms will often be a list of lists. this will print iff
;; one of the inner lists is not null
(when (memf pair? prms)
(printf "param bits: ~s [interleaved with path bits]~%" prms))
(unless (null? q) (printf "query: ~s~%" q))
(when f (printf "fragment: ~s~%" f))
(newline))
(for-each
debug-url-string
'("foo://example.com:8042/over/there?name=ferret#nose"
"urn:example:animal:ferret:nose"
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true"
"ftp://ftp.is.co.za/rfc/rfc1808.txt"
"http://www.ietf.org/rfc/rfc2396.txt#header1"
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two"
"mailto:John.Doe@example.com"
"news:comp.infosystems.www.servers.unix"
"tel:+1-816-555-1212"
"telnet://192.0.2.16:80/"
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2"))

View file

@ -0,0 +1,31 @@
use URI;
use URI::Escape;
my @test-uris = <
foo://example.com:8042/over/there?name=ferret#nose
urn:example:animal:ferret:nose
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass?one
mailto:John.Doe@example.com
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
ssh://alice@example.com
https://bob:pass@example.com/place
http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64
>;
my $u = URI.new;
for @test-uris -> $uri {
say "URI:\t", $uri;
$u.parse($uri);
for <scheme host port path query frag> -> $t {
my $token = try {$u."$t"()} || '';
say "$t:\t", uri-unescape $token.Str if $token;
}
say '';
}

View file

@ -0,0 +1,28 @@
require 'uri'
test_cases = [
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh://alice@example.com",
"https://bob:pass@example.com/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"
]
class URI::Generic; alias_method :domain, :host; end
test_cases.each do |test_case|
puts test_case
uri = URI.parse(test_case)
%w[ scheme domain port path query fragment user password ].each do |attr|
puts " #{attr.rjust(8)} = #{uri.send(attr)}" if uri.send(attr)
end
end

View file

@ -0,0 +1,56 @@
use url::Url;
fn print_fields(url: Url) -> () {
println!("scheme: {}", url.scheme());
println!("username: {}", url.username());
if let Some(password) = url.password() {
println!("password: {}", password);
}
if let Some(domain) = url.domain() {
println!("domain: {}", domain);
}
if let Some(port) = url.port() {
println!("port: {}", port);
}
println!("path: {}", url.path());
if let Some(query) = url.query() {
println!("query: {}", query);
}
if let Some(fragment) = url.fragment() {
println!("fragment: {}", fragment);
}
}
fn main() {
let urls = vec![
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh://alice@example.com",
"https://bob:pass@example.com/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64",
];
for url in urls {
println!("Parsing {}", url);
match Url::parse(url) {
Ok(valid_url) => {
print_fields(valid_url);
println!();
}
Err(e) => println!("Error Parsing url - {:?}", e),
}
}
}

View file

@ -0,0 +1,34 @@
import java.net.URI
object WebAddressParser extends App {
parseAddress("foo://example.com:8042/over/there?name=ferret#nose")
parseAddress("ftp://ftp.is.co.za/rfc/rfc1808.txt")
parseAddress("http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64")
parseAddress("http://www.ietf.org/rfc/rfc2396.txt#header1")
parseAddress("https://bob:pass@example.com/place")
parseAddress("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true")
parseAddress("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two")
parseAddress("ldap://[2001:db8::7]/c=GB?objectClass?one")
parseAddress("mailto:John.Doe@example.com")
parseAddress("news:comp.infosystems.www.servers.unix")
parseAddress("ssh://alice@example.com")
parseAddress("tel:+1-816-555-1212")
parseAddress("telnet://192.0.2.16:80/")
parseAddress("urn:example:animal:ferret:nose")
parseAddress("urn:oasis:names:specification:docbook:dtd:xml:4.1.2")
parseAddress("This is not a URI!")
private def parseAddress(a: String): Unit = {
print(f"Parsing $a%-72s")
try {
val u = new URI(a)
print("\u2714\tscheme = " + u.getScheme)
print("\tdomain = " + u.getHost)
print("\tport = " + (if (-1 == u.getPort) "default" else u.getPort))
print("\tpath = " + (if (u.getPath == null) u.getSchemeSpecificPart else u.getPath))
print("\tquery = " + u.getQuery)
println("\tfragment = " + u.getFragment)
} catch { case ex: Throwable => println('\u2718') }
}
}

View file

@ -0,0 +1,40 @@
package require uri
package require uri::urn
# a little bit of trickery to format results:
proc pdict {d} {
array set \t $d
parray \t
}
proc parse_uri {uri} {
regexp {^(.*?):(.*)$} $uri -> scheme rest
if {$scheme in $::uri::schemes} {
# uri already knows how to split it:
set parts [uri::split $uri]
} else {
# parse as though it's http:
set parts [uri::SplitHttp $rest]
dict set parts scheme $scheme
}
dict filter $parts value ?* ;# omit empty sections
}
set tests {
foo://example.com:8042/over/there?name=ferret#nose
urn:example:animal:ferret:nose
jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt#header1
ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two
mailto:John.Doe@example.com
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
}
foreach uri $tests {
puts \n$uri
pdict [parse_uri $uri]
}

View file

@ -0,0 +1,55 @@
import net.urllib
const urls = ['jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
'ftp://ftp.is.co.za/rfc/rfc1808.txt',
'http://www.ietf.org/rfc/rfc2396.txt#header1',
'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
'mailto:John.Doe@example.com',
'news:comp.infosystems.www.servers.unix',
'tel:+1-816-555-1212',
'telnet://192.0.2.16:80/',
'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',
'foo://example.com:8042/over/there?name=ferret#nose'
]
fn main() {
for url in urls {
u := urllib.parse(url)?
println(u)
print_url(u)
}
}
fn print_url(u urllib.URL) {
println(" Scheme: $u.scheme")
if u.opaque != "" {
println(" Opaque: $u.opaque")
}
if u.str() == '' {
println(" Username: $u.user.username")
if u.user.password != '' {
println(" Password: $u.user.password")
}
}
if u.host != "" {
if u.port() != '' {
println(" Host: ${u.hostname()}")
println(" Port: ${u.port()}")
} else {
println(" Host: $u.host")
}
}
if u.path != "" {
println(" Path: $u.path")
}
if u.raw_query != "" {
println(" RawQuery: $u.raw_query")
m := u.query().data
for q in m {
println(" Key: $q.key Values: $q.value")
}
}
if u.fragment != "" {
println(" Fragment: $u.fragment")
}
}

View file

@ -0,0 +1,96 @@
Function parse_url(url)
parse_url = "URL: " & url
If InStr(url,"//") Then
'parse the scheme
scheme = Split(url,"//")
parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1)
'parse the domain
domain = Split(scheme(1),"/")
'check if the domain includes a username, password, and port
If InStr(domain(0),"@") Then
cred = Split(domain(0),"@")
If InStr(cred(0),".") Then
username = Mid(cred(0),1,InStr(1,cred(0),".")-1)
password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),"."))
ElseIf InStr(cred(0),":") Then
username = Mid(cred(0),1,InStr(1,cred(0),":")-1)
password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":"))
End If
parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_
"Password: " & password
'check if the domain have a port
If InStr(cred(1),":") Then
host = Mid(cred(1),1,InStr(1,cred(1),":")-1)
port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & cred(1)
End If
ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then
host = Mid(domain(0),1,InStr(1,domain(0),":")-1)
port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":"))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then
host = Mid(domain(0),1,InStr(1,domain(0),"]"))
port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1))
parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port
Else
parse_url = parse_url & vbCrLf & "Domain: " & domain(0)
End If
'parse the path if exist
If UBound(domain) > 0 Then
For i = 1 To UBound(domain)
If i < UBound(domain) Then
path = path & domain(i) & "/"
ElseIf InStr(domain(i),"?") Then
path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1)
If InStr(domain(i),"#") Then
query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1)
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment
Else
query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?"))
path = path & vbcrlf & "Query: " & query
End If
ElseIf InStr(domain(i),"#") Then
fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#"))
path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_
"Fragment: " & fragment
Else
path = path & domain(i)
End If
Next
parse_url = parse_url & vbCrLf & "Path: " & path
End If
ElseIf InStr(url,":") Then
scheme = Mid(url,1,InStr(1,url,":")-1)
path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":"))
parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path
Else
parse_url = parse_url & vbcrlf & "Invalid!!!"
End If
End Function
'test the convoluted function :-(
WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2")
WScript.StdOut.WriteLine "-------------------------------"
WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")

View file

@ -0,0 +1,115 @@
var urlParse = Fn.new { |url|
var parseUrl = "URL = " + url
var index
if ((index = url.indexOf("//")) && index >= 0 && url[0...index].count { |c| c == ":" } == 1) {
// parse the scheme
var scheme = url.split("//")
parseUrl = parseUrl + "\n" + "Scheme = " + scheme[0][0..-2]
// parse the domain
var domain = scheme[1].split("/")
// check if the domain includes a username, password and port
if (domain[0].contains("@")) {
var cred = domain[0].split("@")
var split = [cred[0], ""]
if (cred[0].contains(".")) {
split = cred[0].split(".")
} else if (cred[0].contains(":")) {
split = cred[0].split(":")
}
var username = split[0]
var password = split[1]
parseUrl = parseUrl + "\n" + "Username = " + username
if (password != "") parseUrl = parseUrl + "\n" + "Password = " + password
// check if the domain has a port
if (cred[1].contains(":")) {
split = cred[1].split(":")
var host = split[0]
var port = ":" + split[1]
parseUrl = parseUrl + "\n" + "Domain = " + host + "\n" + "Port = " + port
} else {
parseUrl = parseUrl + "\n" + "Domain = " + cred[1]
}
} else if (domain[0].contains(":") && !domain[0].contains("[") && !domain[0].contains("]")) {
var split = domain[0].split(":")
var host = split[0]
var port = ":" + split[1]
parseUrl = parseUrl + "\n" + "Domain = " + host + "\n" + "Port = " + port
} else if (domain[0].contains("[") && domain[0].contains("]:")) {
var split = domain[0].split("]")
var host = split[0] + "]"
var port = ":" + split[1][1..-1]
parseUrl = parseUrl + "\n" + "Domain = " + host + "\n" + "Port = " + port
} else {
parseUrl = parseUrl + "\n" + "Domain = " + domain[0]
}
// parse the path if it exists
if (domain.count > 1) {
var path = "/"
for (i in 1...domain.count) {
if (i < domain.count - 1) {
path = path + domain[i] + "/"
} else if (domain[i].contains("?")) {
var split = domain[i].split("?")
path = path + split[0]
if (domain[i].contains("#")) {
var split2 = split[1].split("#")
var query = split2[0]
var fragment = split2[1]
path = path + "\n" + "Query = " + query + "\n" + "Fragment = " + fragment
} else {
var query = split[1]
path = path + "\n" + "Query = " + query
}
} else if (domain[i].contains("#")) {
var split = domain[i].split("#")
var fragment = split[1]
path = path + split[0] + "\n" + "Fragment = " + fragment
} else {
path = path + domain[i]
}
}
parseUrl = parseUrl + "\n" + "Path = " + path
}
} else if (url.contains(":")) {
var index = url.indexOf(":")
var scheme = url[0...index]
parseUrl = parseUrl + "\n" + "Scheme = " + scheme + "\n"
var path = url[index+1..-1]
if (!path.contains("?")) {
parseUrl = parseUrl + "Path = " + path
} else {
var split = path.split("?")
var query = split[1]
parseUrl = parseUrl + "Path = " + split[0] + "\n"
if (!query.contains("#")) {
parseUrl = parseUrl + "Query = " + query
} else {
split = query.split("#")
var fragment = split[1]
parseUrl = parseUrl + "Query = " + split[0] + "Fragment = " + fragment
}
}
} else {
parseUrl = parseUrl + "\n" + "Invalid!!!"
}
System.print(parseUrl)
System.print()
}
var urls = [
"foo://example.com:8042/over/there?name=ferret#nose",
"urn:example:animal:ferret:nose",
"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true",
"ftp://ftp.is.co.za/rfc/rfc1808.txt",
"http://www.ietf.org/rfc/rfc2396.txt#header1",
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:John.Doe@example.com",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh://alice@example.com",
"https://bob:pass@example.com/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=\%65\%6e\%63\%6F\%64\%65\%64"
]
for (url in urls) urlParse.call(url)