Project

General

Profile

Revision d59e7ee5

Added by shye0000 about 9 years ago

some modif

View differences:

Asynchronous_Download_java_sitools2/PublicOrderResource.java
1
 /*******************************************************************************
2
 * Copyright 2010-2014 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
3
 *
4
 * This file is part of SITools2.
5
 *
6
 * SITools2 is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * SITools2 is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with SITools2.  If not, see <http://www.gnu.org/licenses/>.
18
 ******************************************************************************/
19
package fr.cnes.sitools.resources.order;
20

  
21
import java.io.IOException;
22
import java.util.ArrayList;
23
import java.util.Iterator;
24
import java.util.List;
25
import java.util.logging.Level;
26
import java.util.Map;
27
import java.util.HashMap;
28
import java.io.UnsupportedEncodingException;
29
import java.net.URLEncoder;
30

  
31
import org.restlet.data.Reference;
32
import org.restlet.data.Status;
33
import org.restlet.representation.Representation;
34
import org.restlet.resource.ResourceException;
35
import org.restlet.security.User;
36

  
37
import fr.cnes.sitools.common.exception.SitoolsException;
38
import fr.cnes.sitools.dataset.database.DatabaseRequest;
39
import fr.cnes.sitools.datasource.jdbc.model.AttributeValue;
40
import fr.cnes.sitools.datasource.jdbc.model.Record;
41
import fr.cnes.sitools.plugins.resources.model.ResourceModel;
42
import fr.cnes.sitools.plugins.resources.model.ResourceParameter;
43
import fr.cnes.sitools.resources.order.utils.ListReferencesAPI;
44
import fr.cnes.sitools.resources.order.utils.OrderAPI;
45
import fr.cnes.sitools.resources.order.utils.OrderResourceUtils;
46
import fr.cnes.sitools.server.Consts;
47
import fr.cnes.sitools.util.RIAPUtils;
48
import fr.cnes.sitools.order.model.Order;
49
import org.restlet.Context;
50
import fr.cnes.sitools.tasks.business.Task;
51
import fr.cnes.sitools.mail.model.Mail;
52
import org.restlet.Request;
53
import org.restlet.data.Method;
54
import org.restlet.representation.ObjectRepresentation;
55
import fr.cnes.sitools.util.TemplateUtils;
56
import fr.cnes.sitools.util.Util;
57

  
58

  
59
/**
60
 * Default OrderResource implementation.
61
 * <p>
62
 * The parameter colUrl is used to specify a column containing the list of URLs of the files to order. Each file is then
63
 * either copied or Zipped to the userstorage of the user.
64
 * </p>
65
 * 
66
 * 
67
 * @author m.gond
68
 */
69
public class PublicOrderResource extends AbstractDatasetOrderResource {
70
  /** Maximum number of file to download authorized, default to -1 => no limit */
71
  private int nbMaxDownload = -1;
72
  private fr.cnes.sitools.security.model.User userDetails; 
73
  /*
74
   * (non-Javadoc)
75
   *
76
   * @see fr.cnes.sitools.resources.order.AbstractOrderResource#checkUser()
77
   */
78
  @Override
79
  public void checkUser() {
80
    User user = getClientInfo().getUser();
81
    if (user == null) {
82
      userDetails=null;
83
    }
84
    else{
85
      try {
86
        userDetails = this.getUserDetails(user.getIdentifier(), getContext());
87
      }
88
      catch (SitoolsException e) {
89
        userDetails=null;
90
      }
91

  
92
    }
93

  
94

  
95
  }
96

  
97
  public void notifyAdminEnd() throws SitoolsException {
98
    try {
99
      sendMail(order, getContext(), userDetails, task);
100
    }
101
    catch (SitoolsException e) {
102
      // ne rien faire si le mail n'est pas parti
103
      OrderAPI.createEvent(order, getContext(), "MAIL_NOT_SEND_TO_USER");
104
    }
105
  }
106

  
107
  protected void sendMail(Order order, Context context, fr.cnes.sitools.security.model.User user, Task task)
108
	throws SitoolsException{
109
    List<String> toList = new ArrayList<String>();
110
if(user!=null){	
111
    String userAdd = user.getEmail();
112
    if (userAdd != null && !userAdd.equals("")) {
113
      // System.out.println("EMAIL ADDRESS = " + userAdd);
114
      toList.add(userAdd);
115

  
116
      Mail mailToUser = new Mail();
117
      mailToUser.setToList(toList);
118

  
119
      // TODO EVOL : email subject should be a parameter
120
      mailToUser.setSubject(getMailSubject());
121

  
122
      // default body
123
      mailToUser.setBody(getMailBody(mailToUser));
124

  
125
      org.restlet.Response sendMailResponse = null;
126
      try {
127
        // riap request to MailAdministration application
128
        Request request = new Request(Method.POST, RIAPUtils.getRiapBase()
129
            + settings.getString(Consts.APP_MAIL_ADMIN_URL), new ObjectRepresentation<Mail>(mailToUser));
130

  
131
        sendMailResponse = getContext().getClientDispatcher().handle(request);
132
      }
133
      catch (Exception e) {
134
        getLogger().warning("SERVER ERROR SENDING EMAIL TO USER");
135
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
136
      }
137
      if (sendMailResponse.getStatus().isError()) {
138
        throw new SitoolsException("SERVER ERROR SENDING EMAIL TO USER");
139
      }
140

  
141
      // OK
142
    }
143
    else {
144
      throw new SitoolsException("NO EMAIL ADDRESS DEFINED");
145
    }
146
}
147
else{
148
  ResourceModel resourceModel = getModel();
149
  ResourceParameter email = resourceModel.getParameterByName("Email");
150
  String userAdd = this.getRequest().getResourceRef().getQueryAsForm().getFirstValue("Email");
151
 //String userAdd = email.getValue();
152
  getContext().getLogger().info("******************* UserEmail : "+userAdd);
153
  if (userAdd != null && !userAdd.equals("")) {
154
    toList.add(userAdd);
155
    Mail mailToPublic = new Mail();
156
    mailToPublic.setToList(toList);
157
    mailToPublic.setSubject(getMailSubject());
158
    mailToPublic.setBody(getMailBodyPublic(mailToPublic));
159
    org.restlet.Response sendMailResponse = null;
160
      try {
161
        Request request = new Request(Method.POST, RIAPUtils.getRiapBase()
162
            + settings.getString(Consts.APP_MAIL_ADMIN_URL), new ObjectRepresentation<Mail>(mailToPublic));
163

  
164
        sendMailResponse = getContext().getClientDispatcher().handle(request);
165
      }
166
      catch (Exception e) {
167
        getLogger().warning("SERVER ERROR SENDING EMAIL TO PUBLIC DOWNLOADER");
168
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
169
      }
170
      if (sendMailResponse.getStatus().isError()) {
171
        throw new SitoolsException("SERVER ERROR SENDING EMAIL TO PUBLIC DOWNLOADER");
172
      }
173
  }
174
  else{
175
    throw new SitoolsException("NO EMAIL ADDRESS DEFINED");
176
  }
177
}
178

  
179
  }
180

  
181

  
182
protected String getMailBodyPublic(Mail mailToPublic) {
183
    // default body
184
    String orderNameEncoded = order.getDescription();
185
    String fileNameEncoded = order.getDescription();
186
	
187
    try{
188
	orderNameEncoded = URLEncoder.encode(order.getDescription(),"UTF-8");
189
    } catch (UnsupportedEncodingException e){
190
        e.printStackTrace();
191
    }
192
    try{
193
        fileNameEncoded = URLEncoder.encode(orderNameEncoded,"UTF-8");
194
    } catch (UnsupportedEncodingException e){
195
        e.printStackTrace();
196
    }
197
    String mailBody = "Dear visiter"+":<br/><br/>Your command is complete. <br/>" + "File Name : "
198
        + order.getDescription() + "<br/>"
199
        +"Now you can click the link below to download it:<br/><a href='http://idoc-picard.ias.u-psud.fr:8182/sitools/userstorage/public/files/resources_orders/"
200
	+orderNameEncoded+"/"+fileNameEncoded+".zip"
201
        +"'>http://idoc-picard.ias.u-psud.fr:8182/sitools/userstorage/public/files/resources_orders/"
202
	+orderNameEncoded+"/"+fileNameEncoded+".zip</a>"
203
	+"<br/><br/>Admin<br/><a href='http://idoc-picard.ias.u-psud.fr'>PICARD ARCHIVE</a>";
204

  
205
    // use a freemarker template for email body with Mail object
206
    String templatePath = settings.getRootDirectory() + settings.getString(Consts.TEMPLATE_DIR)
207
        + "mail.order.complete.ftl";
208

  
209
    Map<String, Object> root = new HashMap<String, Object>();
210
    root.put("mail", mailToPublic);
211
    root.put("order", order);
212
    String adminmail = settings.getString("Starter.StatusService.CONTACT_MAIL");
213
    root.put("adminmail", adminmail);
214

  
215
    TemplateUtils.describeObjectClassesForTemplate(templatePath, root);
216

  
217
    root.put("context", getContext());
218

  
219
    String body = TemplateUtils.toString(templatePath, root);
220
    if (Util.isNotEmpty(body)) {
221
      return body;
222
    }
223
    else {
224
      return mailBody;
225
    }
226
  }
227

  
228

  
229

  
230
  @Override
231
  public ListReferencesAPI listFilesToOrder(DatabaseRequest dbRequest) throws SitoolsException {
232
    task.setCustomStatus("Creating list of files to order");
233
    ResourceModel resourceModel = getModel();
234
    ResourceParameter nbMaxDownloadParam = resourceModel.getParameterByName("too_many_selected_threshold");
235
    if (nbMaxDownloadParam != null && !"".equals(nbMaxDownloadParam)) {
236
      try {
237
        nbMaxDownload = Integer.parseInt(nbMaxDownloadParam.getValue());
238
      }
239
      catch (NumberFormatException e) {
240
        nbMaxDownload = -1;
241
      }
242
    }
243
    
244
    if (nbMaxDownload != -1 && nbMaxDownload < dbRequest.getCount()) {
245
      ResourceParameter errorTextParam = resourceModel.getParameterByName("too_many_selected_threshold_text");
246
      String errorText = (errorTextParam != null && !"".equals(errorTextParam.getValue())) ? errorTextParam.getValue()
247
          : "Too many file selected";
248
      throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, errorText);
249
    }
250

  
251
    ResourceParameter colUrl = resourceModel.getParameterByName("colUrl");
252
    if (colUrl.getValue() == null || colUrl.getValue().equals("")) {
253
      throw new SitoolsException("NO COLUMN DEFINED FOR ORDER");
254
    }
255

  
256
    ListReferencesAPI list = new ListReferencesAPI(settings.getPublicHostDomain() + settings.getString(Consts.APP_URL));
257
    while (dbRequest.nextResult()) {
258
      Record rec = dbRequest.getRecord();
259
      AttributeValue attributeValue = OrderResourceUtils.getInParam(colUrl, rec);
260

  
261
      if (attributeValue != null && attributeValue.getValue() != null) {
262
        // get the file path
263
        String filePath = (String) attributeValue.getValue();
264
        String urlAttach = settings.getString(Consts.APP_DATASTORAGE_URL);
265
        // if it contains "/datastorage" get rid of everything before
266
        if (filePath.contains(urlAttach)) {
267
          filePath = filePath.substring(filePath.lastIndexOf(urlAttach));
268
        }
269
        if (filePath.startsWith("http://")) {
270
          list.addReferenceSource(new Reference(filePath));
271
        }
272
        else {
273
          list.addReferenceSource(new Reference(RIAPUtils.getRiapBase() + filePath));
274
        }
275

  
276
      }
277
    }
278
    return list;
279
  }
280

  
281
  @Override
282
  public Representation processOrder(ListReferencesAPI listReferences) throws SitoolsException {
283
    task.setCustomStatus("Order processing");
284
    OrderAPI.createEvent(order, getContext(), "PROCESSING ORDER");
285

  
286
    List<Reference> listOfFilesToOrder = listReferences.getReferencesSource();
287

  
288
    getContext().getLogger().info("******************* User : "+task.getUser());
289
    getContext().getLogger().info("******************* folder : "+settings.getString(Consts.USERSTORAGE_RESOURCE_ORDER_DIR) + folderName);
290
    Reference destRef = OrderResourceUtils.getUserAvailableFolderPath(task.getUser(),
291
        settings.getString(Consts.USERSTORAGE_RESOURCE_ORDER_DIR) + folderName, getContext());
292

  
293
    ResourceModel resourceModel = getModel();
294
    ResourceParameter zipParam = resourceModel.getParameterByName("zip");
295

  
296
    // zip is a USER_INPUT parameter, let's get it from the request
297
    // parameters
298
    String zipValue = this.getRequest().getResourceRef().getQueryAsForm().getFirstValue("zip");
299
    if (zipValue == null || zipValue.equals("") || (!"false".equals(zipValue) && !"true".equals(zipValue))) {
300
      zipValue = zipParam.getValue();
301
    }
302

  
303
    Boolean zip = Boolean.parseBoolean(zipValue);
304
    if (zip) {
305
      task.getLogger().log(Level.INFO, zipParam.getName().toUpperCase() + " in progress for user : " 
306
          + task.getUser().getIdentifier() + " -> ip :" + getClientInfo().getUpstreamAddress());
307
      
308
      task.getLogger().info("List of files ordered :");
309
      for (Reference r : listReferences.getReferencesSource()) {
310
        task.getLogger().info(" - " + r.getIdentifier().substring(16));
311
        r.getPath();
312
      }
313
      zip(listOfFilesToOrder, listReferences, destRef);
314
    }
315
    else {
316
      task.getLogger().log(Level.INFO, "FILE in progress for user : "
317
          + task.getUser().getIdentifier() + " -> ip :" + getClientInfo().getUpstreamAddress());
318
      task.getLogger().info("List of files ordered :");
319
      for (Reference r : listReferences.getReferencesSource()) {
320
        task.getLogger().info(" - " + r.getIdentifier().substring(16));
321
        r.getPath();
322
      }
323
      
324
      Reference ref;
325
      for (Iterator<Reference> iterator = listOfFilesToOrder.iterator(); iterator.hasNext();) {
326
        Reference sourceRef = iterator.next();
327
        task.getLogger().log(Level.WARNING, "{0}", sourceRef);
328
        try {
329
          ref = new Reference(destRef);
330
          ref.addSegment(sourceRef.getLastSegment());
331
          OrderResourceUtils.copyFile(sourceRef, ref, getRequest().getClientInfo(), getContext());
332
          listReferences.addReferenceDest(ref);
333
        }
334
        catch (SitoolsException e) {
335
          task.getLogger().log(Level.WARNING, "File not copied : " + sourceRef, e);
336
        }
337
      }
338
    }
339

  
340
    task.getLogger().log(Level.INFO, "Number of downloaded files : " + listOfFilesToOrder.size());
341
    
342
    // set the result in the task
343
    task.setUrlResult(settings.getString(Consts.APP_URL) + settings.getString(Consts.APP_ORDERS_USER_URL) + "/"
344
        + order.getId());
345

  
346
    try {
347
      // copy the indexFile to the destination reference
348
      String orderFileListName = fileName;
349
      if (orderFileListName == null || "".equals(orderFileListName)) {
350
        orderFileListName = OrderResourceUtils.FILE_LIST_PATTERN.replace("{orderName}", ds.getName());
351
        orderFileListName = orderFileListName.replace("{timestamp}", formatedDate);
352
      }
353
      else {
354
        orderFileListName += "_fileList";
355
      }
356
      destRef.addSegment(orderFileListName);
357
      destRef.setExtensions("txt");
358
      Reference urlUserIndex = listReferences.copyToUserStorage(destRef, getContext(), getClientInfo());
359

  
360
      // add it the order
361
      ArrayList<String> orderedResource = new ArrayList<String>();
362
      orderedResource.add(urlUserIndex.toString());
363
      order.setResourceCollection(orderedResource);
364
      order = OrderAPI.updateOrder(order, getContext());
365

  
366
    }
367
    catch (IOException e) {
368
      throw new SitoolsException("Error while creating the file index in the userstorage", e);
369
    }
370
    return null;
371

  
372
  }
373

  
374
  /**
375
   * Create the Zip from the listOfFilesToOrder
376
   * 
377
   * @param listOfFilesToOrder
378
   *          the list of files to order
379
   * @param listReferences
380
   *          the ListReferenceAPI to add some reference
381
   * @param destRef
382
   *          the destination reference
383
   * @throws SitoolsException
384
   *           if there is an error
385
   */
386
  private void zip(List<Reference> listOfFilesToOrder, ListReferencesAPI listReferences, Reference destRef)
387
    throws SitoolsException {
388

  
389
    String zipFileName = fileName;
390
    if (zipFileName == null || "".equals(zipFileName)) {
391
      zipFileName = OrderResourceUtils.ZIP_FILE_PATTERN.replace("{orderName}", ds.getName());
392
      zipFileName = zipFileName.replace("{timestamp}", formatedDate);
393
    }
394

  
395
    Reference zipRef = new Reference(RIAPUtils.getRiapBase() + settings.getString(Consts.APP_TMP_FOLDER_URL));
396
    zipRef.addSegment(zipFileName);
397
    zipRef.setExtensions("zip");
398

  
399
    // create an index and add it to the zip files
400
    Reference ref;
401
    Reference sourceRef;
402
    for (Iterator<Reference> iterator = listOfFilesToOrder.iterator(); iterator.hasNext();) {
403
      sourceRef = iterator.next();
404
      ref = new Reference(destRef);
405
      ref.addSegment(sourceRef.getLastSegment());
406
      listReferences.addReferenceDest(ref);
407
    }
408

  
409
    // copy the indexFile to the destination reference
410
    Reference destRefListFileInZip = new Reference(destRef);
411

  
412
    String orderFileListName = fileName;
413
    if (orderFileListName == null || "".equals(orderFileListName)) {
414
      orderFileListName = OrderResourceUtils.FILE_LIST_PATTERN.replace("{orderName}", ds.getName());
415
      orderFileListName = orderFileListName.replace("{timestamp}", formatedDate);
416
    }
417
    else {
418
      orderFileListName += "_fileList";
419
    }
420
    destRefListFileInZip.addSegment(orderFileListName);
421
    destRefListFileInZip.setExtensions("txt");
422
    try {
423
      listReferences.copyToUserStorage(destRefListFileInZip, getContext(), getClientInfo());
424
      listReferences.clearReferencesDest();
425
      listReferences.addReferenceSource(destRefListFileInZip);
426
    }
427
    catch (IOException e) {
428
      e.printStackTrace();
429
    }
430

  
431
    OrderResourceUtils.zipFiles(listOfFilesToOrder, settings.getTmpFolderUrl() + "/" + zipFileName + ".zip",
432
        getRequest().getClientInfo(), getContext());
433
    destRef.addSegment(zipRef.getLastSegment());
434
    OrderResourceUtils.copyFile(zipRef, destRef, getRequest().getClientInfo(), getContext());
435
    OrderResourceUtils.deleteFile(zipRef, getRequest().getClientInfo(), getContext());
436

  
437
    Reference destZipRef = new Reference(destRef);
438
    listReferences.addReferenceDest(destZipRef);
439

  
440
    destRef.setLastSegment("");
441
  }
442
}
Asynchronous_Download_java_sitools2/PublicOrderResourceFacade.java
1
 /*******************************************************************************
2
 * Copyright 2010-2014 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
3
 *
4
 * This file is part of SITools2.
5
 *
6
 * SITools2 is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * SITools2 is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with SITools2.  If not, see <http://www.gnu.org/licenses/>.
18
 ******************************************************************************/
19
package fr.cnes.sitools.resources.order;
20

  
21
import org.restlet.data.Form;
22
import org.restlet.ext.wadl.MethodInfo;
23
import org.restlet.representation.Representation;
24
import org.restlet.representation.Variant;
25

  
26
import fr.cnes.sitools.common.resource.SitoolsParameterizedResource;
27
import fr.cnes.sitools.dataset.DataSetApplication;
28
import fr.cnes.sitools.dataset.database.common.DataSetExplorerUtil;
29
import fr.cnes.sitools.tasks.TaskUtils;
30

  
31
/**
32
 * Facade for PublicOrderResource
33
 * 
34
 * 
35
 * @author m.gond
36
 */
37
public class PublicOrderResourceFacade extends SitoolsParameterizedResource implements IOrderResource {
38
  /**
39
   * Description de la ressource
40
   */
41
  @Override
42
  public void sitoolsDescribe() {
43
    setName("PublicOrderResourceFacade");
44
    setDescription("Resource to order data");
45
  }
46

  
47
  /**
48
   * Description WADL de la methode POST
49
   * 
50
   * @param info
51
   *          The method description to update.
52
   */
53
  @Override
54
  public void describePost(MethodInfo info) {
55
    info.setDocumentation("Method to order data from a dataset");
56
    info.setIdentifier("order");
57
    addStandardPostOrPutRequestInfo(info);
58
    DataSetExplorerUtil.addDatasetExplorerGetRequestInfo(info);
59
    DataSetApplication application = (DataSetApplication) getApplication();
60
    DataSetExplorerUtil.addDatasetExplorerGetFilterInfo(info, application.getFilterChained());
61
    addStandardResponseInfo(info);
62
    addStandardInternalServerErrorInfo(info);
63
    this.addInfo(info);
64
  }
65

  
66
  /**
67
   * Create the order
68
   * 
69
   * @param represent
70
   *          the {@link Representation} entity
71
   * @param variant
72
   *          The {@link Variant} needed
73
   * @return a representation
74
   */
75
  public Representation orderPost(Representation represent, Variant variant) {
76
    processBody();
77
    return TaskUtils.execute(this, variant);
78
  }
79

  
80
  /**
81
   * Create the order
82
   * 
83
   * @param variant
84
   *          The {@link Variant} needed
85
   * @return a representation
86
   */
87
  public Representation orderGet(Variant variant) {
88
    return TaskUtils.execute(this, variant);
89
  }
90

  
91
  /**
92
   * process the body and save the request entity {@link Representation}
93
   */
94
  public void processBody() {
95
    Representation body = this.getRequest().getEntity();
96
    if (body != null && body.isAvailable() && body.getSize() > 0) {
97
      Form bodyForm = new Form(body);
98
      getContext().getAttributes().put(TaskUtils.BODY_CONTENT, bodyForm);
99
    }
100
    else {
101
      getContext().getAttributes().remove(TaskUtils.BODY_CONTENT);
102
    }
103
  }
104

  
105
}
Asynchronous_Download_java_sitools2/PublicOrderResourceModel.java
1
 /*******************************************************************************
2
 * Copyright 2010-2014 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
3
 *
4
 * This file is part of SITools2.
5
 *
6
 * SITools2 is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * SITools2 is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with SITools2.  If not, see <http://www.gnu.org/licenses/>.
18
 ******************************************************************************/
19
package fr.cnes.sitools.resources.order;
20

  
21
import java.util.HashSet;
22
import java.util.Map;
23
import java.util.Set;
24

  
25
import fr.cnes.sitools.common.validator.ConstraintViolation;
26
import fr.cnes.sitools.common.validator.ConstraintViolationLevel;
27
import fr.cnes.sitools.common.validator.Validator;
28
import fr.cnes.sitools.dataset.DataSetApplication;
29
import fr.cnes.sitools.plugins.resources.model.DataSetSelectionType;
30
import fr.cnes.sitools.plugins.resources.model.ResourceModel;
31
import fr.cnes.sitools.plugins.resources.model.ResourceParameter;
32
import fr.cnes.sitools.plugins.resources.model.ResourceParameterType;
33
import fr.cnes.sitools.tasks.model.TaskResourceModel;
34
import fr.cnes.sitools.tasks.model.TaskRunTypeAdministration;
35

  
36
/**
37
 * Model for OrderResource
38
 * 
39
 * 
40
 * @author m.gond
41
 */
42
public class PublicOrderResourceModel extends TaskResourceModel {
43

  
44
  /**
45
   * Constructor
46
   */
47
  public PublicOrderResourceModel() {
48

  
49
    super();
50
    setClassAuthor("Shuo");
51
    setClassOwner("IAS");
52
    setClassVersion("0.1");
53
    setName("PublicOrderResourceModel");
54
    setDescription("Order resources associated to metadata for public user and save it in public storage. (Can also create a ZIP, TAR or TAR.GZ 'on the fly')");
55
    /** Resource facade */
56
    setResourceClassName("fr.cnes.sitools.resources.order.PublicOrderResourceFacade");
57
    /** Resource d'implémentation */
58
    setResourceImplClassName("fr.cnes.sitools.resources.order.PublicOrderResource");
59

  
60
    setRunTypeAdministration(TaskRunTypeAdministration.TASK_DEFAULT_RUN_ASYNC);
61

  
62
    ResourceParameter paramColUrl = new ResourceParameter("colUrl", "Colum containing data url for order",
63
        ResourceParameterType.PARAMETER_INTERN);
64
    /** Type de paramètre pour lister les colonnes du dataset */
65
    paramColUrl.setValueType("xs:dataset.columnAlias");
66
    ResourceParameter param2 = new ResourceParameter("zip",
67
        "(true or false) If the data needs to be zipped at the end", ResourceParameterType.PARAMETER_USER_INPUT);
68
    param2.setValue("false");
69
    /** Type de colonne booléen */
70
    param2.setValueType("xs:boolean");
71
    ResourceParameter email= new ResourceParameter("Email","Send alert email when download ready",ResourceParameterType.PARAMETER_USER_INPUT);
72
    email.setValue("");
73
    email.setValueType("xs:string");
74
    this.addParam(paramColUrl);
75
    this.addParam(param2);
76
    this.addParam(email);
77

  
78
    this.setApplicationClassName(DataSetApplication.class.getName());
79
    this.getParameterByName("methods").setValue("POST");
80
    this.setDataSetSelection(DataSetSelectionType.MULTIPLE);
81

  
82
    // paramètres pour la limitation du nombre de fichiers
83
    ResourceParameter paramMaxWarningThreshold = new ResourceParameter("max_warning_threshold",
84
        "Maximum number of files allowed to be downloaded before client warning, download is still allowed",
85
        ResourceParameterType.PARAMETER_USER_GUI);
86
    paramMaxWarningThreshold.setValueType("xs:integer");
87

  
88
    ResourceParameter paramTooManySelectedThreshold = new ResourceParameter("too_many_selected_threshold",
89
        "Maximum number of files allowed to be downloaded (-1 to set no limit)", ResourceParameterType.PARAMETER_INTERN);
90
    paramTooManySelectedThreshold.setValueType("xs:integer");
91
    paramTooManySelectedThreshold.setValue("-1");
92

  
93
    ResourceParameter paramMaxWarningThresholdText = new ResourceParameter("max_warning_threshold_text",
94
        "Text to display to the user when Warning threshold is reached", ResourceParameterType.PARAMETER_USER_GUI);
95
    paramMaxWarningThresholdText.setValueType("xs:string");
96

  
97
    ResourceParameter paramTooManySelectedThresholdText = new ResourceParameter("too_many_selected_threshold_text",
98
        "Text to display to the user when TooMaxySelected threshold is reached",
99
        ResourceParameterType.PARAMETER_USER_GUI);
100
    paramTooManySelectedThresholdText.setValueType("xs:string");
101

  
102
    this.addParam(paramMaxWarningThreshold);
103
    this.addParam(paramTooManySelectedThreshold);
104
    this.addParam(paramMaxWarningThresholdText);
105
    this.addParam(paramTooManySelectedThresholdText);
106

  
107
    this.getParameterByName("fileName").setValue("dataset_order_" + "${date:yyyy-MM-dd HH_mm_ss}");
108

  
109
  }
110

  
111
  @Override
112
  public Validator<ResourceModel> getValidator() {
113
    return new Validator<ResourceModel>() {
114

  
115
      @Override
116
      public Set<ConstraintViolation> validate(ResourceModel item) {
117
        Set<ConstraintViolation> constraints = new HashSet<ConstraintViolation>();
118
        Map<String, ResourceParameter> params = item.getParametersMap();
119
        ResourceParameter param = params.get("colUrl");
120
        String value = param.getValue();
121
        if (value == null || value.equals("")) {
122
          ConstraintViolation constraint = new ConstraintViolation();
123
          constraint.setMessage("An attribute of the dataset must be choosen");
124
          constraint.setLevel(ConstraintViolationLevel.CRITICAL);
125
          constraint.setValueName(param.getName());
126
          constraints.add(constraint);
127
        }
128
        param = params.get("zip");
129
        if (param != null) {
130
          value = param.getValue();
131
          if (value == null || (!"false".equals(value) && !"true".equals(value))) {
132
            ConstraintViolation constraint = new ConstraintViolation();
133
            constraint.setMessage("Must be a boolean");
134
            constraint.setLevel(ConstraintViolationLevel.CRITICAL);
135
            constraint.setInvalidValue(value);
136
            constraint.setValueName(param.getName());
137
            constraints.add(constraint);
138
          }
139
        }
140
        param = params.get("too_many_selected_threshold");
141
        value = param.getValue();
142
        if (value == null || "".equals(value)) {
143
          ConstraintViolation constraint = new ConstraintViolation();
144
          constraint.setMessage("Cannot be null");
145
          constraint.setLevel(ConstraintViolationLevel.CRITICAL);
146
          constraint.setInvalidValue(value);
147
          constraint.setValueName(param.getName());
148
          constraints.add(constraint);
149
        }
150
        else {
151
          try {
152
            Integer.parseInt(value);
153
          }
154
          catch (NumberFormatException e) {
155
            ConstraintViolation constraint = new ConstraintViolation();
156
            constraint.setMessage("Must be an integer value");
157
            constraint.setLevel(ConstraintViolationLevel.CRITICAL);
158
            constraint.setInvalidValue(value);
159
            constraint.setValueName(param.getName());
160
            constraints.add(constraint);
161
          }
162
        }
163
        return constraints;
164
      }
165
    };
166
  }
167

  
168
}
Asynchronous_Download_userInterface_sitools2/goToTaskPanel.js
1
/*******************************************************************************
2
 * Copyright 2010-2014 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
3
 * 
4
 * This file is part of SITools2.
5
 * 
6
 * SITools2 is free software: you can redistribute it and/or modify it under the
7
 * terms of the GNU General Public License as published by the Free Software
8
 * Foundation, either version 3 of the License, or (at your option) any later
9
 * version.
10
 * 
11
 * SITools2 is distributed in the hope that it will be useful, but WITHOUT ANY
12
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14
 * 
15
 * You should have received a copy of the GNU General Public License along with
16
 * SITools2. If not, see <http://www.gnu.org/licenses/>.
17
 ******************************************************************************/
18
/*global Ext, sitools, i18n, SitoolsDesk, alertFailure, window, loadUrl */
19

  
20
Ext.namespace('sitools.user.component.dataviews');
21

  
22
/**
23
 * A simple window that displays result of Resource Tasks.
24
 * @class sitools.user.component.dataviews.goToTaskPanel
25
 * @extends Ext.Panel
26
 */
27
sitools.user.component.dataviews.goToTaskPanel = Ext.extend(Ext.Panel, {
28
//sitools.user.component.livegrid.goToTaskPanel = Ext.extend(Ext.Window, {
29
//    modal : true,
30
    width : "500", 
31
    buttonAlign : 'left',
32
    layout : 'fit',
33
    initComponent : function () {
34
        
35
        
36
        
37
        this.mainPanel = this.createNewFormComponent(this.task);
38
 
39
        this.buttons = ["->",/* {
40
            text : i18n.get('label.goToTask'),
41
            scope : this,
42
            handler : this.goToTask
43
        },*/ {
44
            text : i18n.get('label.close'),
45
            scope : this,
46
            handler : function () {
47
                this.ownerCt.close();
48
            }
49
        } ];
50
        
51
        
52
        this.items = [this.mainPanel];
53
        
54
        sitools.user.component.dataviews.goToTaskPanel.superclass.initComponent.call(this);
55

  
56
    },
57
    
58
    refreshTask : function () {
59
//        var form = this.mainPanel;
60
        var url = this.task.statusUrl;
61
        Ext.Ajax.request({
62
            url : url,
63
            method : "GET",
64
            scope : this,
65
            success : function (ret) {
66
                var data = Ext.decode(ret.responseText);
67
                if (!data.success) {
68
                    Ext.Msg.alert(i18n.get('label.warning'), data.message);
69
                    return false;
70
                }
71
                this.task = data.TaskModel;
72
                this.mainPanel = this.createNewFormComponent(this.task);
73
                this.removeAll();
74
                this.add(this.mainPanel);
75
                this.doLayout();
76
            },
77
            failure : alertFailure
78
        });
79
    },
80
    
81
    createNewFormComponent : function (task) {
82
        var html = String.format("<p>Hi, your download task is being processed, we will inform you by email when it is done.</p>");
83
	html += String.format("<p>For public users, we will send you a link for download in the email.</p>");
84
	//html += String.format("<p>You can check the progress by clicking the button <b>Go to the task</b> below.</p>");
85
	html += String.format("<p>For registered users, you can find and manage(delete or download) all your historical download tasks by clicking the <b>Tasks</b> button which located in your user menu.</p>");
86
       
87
	/* var html = String.format(i18n.get("label.taskLaunched"), task.status);
88
        html += String.format("<a href='#'>{0}</a><br>", i18n.get("label.detail"));
89
        
90
        if (!Ext.isEmpty(task.urlResult)) {
91
			html += "<br>" + String.format(i18n.get("label.taskResult"), task.urlResult);	
92
			html += String.format("<a href='#'>{0}</a><br>", i18n.get("label.result"));
93
        }
94
        else {
95
			html += "<br>" + i18n.get("label.refreshTaskWindow");	
96
			html += String.format("<a href='#'>{0}</a><br>", i18n.get("label.refresh"));
97
        }*/
98
        
99
        var panel = new Ext.Panel({
100
			padding: 5,
101
			layout : "fit", 
102
			html : html, 
103
			listeners : {
104
				scope : this, 
105
				afterrender : function (panel) {
106
					/*panel.getEl().child('a').on("click", function () {
107
						this.showTaskDetail(task);
108
					}, this);
109
					var resultOrRefreshLink = panel.getEl().child('a').next('a');
110
					if (!Ext.isEmpty(task.urlResult)) {
111
						resultOrRefreshLink.on("click", function () {
112
							this.showTaskResults(task);
113
						}, this);
114
					}
115
					else {
116
						resultOrRefreshLink.on("click", function () {
117
							this.refreshTask();
118
						}, this);
119
					}*/
120
				}
121
			}
122
        });
123
        return panel;
124
        
125
//        var formPanel = new Ext.form.FormPanel({
126
//            title : i18n.get("label.taskDetails"),
127
//            padding: 5,
128
//            items : [ {
129
//                name : 'statusUrl',
130
//                xtype : 'textfield',
131
//                value : task.statusUrl,
132
//                hidden : true
133
//            }, {
134
//                name : 'status',
135
//                fieldLabel : i18n.get('label.status'),
136
//                anchor : "100%",
137
//                xtype : 'textfield',
138
//                value : task.status
139
//            }, {
140
//                name : 'id',
141
//                fieldLabel : i18n.get('label.id'),
142
//                anchor : "100%",
143
//                xtype : 'textfield',
144
//                value : task.id
145
//            }, {
146
//                itemValue : task.statusUrl,
147
//                fieldLabel : i18n.get('label.url'),
148
//                xtype : 'box',
149
//                html : "<a href='#'> " + task.statusUrl + "</a>"
150
//                ,
151
//                listeners : {
152
//                    scope : this,
153
//                    render : function (cmp) {
154
//                        cmp.getEl().on('click', function () {
155
//                            var jsObj = sitools.user.modules.userSpaceDependencies.svaTasksDetails;
156
//                            var componentCfg = {
157
//                                sva : task    
158
//                            };
159
//                            var windowConfig = {
160
//                                id : "taskStatusDetails", 
161
//                                title : i18n.get("label.taskDetails") + ":" + task.id
162
//                            };
163
//                            SitoolsDesk.addDesktopWindow(windowConfig, componentCfg, jsObj);
164
//                        });
165
//                    }
166
//                }
167
//            }
168
//            ]
169
//        });
170
//        
171
//        if (!Ext.isEmpty(task.urlResult)) {
172
//            var item = new Ext.BoxComponent({
173
//                itemValue : task.urlResult,
174
//                fieldLabel : i18n.get('label.result'),
175
//                html : "<a href='#'> " + task.urlResult + "</a>",
176
//                listeners : {
177
//                    scope : this,
178
//                    render : function (cmp) {
179
//                        cmp.getEl().on('click', function () {
180
//                            var orderUrl = loadUrl.get('APP_URL') + loadUrl.get('APP_ORDERS_USER_URL');
181
//                            if (cmp.itemValue.indexOf(orderUrl) != -1) {
182
//                                this._showOrderDetails(cmp.itemValue);
183
//                            } else if (cmp.itemValue.indexOf("/records") != -1) {
184
//                                this._showDatasetDetails(cmp.itemValue);
185
//                            } 
186
//                            else {
187
//                                window.open(cmp.itemValue);
188
//                            }
189
//                        }, this);
190
//                    }
191
//                }
192
//            });
193
//            formPanel.add(item);
194
//        }
195
//        
196
//        return formPanel;
197
        
198
    },
199
    
200
    /**
201
     * Handler of the button goToTask. 
202
     * Open the home Module Window with the taskPanel opened.
203
     */
204
    goToTask : function () {
205
        this.ownerCt.close();
206
		var jsObj = sitools.user.component.entete.userProfile.tasks;
207
        var windowConfig = {
208
            title : i18n.get('label.Tasks'),
209
            saveToolbar : false, 
210
            iconCls : "tasks"
211
        };
212
        SitoolsDesk.addDesktopWindow(windowConfig, {}, jsObj, true);
213

  
214
    },
215
    /**
216
     * Open a sitools.user.component.entete.userProfile.orderProp window. 
217
     * @param {String} url the Url to request the task. 
218
     */
219
    _showOrderDetails : function (url) {
220
        Ext.Ajax.request({
221
            url : url,
222
            method : 'GET',
223
            scope : this,
224
            success : function (ret) {
225
                var data = Ext.decode(ret.responseText);
226
                if (!data.success) {
227
                    Ext.Msg.alert(i18n.get('label.warning'), data.message);
228
                    return false;
229
                }
230
                var rec = new Ext.data.Record(data.order);
231
                var jsObj = sitools.user.component.entete.userProfile.orderProp;
232
                var componentCfg = {
233
                    action : 'detail',
234
                    orderRec : rec
235
                };
236
                var title = i18n.get('label.details') + " : ";
237
                title += rec.data.userId;
238
                title += " " + i18n.get('label.the');
239
                title += " " + rec.data.dateOrder;
240

  
241
                var windowConfig = {
242
                    id : "showDataDetailId", 
243
                    title : title,  
244
                    specificType : "dataDetail", 
245
                    iconCls : "dataDetail"
246
                };
247
                SitoolsDesk.addDesktopWindow(windowConfig, componentCfg, jsObj);
248
            },
249
            failure : alertFailure
250
        });
251
        
252
    },
253
    /**
254
     * Only in NoSql, open a dataset view 
255
     * @param {} url
256
     */
257
    _showDatasetDetails : function (url) {
258
        var urlDataset = url.substring(0, url.indexOf("/records"));
259
        Ext.Ajax.request({
260
            url : urlDataset,
261
            method : 'GET',
262
            scope : this,
263
            success : function (ret) {
264
                var data = Ext.decode(ret.responseText);
265
                if (!data.success) {
266
                    Ext.Msg.alert(i18n.get('label.warning'), data.message);
267
                    return false;
268
                }
269
                var dataset = new Ext.data.Record(data.dataset).data;
270
                
271
                var windowConfig = {
272
                        title : i18n.get('label.dataTitle') + " : " + dataset.name,
273
                        datasetName : dataset.name, 
274
                        datasetDescription : dataset.description,
275
                        type : "data", 
276
                        saveToolbar : true, 
277
                        toolbarItems : [], 
278
                        iconCls : "dataDetail"
279
                    };
280
                
281
                //open the dataView according to the dataset Configuration.
282
                var javascriptObject = eval(dataset.datasetView.jsObject);
283
                //add the toolbarItems configuration
284
                Ext.apply(windowConfig, {
285
                    id : "data" + dataset.datasetId
286
                });
287
                var componentCfg = {
288
                    dataUrl : dataset.sitoolsAttachementForUsers,
289
                    datasetId : dataset.id,
290
                    datasetCm : dataset.columnModel, 
291
                    datasetName : dataset.name,
292
                    dictionaryMappings : dataset.dictionaryMappings, 
293
	                datasetViewConfig : dataset.datasetViewConfig, 
294
                    preferencesPath : "/" + dataset.name, 
295
                    preferencesFileName : "datasetView"
296
                };
297
                
298
                SitoolsDesk.addDesktopWindow(windowConfig, componentCfg, javascriptObject);
299
                
300
            },
301
            failure : alertFailure
302
        });
303
        
304
    }, 
305
    /**
306
     * Opens a sitools.user.modules.userSpaceDependencies.svaTasksDetails window to see the task Details. 
307
     * @param {} task
308
     */
309
    showTaskDetail : function (task) {
310
	    var jsObj = sitools.user.component.entete.userProfile.tasksDetails;
311
	    var componentCfg = {
312
	        sva : task    
313
	    };
314
	    var windowConfig = {
315
	        id : "taskStatusDetails", 
316
	        title : i18n.get("label.taskDetails") + ":" + task.id, 
317
	        iconCls : "dataDetail"
318
	    };
319
	    SitoolsDesk.addDesktopWindow(windowConfig, componentCfg, jsObj);
320
	}, 
321
	/**
322
	 * parse the task.urlResult to see if this is an Specialized resource (noSQl or Order). 
323
	 * If not, open a new Window to get the result of the resource. 
324
	 * @param {} task
325
	 */
326
	showTaskResults : function (task) {
327
		var orderUrl = loadUrl.get('APP_URL') + loadUrl.get('APP_ORDERS_USER_URL');
328
        if (task.urlResult.indexOf(orderUrl) != -1) {
329
            this._showOrderDetails(task.urlResult);
330
        } else if (task.urlResult.indexOf("/records") != -1) {
331
            this._showDatasetDetails(task.urlResult);
332
        } 
333
        else {
334
            window.open(task.urlResult);
335
        }
336
	}, 
337
    /**
338
     * Method called when trying to show this component with fixed navigation
339
     * 
340
     * @param {sitools.user.component.viewDataDetail} me the dataDetail view
341
     * @param {} config config options
342
     * @returns
343
     */
344
    showMeInFixedNav : function (me, config) {
345
        Ext.apply(config.windowSettings, {
346
            width : config.windowSettings.winWidth || DEFAULT_WIN_WIDTH,
347
            height : config.windowSettings.winHeight || DEFAULT_WIN_HEIGHT
348
        });
349
        SitoolsDesk.openModalWindow(me, config);
350
    }, 
351
    /**
352
     * Method called when trying to show this component with Desktop navigation
353
     * 
354
     * @param {sitools.user.component.viewDataDetail} me the dataDetail view
355
     * @param {} config config options
356
     * @returns
357
     */
358
    showMeInDesktopNav : function (me, config) {
359
        Ext.apply(config.windowSettings, {
360
            width : config.windowSettings.winWidth || DEFAULT_WIN_WIDTH,
361
            height : config.windowSettings.winHeight || DEFAULT_WIN_HEIGHT
362
        });
363
        SitoolsDesk.openModalWindow(me, config);
364
    }
365
    
366

  
367
});
368

  
Asynchronous_Download_userInterface_sitools2/resourcePluginParamsPanel.js
1
/*******************************************************************************
2
 * Copyright 2010-2014 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
3
 * 
4
 * This file is part of SITools2.
5
 * 
6
 * SITools2 is free software: you can redistribute it and/or modify it under the
7
 * terms of the GNU General Public License as published by the Free Software
8
 * Foundation, either version 3 of the License, or (at your option) any later
9
 * version.
10
 * 
11
 * SITools2 is distributed in the hope that it will be useful, but WITHOUT ANY
12
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14
 * 
15
 * You should have received a copy of the GNU General Public License along with
16
 * SITools2. If not, see <http://www.gnu.org/licenses/>.
17
 ******************************************************************************/
18
/*global Ext, sitools, i18n, SitoolsDesk */
19

  
20
Ext.namespace('sitools.user.component.dataviews');
21
/**
22
 * @cfg {Ext.menu.menu} contextMenu the contextMenu that call the plugin and will execute onResourceCallClick method
23
 * @cfg {Ext.data.Record} resource the resource record
24
 * @cfg {string} url the base url of the resource
25
 * @cfg {string} methods the methods allowed with the format method1|method2|...|methodN
26
 * @cfg {string} runType the runTypeUserInput defined in the resource
27
 * @cfg {boolean} withSelection true if there was a selection, false otherwise
28
 * @cfg {Array} parameters the parameters
29
 * @class sitools.user.component.dataviews.resourcePluginParamsPanel
30
 * @extends Ext.Window
31
 */
32
sitools.user.component.dataviews.resourcePluginParamsPanel = Ext.extend(Ext.Panel, {
33
//sitools.user.component.livegrid.resourcePluginParamsWindow = Ext.extend(Ext.Window, {
34
    width : "450",
35
    
36
    showMethod : false, 
37
    defaultMethod : "",
38
    showRunType : false, 
39
    initComponent : function () {
40
        var methodsArray = this.methods.split("|");
41
        this.showMethod = methodsArray.length > 1;
42
        this.defaultMethod = methodsArray[0];
43
        
44
        this.methodsStore = new Ext.data.ArrayStore({
45
            fields: ["method"],
46
            idIndex: 0
47
        });
48
    
49
        Ext.each(methodsArray, function (item, index) {
50
            this.methodsStore.add(new Ext.data.Record({
51
                method : item
52
            }));
53
        }, this);
54
        
55
        var formCommonParametersFields = [];
56
        var comboMethod = new Ext.form.ComboBox({                
57
            xtype : 'combo',
58
            mode : 'local',
59
            triggerAction : 'all',
60
            editable : false,
61
            name : 'method',
62
            fieldLabel : i18n.get('label.method'),
63
            width : 100,
64
            store : this.methodsStore,
65
            valueField : 'method',
66
            displayField : 'method',
67
            anchor : "100%",
68
            value : this.defaultMethod,
69
            forceSelection : true
70
        });
71
        this.items = [];
72
        if (this.showMethod) {
73
			formCommonParametersFields.push(comboMethod);
74
			this.formParams = new Ext.form.FormPanel({
75
	            padding: 5,
76
	//            title : "Request parameters",
77
	            items : [{
78
	                xtype : 'fieldset',
79
	                title : i18n.get("label.commonParameters"),
80
	                items : formCommonParametersFields
81
	            }]
82
	        });
83
	        
84
	        this.items.push(this.formParams);			
85
        }
86
        
87
        var userInputParams = [];
88
	this.user = projectGlobal.user || {
89
                        firstName : "public",
90
                        identifier : "public",
91
                        email : "&nbsp;"
92
                        };
93

  
94
        Ext.each(this.resource.parameters, function (value, index) {
95
            if (value.type == "PARAMETER_USER_INPUT" && value.userUpdatable) {
96
                if(value.name == "Email" && this.user.identifier != "public"){
97
			//if user is not public donnot show email input field
98
		}else{
99
			var item = this.buildFormItemFromParam(value);
100
	        	userInputParams.push(item);
101
                	if (value.name == "runTypeUserInput") {
102
                		this.showRunType = true;
103
                        }
104

  
105
		}
106
            }
107
        }, this);
108

  
109
        if (!Ext.isEmpty(userInputParams)) {
110
            this.formParamsUserInput = new Ext.form.FormPanel({
111
                padding: 5,
112
                labelWidth : 150, 
113
                items : {
114
                    xtype : 'fieldset',
115
                    title : i18n.get("label.specificParameter"),
116
                    items : userInputParams
117
                }
118
            });  
119
            this.items.push(this.formParamsUserInput);
120
        }
121
        
122
        this.buttons = [{
123
            text : i18n.get('label.submit'),
124
            scope : this,
125
            handler : this.onCall            
126
        }, {
127
            text : i18n.get('label.cancel'),
128
            scope : this,
129
            handler : function () {
130
                this.ownerCt.close();
131
                this.callback.call(undefined, false);
132
            }
133
        }];
134
        sitools.user.component.dataviews.resourcePluginParamsPanel.superclass.initComponent.call(this);
135
    },
136
    
137
    onCall : function () {        
138
        var method;
139
        if (this.showMethod) {
140
	        var form = this.formParams.getForm();
141
	        method = form.findField("method").getValue();
142
        }
143
        else {
144
			method = this.defaultMethod;	
145
        }
146
		
147
        var runTypeUserInput;
148
        if (this.showRunType) {
149
			runTypeUserInput = this.formParamsUserInput.getForm().findField("runTypeUserInput").getValue();
150
        }
151
        else {
152
			runTypeUserInput = this.runType;
153
        }
154
        var limit;
155

  
156
        var userParameters = {};
157
        if (!Ext.isEmpty(this.formParamsUserInput)) {
158
            var formParams = this.formParamsUserInput.getForm();
159
            Ext.iterate(formParams.getValues(), function (key, value) {
160
                userParameters[key] = value;                
161
            });
162
        }
163
        if(userParameters["Email"] == ""){
164
	    Ext.Msg.alert("Email error","Please insert an email address which will be used to inform you with the download link.");
165
            return false;
166
	} 
167
        Ext.each(this.parameters, function (param) {
168
            if (param.type == "PARAMETER_IN_QUERY") {
169
                userParameters[param.name] = param.value;
170
            }
171
        });
172
        
173
        this.contextMenu.onResourceCallClick(this.resource, this.url, method, runTypeUserInput, limit, userParameters, this.postParameter, this.callback);
174
        this.ownerCt.close();
175
    }, 
176
    buildFormItemFromParam : function (value, userInputParams) {
177
		var valueType = value.valueType;
178
        var item = {};
179
        //specific case for boolean
180
        if (valueType.indexOf("xs:boolean") != -1) {
181
            valueType = "xs:enum[true,false]";
182
        }
183
        if (valueType.indexOf("xs:enum") != -1) {
184
	        var enumeration = valueType.split("[");
185
	        enumeration = enumeration[1].split("]");
186
	        enumeration = enumeration[0].split(",");
187

  
188
			var multiple = false;
189
			if (valueType.indexOf("xs:enum-multiple") >= 0 || valueType.indexOf("xs:enum-editable-multiple") >= 0) {
190
				multiple = true;
191
			}
192
			
193
			var storeItems = [];
194
			for (var i = 0; i < enumeration.length; i++) {
195
				var tmp = enumeration[i].trim();
196
				storeItems.push([ tmp, tmp]);
197
			}
198
			var store = new Ext.data.ArrayStore({
199
                fields : ['value', 'text'],
200
                data : storeItems, 
201
                valueField : 'value', 
202
                displayField : 'text'
203
            });
204
			
205
			if (multiple) {
206
				item = {
207
					store : store,
208
					name : value.name, 
209
					xtype : "multiselect", 
210
					values : value.value, 
211
					delimiter : '|', 
212
					fieldLabel : value.name, 
213
					width : 235, 
214
					tooltip : value.description
215
				};
216
			}
217
			else {
218
				item = {
219
					store : store,
220
					name : value.name, 
221
					xtype : "combo", 
222
					value : value.value, 
223
					valueField : "value", 
224
					displayField : "text", 
225
					mode: 'local', 
226
					fieldLabel : value.name, 
227
					triggerAction : 'all',
228
					selectOnFocus : true,
229
					editable : false, 
230
					anchor : "100%", 
231
					tooltip : value.description
232
				};
233
			}
234
        }
235
        else {
236
			item = {
237
                name : value.name,
238
                xtype : 'textfield',
239
                value : value.value,
240
                fieldLabel : value.name,
241
                anchor : "100%", 
242
				tooltip : value.description
243
            };
244
        }
245
        return item;
246
    }, 
247
    /**
248
     * Method called when trying to show this component with fixed navigation
249
     * 
250
     * @param {sitools.user.component.viewDataDetail} me the dataDetail view
251
     * @param {} config config options
252
     * @returns
253
     */
254
    showMeInFixedNav : function (me, config) {
255
        Ext.apply(config.windowSettings, {
256
            width : config.windowSettings.winWidth || DEFAULT_WIN_WIDTH,
257
            height : config.windowSettings.winHeight || DEFAULT_WIN_HEIGHT
258
        });
259
        SitoolsDesk.openModalWindow(me, config);
260
    }, 
261
    /**
262
     * Method called when trying to show this component with Desktop navigation
263
     * 
264
     * @param {sitools.user.component.viewDataDetail} me the dataDetail view
265
     * @param {} config config options
266
     * @returns
267
     */
268
    showMeInDesktopNav : function (me, config) {
269
        Ext.apply(config.windowSettings, {
270
            width : config.windowSettings.winWidth || DEFAULT_WIN_WIDTH,
271
            height : config.windowSettings.winHeight || DEFAULT_WIN_HEIGHT
272
        });
273
        SitoolsDesk.openModalWindow(me, config);
274
    }
275

  
276
});
Enhanced_Node_Editor_adminInterface/GraphsNodeWin.js
1
/***************************************
2
* Copyright 2010-2014 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
3
* 
4
* This file is part of SITools2.
5
* 
6
* SITools2 is free software: you can redistribute it and/or modify
7
* it under the terms of the GNU General Public License as published by
8
* the Free Software Foundation, either version 3 of the License, or
9
* (at your option) any later version.
10
* 
11
* SITools2 is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
* 
16
* You should have received a copy of the GNU General Public License
17
* along with SITools2.  If not, see <http://www.gnu.org/licenses/>.
18
***************************************/
19
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser, 
20
 showHelp*/
21
Ext.namespace('sitools.component.projects');
22

  
23
Ext.define('sitools.admin.graphs.GraphsNodeWin', {
24
    extend : 'Ext.Window',
25
    width : 350,
26
    modal : true,
27
    closable : false,
28

  
29
    initComponent : function () {
30
        projectId = this.projectId;
31
        this.title = i18n.get('label.nodeDescription');
32
        /* paramétres du formulaire */
33
        this.itemsForm = [{
34
            fieldLabel : i18n.get('label.name'),
35
            name : 'name',
36
            anchor : '100%',
37
            allowBlank : false
38
        }, {
39
            fieldLabel : i18n.get('label.description'),
40
            name : 'description',
41
            anchor : '100%'
42
        }, {
43
            xtype : 'sitoolsSelectImage',
44
            name : 'image',
45
            fieldLabel : i18n.get('label.image'),
46
            anchor : '100%',
47
            growMax : 400
48
        },{
49
            xtype: 'button',
50
            id: 'linktodataset',
51
            text: '<span style="">Link to a dataset</span>',
52
            anchor: '65%',
53
            margin: '0 5% 0 0',
54
            handler: function() {
55
                up = Ext.create("sitools.admin.graphs.GraphsDatasetWin", {
56
                    graphTree : true,
57
                    url : loadUrl.get('APP_URL') + '/projects/' + projectId + '?media=json',
58
                    mode : 'link',
59
                    form : form
60
                });
61
                up.show(this);
62

  
63
            }
64
        }, {
65
            xtype: 'button',
66
            id: 'unlinkbutton',
67
            text: '<span style="">Unlink</span>',
68
            disabled:true,
69
            anchor: '35%',
70
            margin: '0 0 0 5%',
71
            handler: function() {
72
                Ext.getCmp('unlinkbutton').setDisabled(true);
73
                form.findField('nbRecord').setValue('');
74
                form.findField('datasetURL').setValue('');
75
                Ext.getCmp('datatablecheckbox').setValue(false);
76
                Ext.getCmp('queryformcheckbox').setValue(false);
77
                Ext.getCmp('datatablecheckbox').setDisabled(true);
78
                Ext.getCmp('queryformcheckbox').setDisabled(true);
79
            }
80
        },{
81
            name : 'nbRecord',
82
            fieldLabel : 'Number of records',
83
            readOnly: true,
84
            cls: 'x-item-disabled',
85
            anchor : '100%'
86
        },{
87
            name : 'datasetURL',
88
            fieldLabel : 'Dataset URL',
89
            readOnly: true,
90
            cls: 'x-item-disabled',
91
            anchor : '100%'
92
        }, {
93
            xtype: 'checkboxfield',
94
            boxLabel: 'Data table',
95
            name: 'datatable',
96
            width: '40%',
97
            margin: '0 10% 0 10%',
98
            disabled: true,
99
            id: 'datatablecheckbox'
100
        }, {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff