Précédent   Forum du club des développeurs et IT Pro > Webmasters - Développement Web > Contribuez
Contribuez Proposez vos articles, cours, tutoriels, questions/réponses pour les FAQ, sources et autres ressources pour la rubrique Web ainsi que ses sous-rubriques.
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse
 
Outils de la discussion
Publicité
'
Vieux 22/03/2012, 14h42   #1
sekaijin
Expert Confirmé Sénior
 
Avatar de sekaijin
 
Homme
Urbaniste
Inscription : juillet 2004
Messages : 2 117
Détails du profil
Informations personnelles :
Sexe : Homme
Âge : 49
Localisation : France, Yvelines (Île de France)

Informations professionnelles :
Activité : Urbaniste
Secteur : Santé

Informations forums :
Inscription : juillet 2004
Messages : 2 117
Points : 5 038
Points : 5 038
Par défaut URI Scheme: URIBuilder

bonjour.

si vous allez sur la page : http://en.wikipedia.org/wiki/URI_scheme
vous trouverez une doc sur la syntaxe des URI (URN, URL)
dont voici un résumé:
Code plaintext :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  foo://username:password@example.com:8042/over/there/index.dtb?type=animal&name=narwhal#nose
  \_/   \_______________/ \_________/ \__/            \___/ \_/ \______________________/ \__/
   |           |               |       |                |    |            |                |
   |       userinfo         hostname  port              |    |          query          fragment
   |    \________________________________/\_____________|____|/ \__/ \____/ \__/ \_____/
   |                    |                          |    |    |    |     |     |     |
scheme              authority                    path   |    |    interpretable as keys
 name   \_______________________________________________|____|/         |           |
   |                         |                          |    |    interpretable as values
   |                 hierarchical part                  |    |
   |                                                    |    |
   |            path               interpretable as filename |
   |   ___________|____________                              |
  / \ /                        \                             |
  urn:example:animal:ferret:nose               interpretable as extension
 
 scheme
  name  userinfo  hostname       query
  _|__   ___|__   ____|____   _____|_____
 /    \ /      \ /         \ /           \
 mailto:username@example.com?subject=Topic

créant dynamiquement beaucoup d'uri à partir de nombreuses informations issues de diverses source je me suis fait une classe URIBuilder qui propose un DSL pour créer une URI. je travaille en java mais un portage vers JavaScript était peut coûteux le voici donc.
Code javascript :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
URIBuilder = function() {
	this.schemename = null;
	this.username = null;
	this.pass = null;
	this.hostname = null;
	this.portnumber = null;
	this.fullpath = null;
	this.querystring = null;
	this.fragmentname = null;
 
	this.schemeName = function(string) {
		this.schemename = string;
		return this;
	};
	this.userName = function(string) {
		this.username = string;
		return this;
	};
	this.password = function(string) {
		this.pass = string;
		return this;
	};
	this.hostName = function(string) {
		this.hostname = string;
		return this;
	};
	this.port = function(string) {
		this.portnumber = string;
		return this;
	};
	this.path = function(string) {
		this.fullpath = string;
		return this;
	};
	this.query = function(string) {
		this.querystring = string;
		return this;
	};
	this.fragment = function(string) {
		this.fragmentname = string;
		return this;
	};
 
	this.getSchemeName = function(string) {
		return this.schemename;
	};
	this.getUserName = function(string) {
		return this.username;
	};
	this.getPassword = function(string) {
		return this.pass;
	};
	this.getHostName = function(string) {
		return this.hostname;
	};
	this.getPort = function(string) {
		return this.portnumber;
	};
	this.getPath = function(string) {
		return this.fullpath;
	};
	this.getQuery = function(string) {
		return this.querystring;
	};
	this.getFragment = function(string) {
		return this.fragmentname;
	};
 
	this.getUserinfo = function(string) {
		if (null != this.getPassword()) {
			return this.getUserName() + ":" + this.getPassword();
		} else {
			return this.getUserName()
		}
	};
	this.getLocation = function(string) {
		if (null != this.getPort()) {
			return this.getHostName() + ":" + this.getPort();
		} else {
			return this.getHostName()
		}
	};
	this.getAuthority = function(string) {
		if (null != this.getUserinfo()) {
			return this.getUserinfo() + "@" + this.getLocation();
		} else {
			return this.getLocation()
		}
	};
	this.getHierarchical = function(string) {
		return this.getAuthority() + this.getPath();
	};
 
	this.getUri = function(string) {
		uri = this.getSchemeName();
		if (null != this.getAuthority()) {
			uri = uri + "://" + this.getHierarchical();
		} else {
			uri = uri + ":" + this.getPath()
		}
		if (null != this.getQuery()) {
			uri = uri + "?" + this.getQuery()
		}
		if (null != this.getFragment()) {
			uri = uri + "#" + this.getFragment()
		}
		return uri;
	};
}
//une petite facilité
URIBuilder.newBuilder = function(){
	return new URIBuilder();
}
Pour mieux comprendre comment cela fonctionne quelques exemples
Code javascript :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
uriBuilder = new URIBuilder();
//une URN
console.log(uriBuilder
	.schemeName('urn')
	.path('org.jsunit.test')
	.getUri());
 
//un url http avec le même builder (recyclé)
console.log(uriBuilder
	.schemeName('http')
	.hostName('localhost')
	.port(8081)
	.path('/org/jsunit/test.php')
	.getUri());
 
//ajout d'un login à l'url
console.log(uriBuilder
	.userName('jhon')
	.password('doe')
	.getUri());
 
//ajout d'une query et une ancre à l'url
console.log(uriBuilder
	.query('var=15&sort=desc')
	.fragment('ancre1')
	.getUri());
 
//création d'une url en une seule ligne
console.log(URIBuilder.newBuilder()
	.schemeName('http')
	.userName('jhon')
	.password('doe')
	.hostName('localhost')
	.port(8081)
	.path('/org/jsunit/test.php')
	.query('var=15&sort=desc')
	.fragment('ancre1')
	.getUri());
A+JYT
sekaijin est déconnecté   Envoyer un message privé Réponse avec citation 10
Vieux 23/03/2012, 03h31   #2
danielhagnoul
Rédacteur
 
Avatar de danielhagnoul
 
Homme Daniel Hagnoul
Étudiant perpétuel
Inscription : février 2009
Messages : 3 848
Détails du profil
Informations personnelles :
Nom : Homme Daniel Hagnoul
Âge : 62
Localisation : Belgique

Informations professionnelles :
Activité : Étudiant perpétuel
Secteur : Enseignement

Informations forums :
Inscription : février 2009
Messages : 3 848
Points : 14 346
Points : 14 346
Bonsoir

Intéressant !

En jQuery on a déjà :

Il sera utile de comparer les versions, mais je regarderais cela plus tard, car je crois qu'il est l'heure d'aller dormir (03:30 !).
__________________

FAQ jQuery

Mon cahier d’exercices sur jQuery & Co

plugin dialogModal

Si un message vous a aidé ou vous semble pertinent, votez pour lui !
danielhagnoul est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 23/03/2012, 07h26   #3
sekaijin
Expert Confirmé Sénior
 
Avatar de sekaijin
 
Homme
Urbaniste
Inscription : juillet 2004
Messages : 2 117
Détails du profil
Informations personnelles :
Sexe : Homme
Âge : 49
Localisation : France, Yvelines (Île de France)

Informations professionnelles :
Activité : Urbaniste
Secteur : Santé

Informations forums :
Inscription : juillet 2004
Messages : 2 117
Points : 5 038
Points : 5 038
Merci pour les références
lorsque j'ai développé URIBuilder mon problème était justement que je ne trouvais que des choses comme celles que propose JQuery
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$.url.build({
	protocol: 'http',
	username: 'username',
	password: 'password',
	host: 'hostname',
	path: '/path',
	query: 'arg1=value%40+1&arg2=touch%C3%A9',
	// or 
	//params: {
	//	'arg1': 'value@ 1',
	//	'arg2': 'touché'
	//}
	anchor: 'anchor',
})
cette façon de faire nécessite de tout avoir à disposition dès l'appel au constructeur

passer par un builder permet de construire l'objet (ici une URI) par étape par exemple dans une méthode don lit dans une base les infos sur le site à atteindre et on prépare l'URL de base
Code :
1
2
3
4
5
uriBuilder
	.schemeName('http')
	.hostName('localhost')
	.port(8081)
	.path('/org/jsunit/test.php');
puis dans une autre on interroge la base des utilisateurs pour savoir quel compte utiliser
Code :
1
2
3
4
uriBuilder
	.userName('jhon')
	.password('doe')
	.getUri()
l'url est complète on paut la récupérer.
avec une solution comme JQuery un faut cumuler les différentes partie dans un objet et le passer au final à la méthode url.

le code que je propose n'est pas incompatible il pourrait très bien utiliser jquery
la méthode getUriString peut facilement être réécrite avec un appel à JQuery.url

les deux sont donc complémentaire.
une intégration des deux pourrait donner
Code :
1
2
3
b = $.URIBuilder()
...
b.getURIString() //qui retourne le résultat de l'appel à $.uri.build(...)
le builder sert à conserver les élément nécessaire à la création de l'objet jusqu'au build final
de plus l'écrire sous forme de DSL permet d'avoir une syntaxe qui reste claire

A+JYT
sekaijin est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 23/03/2012, 23h41   #4
danielhagnoul
Rédacteur
 
Avatar de danielhagnoul
 
Homme Daniel Hagnoul
Étudiant perpétuel
Inscription : février 2009
Messages : 3 848
Détails du profil
Informations personnelles :
Nom : Homme Daniel Hagnoul
Âge : 62
Localisation : Belgique

Informations professionnelles :
Activité : Étudiant perpétuel
Secteur : Enseignement

Informations forums :
Inscription : février 2009
Messages : 3 848
Points : 14 346
Points : 14 346
Bonsoir

Je ne mettais pas en cause l'utilité de ton travail, car jusqu'ici je me sers uniquement de la seconde référence ( https://github.com/allmarkedup/jQuery-URL-Parser ) pour parser des URI et je voulais simplement tester si les URI construits avec ta méthode étaient correctement analysés par le programme qui a ma préférence dans le but de me servir des deux et de contrôler l'un par l'autre.

Comme je le pensais hier soir il y a un petit problème.

Si j'analyse l'exemple :

Code :
1
2
3
4
5
var url = $.url( 'foo://username:password@example.com:8042/over/there/index.dtb?type=animal&name=narwhal#nose' );
 
$.each( url.data, function( key, value ){
    console.log( key, value );
});
le résultat est correct :

authority = "username:password@example.com:8042"
base = "foo://example.com:8042"
directory = "/over/there/"
file = "index.dtb"
fragment = "nose"
host = "example.com"
password = "password"
path = "/over/there/index.dtb"
port = "8042"
protocol = "foo"
query = "type=animal&name=narwhal"
relative = "/over/there/index.dtb?t...nimal&name=narwhal#nose"	
source = "foo://username:password...nimal&name=narwhal#nose"	
user = "username"
userInfo = "username:password"
Si j'analyse : 'http://allmarkedup.com?sky=blue&grass=green' le résultat est correct.

Mais si j'analyse :

Code :
1
2
3
var url = $.url( uriBuilder.schemeName( 'http' ).userName( 'jhon' ).password( 'doe' )
				.hostName( 'localhost' ).port( 8081 ).path( '/org/jsunit/test.php' )
				.query( 'var=15&sort=desc' ).fragment( 'ancre1' ).getUri() );
le résultat n'est pas correct (il manque plusieurs paramètres, par exemple query) :

authority = "jhon:doe@localhost:8081"
base = "http://localhost:8081"
directory = ""
file = ":"
fragment = ""
host = "localhost"
password = "doe"
path = ":"
port = "8081"
protocol = "http"
query = ""
relative = ":"
source = "http://jhon:doe@localhost:8081:"
user = "jhon"
userInfo = "jhon:doe"
L'URI générée est : 'http://jhon:doe@localhost:8081:/org/jsunit/test.php?var=15&sort=desc#ancre1'

Je crois que le second ":" est en excédent, car sans lui j'obtiens une analyse complète et correcte.

authority = "jhon:doe@localhost:8081"
base = "http://localhost:8081"
directory = "/org/jsunit/"
file = "test.php"
fragment = "ancre1"
host = "localhost"
password = "doe"
path = "/org/jsunit/test.php"
port = "8081"
protocol = "http"
query = "var=15&sort=desc"
relative = "/org/jsunit/test.php?var=15&sort=desc#ancre1"
source = "http://jhon:doe@localho...var=15&sort=desc#ancre1"
user = "jhon"	
userInfo = "jhon:doe"
__________________

FAQ jQuery

Mon cahier d’exercices sur jQuery & Co

plugin dialogModal

Si un message vous a aidé ou vous semble pertinent, votez pour lui !
danielhagnoul est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 24/03/2012, 11h32   #5
sekaijin
Expert Confirmé Sénior
 
Avatar de sekaijin
 
Homme
Urbaniste
Inscription : juillet 2004
Messages : 2 117
Détails du profil
Informations personnelles :
Sexe : Homme
Âge : 49
Localisation : France, Yvelines (Île de France)

Informations professionnelles :
Activité : Urbaniste
Secteur : Santé

Informations forums :
Inscription : juillet 2004
Messages : 2 117
Points : 5 038
Points : 5 038
oops un bug
Merci à toi dans le portage j'ai ajouté un ":" dans la méthode getHierarchical
j'ai corrigé la chose dans le post initial.
Code :
1
2
3
	this.getHierarchical = function(string) {
		return this.getAuthority() + this.getPath();
	};
merci
A+JYT
sekaijin est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse
Outils de la discussion

Navigation rapide


Fuseau horaire GMT +2. Il est actuellement 13h51.


 
 
 
 
Partenaires

Hébergement Web