Project

General

Profile

Corot » History » Version 10

Anonymous, 05/06/2012 16:37

1 1 Anonymous
h1. Corot
2 1 Anonymous
3 1 Anonymous
4 8 Anonymous
h2. Scripts de création des imagettes 
5 8 Anonymous
6 8 Anonymous
Premièrement, récupérer la liste des corotid à traiter. On peut séparer par run_code pour faire tourner le script moins longtemps et faire moins chauffer le corot-lightcurve et son repertoire 'temp'.
7 8 Anonymous
8 8 Anonymous
On récupère donc les corotid depuis pgadmin3 (exemple pour SRa05 et EN2_STAR_CHR : select distinct corotid from exo_n2_view where run_code like 'SRa05%' and en2_star_mon; )
9 8 Anonymous
10 8 Anonymous
Puis avec emacs on rajoute le début de l'url : http://idoc-corot-lightcurve.ias.u-psud.fr/rest/tempo/basic/N2/SRa05/ (dans un fichier, par exemple "links.txt")
11 8 Anonymous
12 8 Anonymous
On utilise tempo qui pointe vers les data privés mais sans authentification (ligne à décommenter dans spring-config.xml sur idc-appli2 : /usr/local/tomcat_corot/webapps/corot-lightcurve/WEB-INF/conf)
13 8 Anonymous
14 8 Anonymous
Puis on exécute le script perl qui va générer les *.png dans  /usr/local/tomcat_corot/webapps/corot-lightcurve/temp/ : 
15 8 Anonymous
16 8 Anonymous
<pre><code class="java">
17 8 Anonymous
18 8 Anonymous
#!/usr/bin/perl
19 8 Anonymous
open READ, "< links.txt";
20 8 Anonymous
while (<READ>)
21 8 Anonymous
{
22 8 Anonymous
  chomp;
23 8 Anonymous
  system("curl $_ | grep \"alt=\\\"Light curve for corot id\" >> adr_img.txt");
24 8 Anonymous
}
25 8 Anonymous
26 8 Anonymous
</code></pre>
27 8 Anonymous
28 8 Anonymous
29 8 Anonymous
On obtient une ligne par imagette générée.
30 8 Anonymous
31 8 Anonymous
<img src="http://idoc-corot-lightcurve.ias.u-psud.fr/temp/lightcurve_8653845841090318133.png" alt="Light curve for corot id : 223925326 (run SRa05)" />
32 8 Anonymous
33 8 Anonymous
Il faut ensuite copier les imagettes en local et les renommer : D'abord éditer avec Emacs (avec des replace string) pour obtenir :
34 8 Anonymous
35 8 Anonymous
http://idoc-corot-lightcurve.ias.u-psud.fr/temp/lightcurve_8653845841090318133.png > img_exo_223925326_SRa05.png
36 8 Anonymous
37 8 Anonymous
Puis lancer le 2eme script perl :
38 8 Anonymous
39 8 Anonymous
<pre><code class="java">
40 8 Anonymous
41 8 Anonymous
#!/usr/bin/perl
42 8 Anonymous
open READ, "< adr_img.txt";
43 8 Anonymous
while (<READ>)
44 8 Anonymous
{
45 8 Anonymous
  chomp;
46 8 Anonymous
  system("curl $_");
47 8 Anonymous
}
48 8 Anonymous
49 8 Anonymous
</code></pre>
50 8 Anonymous
51 8 Anonymous
52 1 Anonymous
h2. Gestion des imagettes dans le Detail
53 1 Anonymous
54 1 Anonymous
Dans le fichier : /usr/local/Sitools2_Corot/workspace/client-user/js/components/viewDataDetail/viewDataDetail.js
55 1 Anonymous
Ligne 102 : collapsed : false
56 2 Anonymous
57 2 Anonymous
58 2 Anonymous
h2. Export VOTABLE
59 3 Anonymous
60 3 Anonymous
Dans contextMenu.js (client) :
61 3 Anonymous
62 3 Anonymous
<pre><code class="javascript">
63 4 Anonymous
         // ligne 864 fichier version 0.9.1
64 3 Anonymous
        // on test que l'utilisateur ne selectionne pas CHR et MON en meme temps + qu'il n'a pas pris de WINDESC et d'IMAG
65 3 Anonymous
	if((request.search("EN2_STAR_CHR")!=-1 && request.search("EN2_STAR_MON")!=-1) || request.search("EN2_WIN")!=-1 || request.search("EN2_STAR_IMAG")!=-1){
66 3 Anonymous
                       // si oui on l'averti que ce n'est pas possible et on ne lance pas le VOTable
67 3 Anonymous
			Ext.Msg.alert("WARNING !", "DONT SELECT WINDESCRIPTOR OR IMAG" +  "<br/>"  + " ALSO DONT PICK EN2_STAR_MON AND EN2_STAR_CHR AT THE SAME TIME PLEASE !!!");
68 3 Anonymous
69 3 Anonymous
		}else{ 
70 3 Anonymous
 // sinon on lance exportVOTable
71 3 Anonymous
72 3 Anonymous
			
73 3 Anonymous
			url += "?1=1" + request;
74 3 Anonymous
			if (!Ext.isEmpty(limit)) {
75 3 Anonymous
				url += "&limit=" + limit;
76 3 Anonymous
			}
77 3 Anonymous
			if (! Ext.isEmpty(userParameters)) {
78 3 Anonymous
				Ext.iterate(userParameters, function (key, value) {
79 3 Anonymous
					url += "&" + key + "=" + value; 
80 3 Anonymous
				});
81 3 Anonymous
			}
82 3 Anonymous
			
83 3 Anonymous
			// If Get => the Resource MUST be synchrone and then send a representation
84 3 Anonymous
			if (method == "GET") {
85 3 Anonymous
				window.open(url);
86 3 Anonymous
				Ext.getBody().unmask();
87 3 Anonymous
				return;
88 3 Anonymous
			} else {
89 3 Anonymous
				this._executeRequestForResource(url, method);
90 3 Anonymous
			}
91 3 Anonymous
		}
92 3 Anonymous
93 6 Anonymous
</code></pre>
94 5 Anonymous
95 5 Anonymous
96 5 Anonymous
Puis dans ExportVORessource.java :
97 5 Anonymous
98 5 Anonymous
<pre><code class="java">
99 5 Anonymous
     // ligne 192
100 5 Anonymous
     // Execute request to know which value are selected
101 5 Anonymous
        String primkey=""; 
102 5 Anonymous
        Integer type=0;
103 5 Anonymous
        try {
104 5 Anonymous
            primkey = databaseRequest.getRequestAsString(); //.getSelectedPrimaryKey();
105 5 Anonymous
            boolean found = primkey.contains("AN2");
106 5 Anonymous
            if(found){
107 5 Anonymous
                System.out.println("J'ai trouvé AN2 !!!\n");
108 5 Anonymous
                type=1;
109 5 Anonymous
            }else{
110 5 Anonymous
            //System.out.println("AN2 non trouvé !!!\n");
111 5 Anonymous
            if((primkey.contains("EN2_STAR_CHR") && primkey.contains("EN2_STAR_MON")) || primkey.contains("EN2_WIN") || primkey.contains("EN2_STAR_IMAG")){
112 5 Anonymous
                System.out.println("Error j'ai trouvé CHR et MON !!!\n");
113 5 Anonymous
            }else{ 
114 5 Anonymous
                if(primkey.contains("EN2_STAR_CHR")){
115 5 Anonymous
                    System.out.println("J'ai trouvé CHR !!!\n");
116 5 Anonymous
                    type = 2;
117 5 Anonymous
                } else{ 
118 5 Anonymous
                    if(primkey.contains("EN2_STAR_MON")){
119 5 Anonymous
                        System.out.println("J'ai trouvé MON !!!\n");
120 5 Anonymous
                        type = 3;   
121 5 Anonymous
                    }
122 5 Anonymous
                    }
123 5 Anonymous
                }
124 5 Anonymous
            }
125 5 Anonymous
        System.out.println("Type vaux : " + type);
126 5 Anonymous
        } catch (SitoolsException ex) {
127 5 Anonymous
            Logger.getLogger(ExportVOResource.class.getName()).log(Level.SEVERE, null, ex);
128 5 Anonymous
        }
129 5 Anonymous
       System.out.println("primkey : " + primkey); // astero et AN2_STAR dans la requete !!!
130 5 Anonymous
131 5 Anonymous
      [ ........  ]
132 5 Anonymous
133 5 Anonymous
     // ligne 246
134 5 Anonymous
    String template_name = "";
135 5 Anonymous
        if (type==1)
136 5 Anonymous
            template_name = "template_astero.ftl";
137 5 Anonymous
        else if (type==2)
138 5 Anonymous
             template_name = "template_exo_chr.ftl";
139 5 Anonymous
        else if (type==3)
140 5 Anonymous
             template_name = "template_exo_mon.ftl";
141 5 Anonymous
        
142 5 Anonymous
        
143 5 Anonymous
        System.out.println("j'envoie le template : " + template_name);
144 5 Anonymous
        
145 5 Anonymous
        //Return the response
146 7 Anonymous
        if (type!=0)
147 7 Anonymous
           return new VOTableRepresentation(dataModel, template_name);
148 7 Anonymous
        else
149 7 Anonymous
           return null;
150 6 Anonymous
</code></pre>
151 6 Anonymous
152 6 Anonymous
153 6 Anonymous
154 6 Anonymous
Les templates.ftl doivent être dans le folder de VOTableRepresentation.java et doivent être bien définis.
155 6 Anonymous
156 6 Anonymous
Exemple :  Pour EN2_STAR_MON, template_exo_mon.ftl
157 6 Anonymous
158 6 Anonymous
<pre><code class="XML">
159 6 Anonymous
160 6 Anonymous
<?xml version="1.0" encoding="UTF-8"?>
161 6 Anonymous
<VOTABLE version="1.2" 
162 6 Anonymous
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
163 6 Anonymous
xsi:schemaLocation="http://www.ivoa.net/xml/VOTable/v1.2" 
164 6 Anonymous
xmlns="http://www.ivoa.net/xml/VOTable/v1.2">
165 6 Anonymous
<!--
166 6 Anonymous
 !  VOTable written by MHUSSON@IAS version 0.1 (mhusson@ias.u-psud.fr)
167 6 Anonymous
 !  at 2012-03-30
168 6 Anonymous
 !  Best use with TOPCAT 3.9 or higher version
169 6 Anonymous
 !-->
170 6 Anonymous
    <RESOURCE name="COROT N2 EN2MON">        
171 6 Anonymous
        <DESCRIPTION>COROT N2 PUBLIC DATA VOTABLE STREAM FORMAT</DESCRIPTION>          
172 6 Anonymous
	<PARAM name="COROT VERSION" datatype="char" arraysize="*" value="N2">
173 6 Anonymous
		<DESCRIPTION>COROT N2 FITS STREAM</DESCRIPTION>
174 6 Anonymous
	</PARAM>
175 6 Anonymous
	<INFO name="SITOOLS2 COROT PROJECT" value="http://idoc-corotn2-public-v2.ias.u-psud.fr">
176 6 Anonymous
		VOTABLE generated with SItools2 COROT and exportVO Ressource (J-C.Malapert@CNES, M.Husson@IAS)
177 6 Anonymous
	</INFO>
178 6 Anonymous
 	<TABLE ID="reference">
179 6 Anonymous
	<FIELD ID="date" arraysize="23" datatype="char" name="DATE" unit="yyyy-mm-jjThh:mi:ss"/>
180 6 Anonymous
	<FIELD ID="datejd" datatype="double" name="DATEJD" unit="COROT JULIAN DAY"/>
181 6 Anonymous
	<FIELD ID="datehel" datatype="double" name="DATEHEL" unit="COROT JULIAN DAY"/>
182 6 Anonymous
	<FIELD ID="status" datatype="int" name="STATUS"/>
183 6 Anonymous
	<FIELD ID="whiteflux" datatype="float" name="WHITEFLUX" unit="ELECTRONS"/>
184 6 Anonymous
	<FIELD ID="whitefluxdev" datatype="float" name="WHITEFLUXDEV" unit="ELECTRONS"/>
185 6 Anonymous
	<FIELD ID="bg" datatype="float" name="BG" unit="ELECTRONS PER PIXEL"/>
186 6 Anonymous
	<FIELD ID="correc" datatype="float" name="CORREC" unit="ELECTRONS"/>
187 6 Anonymous
	</TABLE>
188 6 Anonymous
	<#list rows as row>
189 6 Anonymous
	<TABLE ref="reference" name="${row["file"]}">
190 6 Anonymous
	<PARAM name="COROT ID" value="${row["corotid"]}"/>
191 6 Anonymous
	<PARAM name="COROT RUN" value="${row["run_code"]}"/>
192 6 Anonymous
        	<DATA>
193 6 Anonymous
			<FITS extnum="1">
194 6 Anonymous
				<STREAM actuate="onRequest" href="${row["download"]}"/>
195 6 Anonymous
			</FITS>
196 6 Anonymous
        	   </DATA>
197 6 Anonymous
        </TABLE>
198 6 Anonymous
    	</#list>
199 6 Anonymous
    </RESOURCE>
200 6 Anonymous
</VOTABLE>
201 6 Anonymous
202 6 Anonymous
</code></pre> 
203 9 Anonymous
204 9 Anonymous
205 9 Anonymous
h2. Les composants de formulaire : 
206 9 Anonymous
207 9 Anonymous
Le Date Begin-end : qui permet de faire une requête sur deux colonnes différentes, "date de début" et "date de fin". On récupère ainsi les observations dont la date de début est intervenu après "date de début" et dont la fin est intervenu avant la "date de fin".
208 9 Anonymous
209 9 Anonymous
Le code javascript correspondant : 
210 9 Anonymous
211 9 Anonymous
Partie ADMIN : 
212 9 Anonymous
213 9 Anonymous
<pre><code class="javascript">
214 9 Anonymous
215 9 Anonymous
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser, 
216 9 Anonymous
 showHelp*/
217 9 Anonymous
Ext.namespace('sitools.component.forms.multiParam');
218 9 Anonymous
219 9 Anonymous
sitools.component.forms.multiParam.DateBeginEnd = Ext.extend(sitools.component.forms.multiParam.abstractForm, {
220 9 Anonymous
    height : 250,
221 9 Anonymous
    id : 'sitools.component.forms.definitionId',
222 9 Anonymous
    initComponent : function () {
223 9 Anonymous
        this.winPropComponent.specificHeight = 350;
224 9 Anonymous
        this.winPropComponent.specificWidth = 400;
225 9 Anonymous
        sitools.component.forms.multiParam.DateBeginEnd.superclass.initComponent.call(this);
226 9 Anonymous
     
227 9 Anonymous
228 9 Anonymous
        
229 9 Anonymous
    /*
230 9 Anonymous
     * Build all the Columns mapping for the configuration, 
231 9 Anonymous
     * this object needs three columns
232 9 Anonymous
     */
233 9 Anonymous
    var labels = ['DATE FROM', 'DATE TO'];
234 9 Anonymous
    for (var i = 1; i <= 2; i++) {
235 9 Anonymous
		this['mapParam' + i] = new Ext.form.ComboBox({
236 9 Anonymous
		    fieldLabel : labels[i - 1],
237 9 Anonymous
		    triggerAction : 'all',
238 9 Anonymous
		    name : "PARAM" + i,
239 9 Anonymous
		    specificType : "mapParam", 
240 9 Anonymous
		    columnIndex : i, 
241 9 Anonymous
		    lazyRender : true,
242 9 Anonymous
		    mode : 'local',
243 9 Anonymous
		    store : this.storeColumn,
244 9 Anonymous
		    valueField : 'columnAlias',
245 9 Anonymous
		    displayField : 'header',
246 9 Anonymous
		    anchor : '100%', 
247 9 Anonymous
		    allowBlank : false 
248 9 Anonymous
		    
249 9 Anonymous
		}); 
250 9 Anonymous
		
251 9 Anonymous
		if (this.action == "modify") {
252 9 Anonymous
			Ext.apply(this['mapParam' + i], {
253 9 Anonymous
				value : this.selectedRecord.data.code[i - 1]
254 9 Anonymous
			});
255 9 Anonymous
		}
256 9 Anonymous
       
257 9 Anonymous
		this.insert(i, this['mapParam' + i]);
258 9 Anonymous
    }
259 9 Anonymous
260 9 Anonymous
    this.componentDefaultValue1 = new Ext.form.DateField({
261 9 Anonymous
        fieldLabel : i18n.get('label.defaultValue') + ' (DATE FROM)',
262 9 Anonymous
        name : 'componentDefaultValue1',
263 9 Anonymous
        anchor : '100%',
264 9 Anonymous
        format : DEFAULT_DATE_FORMAT
265 9 Anonymous
    });
266 9 Anonymous
    this.componentDefaultValue2 = new Ext.form.DateField({
267 9 Anonymous
        fieldLabel : i18n.get('label.defaultValue') + ' (DATE TO)',
268 9 Anonymous
        name : 'componentDefaultValue2',
269 9 Anonymous
        anchor : '100%',
270 9 Anonymous
        format : DEFAULT_DATE_FORMAT
271 9 Anonymous
    });
272 9 Anonymous
273 9 Anonymous
    this.add(this.componentDefaultValue1);
274 9 Anonymous
    this.add(this.componentDefaultValue2);
275 9 Anonymous
276 9 Anonymous
    
277 9 Anonymous
},
278 9 Anonymous
onRender : function () {
279 9 Anonymous
    sitools.component.forms.multiParam.DateBeginEnd.superclass.onRender.apply(this, arguments);
280 9 Anonymous
    if (this.action == 'modify') {
281 9 Anonymous
        if (!Ext.isEmpty(this.selectedRecord.data.defaultValues)) {
282 9 Anonymous
            if (Ext.isString(this.selectedRecord.data.defaultValues[0])) {
283 9 Anonymous
                this.componentDefaultValue1.setValue(this.selectedRecord.data.defaultValues[0].split('T')[0]);
284 9 Anonymous
            }
285 9 Anonymous
            else {
286 9 Anonymous
                this.componentDefaultValue1.setValue(this.selectedRecord.data.defaultValues[0].split('T')[0]);
287 9 Anonymous
            }
288 9 Anonymous
            if (Ext.isString(this.selectedRecord.data.defaultValues[1])) {
289 9 Anonymous
                this.componentDefaultValue2.setValue(this.selectedRecord.data.defaultValues[1].split('T')[0]);
290 9 Anonymous
            }
291 9 Anonymous
            else {
292 9 Anonymous
                this.componentDefaultValue2.setValue(this.selectedRecord.data.defaultValues[1].split('T')[0]);
293 9 Anonymous
            }
294 9 Anonymous
        }
295 9 Anonymous
    }
296 9 Anonymous
},
297 9 Anonymous
afterRender : function () {
298 9 Anonymous
    sitools.component.forms.multiParam.DateBeginEnd.superclass.afterRender.apply(this, arguments);
299 9 Anonymous
    if (this.action == 'modify') {
300 9 Anonymous
		if (!Ext.isEmpty(this.selectedRecord.data.defaultValues)) {
301 9 Anonymous
            this.componentDefaultValue1.setValue(this.selectedRecord.data.defaultValues[0]);
302 9 Anonymous
            this.componentDefaultValue2.setValue(this.selectedRecord.data.defaultValues[1]);
303 9 Anonymous
            
304 9 Anonymous
        }
305 9 Anonymous
    }
306 9 Anonymous
   
307 9 Anonymous
},
308 9 Anonymous
309 9 Anonymous
_onValidate : function (action, gridFormComponents) {
310 9 Anonymous
    var f = this.getForm();
311 9 Anonymous
    if (!f.isValid()) {
312 9 Anonymous
    	Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
313 9 Anonymous
        return false;
314 9 Anonymous
    }
315 9 Anonymous
    var defaultValue1 = Ext.isEmpty(f.findField('componentDefaultValue1')) ? "" : f.findField('componentDefaultValue1').getValue();
316 9 Anonymous
    var defaultValue2 = Ext.isEmpty(f.findField('componentDefaultValue2')) ? "" : f.findField('componentDefaultValue2').getValue();
317 9 Anonymous
318 9 Anonymous
	var columnObjects = this.find('specificType', 'mapParam');
319 9 Anonymous
	var code = [];
320 9 Anonymous
	Ext.each(columnObjects, function (columnObject) {
321 9 Anonymous
		code.push(columnObject.getValue());
322 9 Anonymous
	});
323 9 Anonymous
  
324 9 Anonymous
    if (action == 'modify') {
325 9 Anonymous
        var rec = gridFormComponents.getSelectionModel().getSelected();
326 9 Anonymous
        
327 9 Anonymous
        var labelParam1 = Ext.isEmpty(f.findField('LABEL_PARAM1')) ? "" : f.findField('LABEL_PARAM1').getValue();
328 9 Anonymous
        var css = Ext.isEmpty(f.findField('CSS')) ? "" : f.findField('CSS').getValue();
329 9 Anonymous
        
330 9 Anonymous
        rec.set('label', labelParam1);
331 9 Anonymous
        rec.set('code', code);
332 9 Anonymous
        rec.set('css', css);
333 9 Anonymous
        rec.set('componentDefaultHeight', f.findField('componentDefaultHeight').getValue());
334 9 Anonymous
        rec.set('componentDefaultWidth', f.findField('componentDefaultWidth').getValue());
335 9 Anonymous
336 9 Anonymous
        rec.set('defaultValues', [ defaultValue1, defaultValue2]);
337 9 Anonymous
    } else {
338 9 Anonymous
        var formComponentsStore = gridFormComponents.getStore();
339 9 Anonymous
        
340 9 Anonymous
        // Génération de l'id
341 9 Anonymous
        var lastId = 0;
342 9 Anonymous
        var greatY = 0;
343 9 Anonymous
        formComponentsStore.each(function (component) {
344 9 Anonymous
            if (component.data.id > lastId) {
345 9 Anonymous
                lastId = parseInt(component.data.id, 10);
346 9 Anonymous
            }
347 9 Anonymous
            if (component.data.ypos > greatY) {
348 9 Anonymous
                greatY = parseInt(component.data.ypos, 10)  + parseInt(component.data.height, 10);
349 9 Anonymous
            }
350 9 Anonymous
351 9 Anonymous
        });
352 9 Anonymous
        var componentId = lastId + 1;
353 9 Anonymous
        componentId = componentId.toString();
354 9 Anonymous
        var componentYpos = greatY + 10;
355 9 Anonymous
        
356 9 Anonymous
        formComponentsStore.add(new Ext.data.Record({
357 9 Anonymous
            label : f.findField('LABEL_PARAM1').getValue(),
358 9 Anonymous
            type : this.ctype,
359 9 Anonymous
            code : code,
360 9 Anonymous
            width : f.findField('componentDefaultWidth').getValue(),
361 9 Anonymous
            height : f.findField('componentDefaultHeight').getValue(),
362 9 Anonymous
            id : componentId,
363 9 Anonymous
            ypos : componentYpos,
364 9 Anonymous
            css : f.findField('CSS').getValue(),
365 9 Anonymous
            jsAdminObject : this.jsAdminObject,
366 9 Anonymous
            jsUserObject : this.jsUserObject,
367 9 Anonymous
            defaultValues : [ defaultValue1, defaultValue2 ]
368 9 Anonymous
        }));
369 9 Anonymous
    }
370 9 Anonymous
    return true;
371 9 Anonymous
}
372 9 Anonymous
373 9 Anonymous
});
374 9 Anonymous
375 9 Anonymous
</code></pre>
376 9 Anonymous
377 9 Anonymous
378 9 Anonymous
partie CLIENT : 
379 9 Anonymous
380 9 Anonymous
<pre><code class="javascript">
381 9 Anonymous
/***************************************
382 9 Anonymous
* Copyright 2011 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
383 9 Anonymous
* 
384 9 Anonymous
* This file is part of SITools2.
385 9 Anonymous
* 
386 9 Anonymous
* SITools2 is free software: you can redistribute it and/or modify
387 9 Anonymous
* it under the terms of the GNU General Public License as published by
388 9 Anonymous
* the Free Software Foundation, either version 3 of the License, or
389 9 Anonymous
* (at your option) any later version.
390 9 Anonymous
* 
391 9 Anonymous
* SITools2 is distributed in the hope that it will be useful,
392 9 Anonymous
* but WITHOUT ANY WARRANTY; without even the implied warranty of
393 9 Anonymous
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
394 9 Anonymous
* GNU General Public License for more details.
395 9 Anonymous
* 
396 9 Anonymous
* You should have received a copy of the GNU General Public License
397 9 Anonymous
* along with SITools2.  If not, see <http://www.gnu.org/licenses/>.
398 9 Anonymous
***************************************/
399 9 Anonymous
/*global Ext, sitools*/
400 9 Anonymous
Ext.ns('sitools.component.users.SubSelectionParameters.SingleSelection');
401 9 Anonymous
402 9 Anonymous
sitools.component.users.SubSelectionParameters.SingleSelection.DateBeginEnd = Ext.extend(Ext.Container, {
403 9 Anonymous
404 9 Anonymous
    initComponent : function () {
405 9 Anonymous
        this.fieldFrom = new Ext.form.DateField({
406 9 Anonymous
            allowBlank : true,
407 9 Anonymous
            format : DEFAULT_DATE_FORMAT, 
408 9 Anonymous
            width : 165,
409 9 Anonymous
            height : this.height,
410 9 Anonymous
            value : new Date(this.defaultValues[0]).format(DEFAULT_DATE_FORMAT)
411 9 Anonymous
        });
412 9 Anonymous
        this.fieldTo = new Ext.form.DateField({
413 9 Anonymous
            allowBlank : true,
414 9 Anonymous
            format : DEFAULT_DATE_FORMAT, 
415 9 Anonymous
            width : 165,
416 9 Anonymous
            height : this.height,
417 9 Anonymous
            value : new Date(this.defaultValues[1]).format(DEFAULT_DATE_FORMAT)
418 9 Anonymous
        });
419 9 Anonymous
        Ext.apply(this, {
420 9 Anonymous
            layout : 'table',
421 9 Anonymous
            columns : 2,     /* 3*/
422 9 Anonymous
            fieldLabel : this.label,
423 9 Anonymous
            stype : "sitoolsFormContainer",
424 9 Anonymous
425 9 Anonymous
            items : [ new Ext.Container({
426 9 Anonymous
            	border : false,
427 9 Anonymous
            	html : this.label + " : ", 
428 9 Anonymous
            	width : "150"
429 9 Anonymous
            }), this.fieldFrom, new Ext.Container({
430 9 Anonymous
                border : false,
431 9 Anonymous
                html : '&nbsp;'
432 9 Anonymous
            }), this.fieldTo ]
433 9 Anonymous
        });
434 9 Anonymous
        sitools.component.users.SubSelectionParameters.SingleSelection.DateBeginEnd.superclass.initComponent.apply(
435 9 Anonymous
                this, arguments);
436 9 Anonymous
    },
437 9 Anonymous
438 9 Anonymous
    /**
439 9 Anonymous
     * The code of the parameter to notify changed event.
440 9 Anonymous
     */
441 9 Anonymous
    code : null,
442 9 Anonymous
443 9 Anonymous
    /**
444 9 Anonymous
     * The left bound of the period.
445 9 Anonymous
     */
446 9 Anonymous
    fieldFrom : null,
447 9 Anonymous
448 9 Anonymous
    /**
449 9 Anonymous
     * The right bound of the period.
450 9 Anonymous
     */
451 9 Anonymous
    fieldTo : null,
452 9 Anonymous
453 9 Anonymous
    notifyValueSelected : function () {
454 9 Anonymous
        this.parent.notifyValueChanged(this.code);
455 9 Anonymous
    },
456 9 Anonymous
457 9 Anonymous
    isValueDefined : function () {
458 9 Anonymous
        if (this.fieldFrom.getValue() && this.fieldTo.getValue()) {
459 9 Anonymous
            return true;
460 9 Anonymous
        } else {
461 9 Anonymous
            return false;
462 9 Anonymous
        }
463 9 Anonymous
    },
464 9 Anonymous
465 9 Anonymous
    getSelectedValue : function () {
466 9 Anonymous
        return {
467 9 Anonymous
            from : this.fieldFrom.getValue(),
468 9 Anonymous
            to : this.fieldTo.getValue()
469 9 Anonymous
        };
470 9 Anonymous
    },
471 9 Anonymous
    
472 9 Anonymous
    getParameterValue : function () {
473 9 Anonymous
        var value = this.getSelectedValue();
474 9 Anonymous
        if (Ext.isEmpty(value) || Ext.isEmpty(value.from) || Ext.isEmpty(value.to)) {
475 9 Anonymous
            return null;
476 9 Anonymous
        }
477 9 Anonymous
        return this.type + "|" + this.code + "|" + value.from.format('Y-m-d') + "|" + value.to.format('Y-m-d') ;
478 9 Anonymous
    }
479 9 Anonymous
});
480 9 Anonymous
</code></pre>
481 9 Anonymous
482 9 Anonymous
483 9 Anonymous
Code JAVA à inclure dans *workspace/fr.cnes.sitools.extensions/src/fr/cnes/sitools/filter* et référencer la classe dans le fichier *fr.cnes.sitools.filter.FilterHelper*
484 9 Anonymous
485 9 Anonymous
<pre><code class="java">
486 10 Anonymous
/*******************************************************************************
487 10 Anonymous
 * Copyright 2011 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
488 10 Anonymous
 * 
489 10 Anonymous
 * This file is part of SITools2.
490 10 Anonymous
 * 
491 10 Anonymous
 * SITools2 is free software: you can redistribute it and/or modify
492 10 Anonymous
 * it under the terms of the GNU General Public License as published by
493 10 Anonymous
 * the Free Software Foundation, either version 3 of the License, or
494 10 Anonymous
 * (at your option) any later version.
495 10 Anonymous
 * 
496 10 Anonymous
 * SITools2 is distributed in the hope that it will be useful,
497 10 Anonymous
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
498 10 Anonymous
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
499 10 Anonymous
 * GNU General Public License for more details.
500 10 Anonymous
 * 
501 10 Anonymous
 * You should have received a copy of the GNU General Public License
502 10 Anonymous
 * along with SITools2.  If not, see <http://www.gnu.org/licenses/>.
503 10 Anonymous
 ******************************************************************************/
504 10 Anonymous
package fr.cnes.sitools.filter.basic;
505 9 Anonymous
506 10 Anonymous
import java.util.Arrays;
507 10 Anonymous
import java.util.HashMap;
508 10 Anonymous
import java.util.List;
509 10 Anonymous
import java.util.Set;
510 10 Anonymous
511 10 Anonymous
import org.restlet.Request;
512 10 Anonymous
import org.restlet.data.Form;
513 10 Anonymous
import org.restlet.ext.wadl.ParameterInfo;
514 10 Anonymous
import org.restlet.ext.wadl.ParameterStyle;
515 10 Anonymous
516 10 Anonymous
import fr.cnes.sitools.common.validator.ConstraintViolation;
517 10 Anonymous
import fr.cnes.sitools.common.validator.Validator;
518 10 Anonymous
import fr.cnes.sitools.dataset.DataSetApplication;
519 10 Anonymous
import fr.cnes.sitools.dataset.filter.business.AbstractFilter;
520 10 Anonymous
import fr.cnes.sitools.dataset.model.Column;
521 10 Anonymous
import fr.cnes.sitools.dataset.model.DataSet;
522 10 Anonymous
import fr.cnes.sitools.dataset.model.Operator;
523 10 Anonymous
import fr.cnes.sitools.dataset.model.Predicat;
524 10 Anonymous
import fr.cnes.sitools.util.SQLUtils;
525 10 Anonymous
526 10 Anonymous
/**
527 10 Anonymous
 * Filter defined for Date Between Component
528 10 Anonymous
 * 
529 10 Anonymous
 * 
530 10 Anonymous
 * @author d.arpin
531 10 Anonymous
 * <a href="https://sourceforge.net/tracker/?func=detail&atid=2158259&aid=3411383&group_id=531341">[3411383]</a><br/>
532 10 Anonymous
 * 2011/09/19 d.arpin {add quotes arround date Value}
533 10 Anonymous
 */
534 10 Anonymous
public final class DateBeginEndFilter extends AbstractFilter {
535 10 Anonymous
  /**
536 10 Anonymous
   * The index of TYPE
537 10 Anonymous
   */
538 10 Anonymous
  private static final int TYPE = 0;
539 10 Anonymous
  /**
540 10 Anonymous
   * The index of COLUMN
541 10 Anonymous
   */
542 10 Anonymous
  private static final int COLUMN = 1;
543 10 Anonymous
  /**
544 10 Anonymous
   * The index of Values
545 10 Anonymous
   */
546 10 Anonymous
  private static final int VALUES = 2;
547 10 Anonymous
548 10 Anonymous
  /** The TEMPLATE_PARAM */
549 10 Anonymous
  private static final String TEMPLATE_PARAM = "p[#]";
550 10 Anonymous
  /**
551 10 Anonymous
   * the values from to
552 10 Anonymous
   */
553 10 Anonymous
  private String[] values;
554 10 Anonymous
555 10 Anonymous
  /**
556 10 Anonymous
   * The list of component that uses this filter
557 10 Anonymous
   */
558 10 Anonymous
  private enum TYPE_COMPONENT {
559 10 Anonymous
    /** DefaultType */
560 10 Anonymous
    DATE_BEGIN_END
561 10 Anonymous
  }
562 10 Anonymous
563 10 Anonymous
  /**
564 10 Anonymous
   * Default constructor
565 10 Anonymous
   */
566 10 Anonymous
  public DateBeginEndFilter() {
567 10 Anonymous
568 10 Anonymous
    super();
569 10 Anonymous
    this.setName("DateBeginEndFilter");
570 10 Anonymous
    this.setDescription("Required when using Date Between Components between 2 columns");
571 10 Anonymous
572 10 Anonymous
    this.setAuthor("HUSSON@IAS");
573 10 Anonymous
    this.setClassAuthor("HUSSON@IAS");
574 10 Anonymous
    this.setClassOwner("IAS");
575 10 Anonymous
    this.setVersion("0.1");
576 10 Anonymous
    this.setDefaultFilter(true);
577 10 Anonymous
578 10 Anonymous
    HashMap<String, ParameterInfo> rpd = new HashMap<String, ParameterInfo>();
579 10 Anonymous
580 10 Anonymous
    ParameterInfo paramInfo;
581 10 Anonymous
    paramInfo = new ParameterInfo("p[#]", false, "xs:string", ParameterStyle.QUERY,
582 10 Anonymous
    "DATE_BEGIN_END|columnFrom,columnTo|valueFrom|valueTo");
583 10 Anonymous
    rpd.put("0", paramInfo);
584 10 Anonymous
    this.setRequestParamsDescription(rpd);
585 10 Anonymous
    //
586 10 Anonymous
587 10 Anonymous
  }
588 10 Anonymous
589 10 Anonymous
  @Override
590 10 Anonymous
  public List<Predicat> createPredicats(Request request, List<Predicat> predicats) throws Exception {
591 10 Anonymous
    // Get the dataset
592 10 Anonymous
    DataSetApplication dsApplication = null;
593 10 Anonymous
    DataSet ds = null;
594 10 Anonymous
595 10 Anonymous
    Form params = request.getResourceRef().getQueryAsForm();
596 10 Anonymous
    boolean filterExists = true;
597 10 Anonymous
    int i = 0;
598 10 Anonymous
    // Build predicat for filters param
599 10 Anonymous
    while (filterExists) {
600 10 Anonymous
      String index = TEMPLATE_PARAM.replace("#", Integer.toString(i++));
601 10 Anonymous
      String formParam = params.getFirstValue(index);
602 10 Anonymous
      if (formParam != null) {
603 10 Anonymous
        String[] parameters = formParam.split("\\|");
604 10 Anonymous
        TYPE_COMPONENT[] types = TYPE_COMPONENT.values();
605 10 Anonymous
        Boolean trouve = false;
606 10 Anonymous
        for (TYPE_COMPONENT typeCmp : types) {
607 10 Anonymous
          if (typeCmp.name().equals(parameters[TYPE])) {
608 10 Anonymous
            trouve = true;
609 10 Anonymous
          }
610 10 Anonymous
        }
611 10 Anonymous
        if (trouve) {
612 10 Anonymous
          if (dsApplication == null) {
613 10 Anonymous
            dsApplication = (DataSetApplication) getContext().getAttributes().get("DataSetApplication");
614 10 Anonymous
            ds = dsApplication.getDataSet();
615 10 Anonymous
          }
616 10 Anonymous
          String columnfrom = null;
617 10 Anonymous
          String columnto = null;
618 10 Anonymous
          if (parameters.length >= VALUES) {
619 10 Anonymous
            columnfrom = parameters[COLUMN].split(",")[0];
620 10 Anonymous
            columnto = parameters[COLUMN].split(",")[1];
621 10 Anonymous
622 10 Anonymous
            Column colfrom = ds.findByColumnAlias(columnfrom);
623 10 Anonymous
            Column colto = ds.findByColumnAlias(columnto);
624 10 Anonymous
625 10 Anonymous
            if (colfrom != null && colfrom.getFilter() != null && colfrom.getFilter() && checkValues(parameters) && colto != null && colto.getFilter() != null && colto.getFilter()) {
626 10 Anonymous
              // escape the values to avoid SQL injection
627 10 Anonymous
              String valuefrom = "'" + SQLUtils.escapeString(values[0]) + "'";
628 10 Anonymous
              String valueto = "'" + SQLUtils.escapeString(values[1]) + "'";
629 10 Anonymous
630 10 Anonymous
              Predicat predicat = new Predicat();
631 10 Anonymous
              predicat.setLeftAttribute(colfrom);
632 10 Anonymous
              predicat.setNbOpenedParanthesis(1);
633 10 Anonymous
              predicat.setNbClosedParanthesis(0);
634 10 Anonymous
              predicat.setCompareOperator(Operator.GTE.value());
635 10 Anonymous
              predicat.setRightValue(valuefrom);
636 10 Anonymous
              predicats.add(predicat);
637 10 Anonymous
              predicat = new Predicat();
638 10 Anonymous
              predicat.setLeftAttribute(colto);
639 10 Anonymous
              predicat.setNbOpenedParanthesis(0);
640 10 Anonymous
              predicat.setNbClosedParanthesis(1);
641 10 Anonymous
              predicat.setCompareOperator(Operator.LTE.value());
642 10 Anonymous
              predicat.setRightValue(valueto);
643 10 Anonymous
              predicats.add(predicat);
644 10 Anonymous
            }
645 10 Anonymous
646 10 Anonymous
          }
647 10 Anonymous
        }
648 10 Anonymous
      }
649 10 Anonymous
650 10 Anonymous
      else {
651 10 Anonymous
        filterExists = false;
652 10 Anonymous
      }
653 10 Anonymous
    }
654 10 Anonymous
655 10 Anonymous
    return predicats;
656 10 Anonymous
  }
657 10 Anonymous
658 10 Anonymous
  /**
659 10 Anonymous
   * Check values of the form
660 10 Anonymous
   * 
661 10 Anonymous
   * @param parameters
662 10 Anonymous
   *          the parameters of the filter
663 10 Anonymous
   * @return true if values agree
664 10 Anonymous
   */
665 10 Anonymous
  private boolean checkValues(String[] parameters) {
666 10 Anonymous
    values = Arrays.copyOfRange(parameters, VALUES, parameters.length);
667 10 Anonymous
    if (values.length == 2) {
668 10 Anonymous
      return true;
669 10 Anonymous
    }
670 10 Anonymous
    return false;
671 10 Anonymous
  }
672 10 Anonymous
673 10 Anonymous
  /**
674 10 Anonymous
   * Gets the validator for this Filter
675 10 Anonymous
   * 
676 10 Anonymous
   * @return the validator for the filter
677 10 Anonymous
   */
678 10 Anonymous
  @Override
679 10 Anonymous
  public Validator<AbstractFilter> getValidator() {
680 10 Anonymous
    return new Validator<AbstractFilter>() {
681 10 Anonymous
      @Override
682 10 Anonymous
      public Set<ConstraintViolation> validate(AbstractFilter item) {
683 10 Anonymous
        return null;
684 10 Anonymous
      }
685 10 Anonymous
    };
686 10 Anonymous
  }
687 10 Anonymous
688 10 Anonymous
}
689 9 Anonymous
</code></pre>