Project

General

Profile

« Previous | Next » 

Revision 42217

[maven-release-plugin] copy for tag dnet-modular-repositories-ui-4.0.6

View differences:

modules/dnet-modular-repositories-ui/tags/dnet-modular-repositories-ui-4.0.6/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3
	<parent>
4
		<groupId>eu.dnetlib</groupId>
5
		<artifactId>dnet-parent</artifactId>
6
		<version>1.0.0</version>
7
	</parent>
8
	<modelVersion>4.0.0</modelVersion>
9
	<groupId>eu.dnetlib</groupId>
10
	<artifactId>dnet-modular-repositories-ui</artifactId>
11
	<packaging>jar</packaging>
12
	<version>4.0.6</version>
13
	<scm>
14
   		<developerConnection>scm:svn:https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/dnet-modular-repositories-ui/tags/dnet-modular-repositories-ui-4.0.6</developerConnection>
15
	</scm>
16
	<dependencies>
17
		<dependency>
18
			<groupId>eu.dnetlib</groupId>
19
			<artifactId>dnet-modular-ui</artifactId>
20
			<version>[3.0.0,4.0.0)</version>
21
		</dependency>
22
		<dependency>
23
			<groupId>eu.dnetlib</groupId>
24
			<artifactId>dnet-modular-workflows-ui</artifactId>
25
			<version>[4.0.0,5.0.0)</version>
26
		</dependency>
27
		<dependency>
28
			<groupId>eu.dnetlib</groupId>
29
			<artifactId>dnet-datasource-manager-rmi</artifactId>
30
			<version>[4.0.0, 5.0.0)</version>
31
		</dependency>
32
		<dependency>
33
			<groupId>junit</groupId>
34
			<artifactId>junit</artifactId>
35
			<version>${junit.version}</version>
36
			<scope>test</scope>
37
		</dependency>
38
		<dependency>
39
			<groupId>javax.servlet</groupId>
40
			<artifactId>javax.servlet-api</artifactId>
41
			<version>${javax.servlet.version}</version>
42
			<scope>provided</scope>
43
		</dependency>
44
	</dependencies>
45

  
46
	<properties>
47
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
48
	</properties>
49

  
50
</project>
modules/dnet-modular-repositories-ui/tags/dnet-modular-repositories-ui-4.0.6/src/main/resources/eu/dnetlib/web/resources/js/repoControllers.js
1
var repoControllers = angular.module('repoControllers', []);
2

  
3
repoControllers.controller('repoBrowseCtrl', [
4
	'$scope', '$http', '$timeout', '$sce', '$location',
5
	function ($scope, $http, $timeout, $sce, $location) {
6
		common_init($scope, $http, $sce, $location);
7
		$scope.repoBrowseFields = getBrowseFields();
8
		$scope.filterBrowseData = { filterText: '' };
9
		$scope.repoBrowseData = { 'data' : [] };
10
		
11
		$scope.gridBrowseData = {
12
				data: 'repoBrowseData.data',
13
				enableRowSelection: false,
14
				enableCellEditOnFocus: false,
15
				enableHighlighting: true,
16
				filterOptions: $scope.filterBrowseData,
17
				sortInfo: { fields: ['value'], directions: ['desc'] },
18
				columnDefs: [
19
				             {field: 'name', displayName: 'Name', cellTemplate: '<div class="ngCellText"><a href="javascript:void(0)" ng-click="browseApis(repoBrowseData.id, row.getProperty(\'id\'))">{{row.getProperty(col.field)}}</a></div>' },
20
				             {field: 'value', displayName: '# datasources', width: '20%', headerClass: 'text-right', cellClass: 'text-right' }
21
				             ]
22
		};
23
		
24
		$scope.searchApis = function (text) {
25
			$scope.go('/list/__SEARCH__/' + text); 
26
		} 
27
		
28
		$scope.browseApis = function (field, value) {
29
			$('#showRepoBrowseData').modal('hide');
30
			$scope.showSpinner();
31
			$timeout(function() {
32
				$scope.go('/list/' + field + '/' + value);
33
			}, 1500);
34
		}
35
		
36
		$scope.browseRepoField = function(field) {
37
			$scope.repoBrowseData = {
38
				'label' : field.label,
39
				'id' :    field.id,
40
				'data'  : []
41
			};
42
			$scope.showSpinner();
43
	      	$http.get('browseRepoField.do?field=' + field.id).success(
44
	            function(data) {
45
	            	$scope.hideSpinner();
46
	            	$scope.repoBrowseData.data = data;
47
	            	$('#showRepoBrowseData').modal('show');
48
	            }
49
	        ).error(
50
	            function() {
51
	            	$scope.showError('Something really bad must have happened to our fellow hamster..');
52
	            	$scope.hideSpinner();
53
	            }
54
	        );
55
		};
56
	}
57
]);
58

  
59
repoControllers.controller('repoListCtrl', [
60
	'$scope', '$http', '$timeout', '$sce', '$routeParams', '$location',
61
	function ($scope, $http, $timeout, $sce, $routeParams, $location) {
62
		common_init($scope, $http, $sce, $location);
63

  
64
		$scope.apis = [];
65
		$scope.filterApis = { filterText: '' };
66
		$scope.gridApis = { 
67
				data: 'apis',
68
				enableRowSelection: false,
69
				enableCellEditOnFocus: false,
70
				enableHighlighting: true,
71
				filterOptions: $scope.filterApis,
72
				columnDefs: [
73
				             {field: 'repoCountry' , displayName: 'Country',               width: '80px',  headerClass: 'text-center', cellTemplate: '<ng-repo-country-cell />' },
74
				             {field: 'repoName'    , displayName: 'Datasource Api',        cellTemplate: '<ng-reponame-cell />' },
75
				             {field: 'repoPrefix'  , displayName: 'Namespace Prefix',      width: '150px', headerClass: 'text-center', cellClass: 'text-center' },
76
				             {field: 'protocol'    , displayName: 'Protocol',        	   width: '160px', headerClass: 'text-center', cellClass: 'text-center' },
77
				             {field: 'aggrDate'    , displayName: 'Last Aggregation Date', width: '200px', headerClass: 'text-center', cellTemplate: '<ng-aggr-date-cell />' },
78
				             {field: 'aggrTotal'   , displayName: 'Total',                 width: '80px',  headerClass: 'text-center', cellTemplate: '<ng-aggr-total-cell />' }
79
				            ]
80
		};
81
		
82
    	$scope.currentApiSelectionParam = $routeParams.param;
83
    	$scope.currentApiSelectionValue = $routeParams.value;
84
    	
85
    	$scope.updateApis = function(refresh) {
86
			$scope.showSpinner();
87
						    
88
			var params = {
89
				'param' : $scope.currentApiSelectionParam,
90
				'value' : $scope.currentApiSelectionValue,
91
			};
92
			if (refresh) {
93
				params.refresh = 1;
94
			}
95

  
96
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
97
			$http.post('listApis.do', $.param(params)).success(
98
	            function(data) {
99
	            	$scope.hideSpinner();
100
	            	$scope.apis = data;
101
	            	$scope.resizeMainElement(document.getElementById('apisTable'));
102
	            }
103
	        ).error(
104
	            function() {
105
	            	$scope.showError('Something really bad must have happened to our fellow hamster..');
106
	            	$scope.hideSpinner();
107
	            }
108
	        );
109
    	};
110
    		
111
		$scope.showApi = function (repoId, ifaceId) {
112
			$scope.go('/api/' + repoId + '/' + ifaceId + "/ALL/ALL"); 
113
		}
114
		
115
		window.onresize = function() {
116
			var elem = document.getElementById('apisTable');
117
			if (elem) {
118
				angular.element(elem).scope().resizeMainElement(elem);
119
			}
120
		};
121
    	
122
    	$scope.updateApis(false);
123
	}
124
]);
125

  
126
repoControllers.controller('repoApiCtrl', [
127
	'$scope', '$http', '$timeout', '$sce', '$routeParams', '$location',
128
	function ($scope, $http, $timeout, $sce, $routeParams, $location) {
129
		common_init($scope, $http, $sce, $location);
130
		
131
		commonInitialize($scope, $http, $sce);
132
		wf_init($scope, $http, $sce);
133
		
134
		$scope.availableRepohiWfs = getAvailableRepohiWfs();
135
		$scope.compatibilityLevels = getCompatibilityLevels();
136
		
137
		$scope.validatorBlacklistAddress = '';
138
		$scope.validatorBlacklistAddress = '';
139
    			
140
		$scope.currentRepoApi = {};
141
		$scope.currentSets = [];
142
		$scope.selectedSets = [];
143
    	
144
    	$scope.loadApi = function() {
145
    		$scope.showSpinner();
146
    		$(".btnRefreshApi").attr("disabled", "disabled");
147
    		$http.get('repoApi.get?repoId=' + $routeParams.repoId + "&ifaceId=" +  $routeParams.ifaceId)
148
            .success(
149
                function(data) {
150
                	$scope.currentRepoApi = data;
151
                	$scope.metaworkflows = data.metaWFs;
152
 
153
                	angular.forEach(data.otherParams, function(term){
154
                		if (term.id == 'last_validation_job') {
155
                			if (getValidatorAddress()) {
156
                				$scope.validatorDetailsAddress = getValidatorAddress() + "/prepareSummary.action?jobId=" + term.value;
157
                			}
158
                			if (getValidatorServiceAddress()) {
159
                				$scope.validatorBlacklistAddress = getValidatorServiceAddress() + "/workflows?request=GetBlacklistedRecords&datasourceId=" + $routeParams.repoId;
160
                			}
161
                		}                                       
162
                	});
163
                	
164
                	if (data.protocol == 'oai') {
165
    	            	var found = false;
166
    	            	angular.forEach(data.accessParams, function(param, pos){
167
    	                    if (param.name == 'set') {
168
    	                    	$scope.listSets($scope.currentRepoApi.accessParams);
169
    	                    }
170
    	        		});
171
                	}
172
                	$scope.hideSpinner(); 
173
                	            	
174
                	$(".btnRefreshApi").removeAttr("disabled");
175
                	
176
                	if ($routeParams.metawf != 'ALL' && $routeParams.wf != 'ALL') {
177
                		$scope.getAtomicWorkflowAndMetaWf($routeParams.metawf, $routeParams.wf);
178
                		$timeout(function() {
179
                			$("#collapse_" + $routeParams.metawf.substring(0, 36)).collapse('show');
180
                		}, 2000);
181
                	}
182
                }
183
            ).error(
184
                function() {
185
                	$scope.showError('Something really bad must have happened to our fellow hamster..');
186
                	$scope.hideSpinner();
187
                }
188
            );
189
    	};
190
    	
191
		$scope.newDataProviderWorkflow = function (wf) {
192
			
193
			if (wf == undefined) {
194
				$scope.showError('Please choose a workflow !');
195
	    		return;
196
			}
197
			
198
			$scope.showSpinner();
199
	
200
			$scope.metaworkflows.push({"id":"","name":"Waiting...","status":"MISSING","progress":0});
201
	    				
202
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
203
			$http.post('repoMetaWf.new', $.param({
204
				'wf'    : wf,
205
				'iface' : $scope.currentRepoApi.id,
206
				'id'    : $scope.currentRepoApi.repoId, 
207
				'name'  : $scope.currentRepoApi.repoName
208
			})).success(
209
	       			function(data) {
210
	       				$scope.hideSpinner();
211
	       				$(".btnRefreshApi").attr("disabled", "disabled");
212
	       				$timeout(function () { $scope.loadApi() }, 7000);
213
		            }
214
	       	).error(
215
	       			function() {
216
	       				$scope.showError('Something really bad must have happened to our fellow hamster..');
217
	       				$scope.hideSpinner();
218
		           }
219
	       	);
220
		};
221
		
222
		$scope.destroyDataProviderWorkflow = function (metaWf) {
223
			
224
			if (metaWf.destroyWorkflow == undefined) {
225
				$scope.showError('Destroy wf is missing !');
226
	    		return;
227
			}
228
			
229
			if (!confirm("Are you sure ?")) {
230
				return;
231
			}
232
					
233
			$scope.showSpinner();
234
			
235
			metaWf.deleting = true;
236
			
237
			$http.get('repoMetaWf.destroy?destroyWf=' + metaWf.destroyWorkflow)
238
	       	.success(
239
	       			function(data) {
240
	       				$scope.hideSpinner();
241
	       				$(".btnRefreshApi").attr("disabled", "disabled");
242
	       				$timeout(function () { $scope.loadApi() }, 7000);
243
		            }
244
	       	).error(
245
	       			function() {
246
	       				$scope.showError('Something really bad must have happened to our fellow hamster..');
247
	       				$scope.hideSpinner();
248
		           }
249
	       	);
250
		};
251
		
252
		$scope.testOAI = function (params) {
253
			angular.forEach(params, function(param, pos){
254
	            if (param.name == 'baseUrl') {
255
	            	location.href = "oaiExplorer.do?oaiBaseUrl=" + param.value;
256
	            }
257
			});
258
		}
259
	
260
		$scope.updateRepoApi = function(params) {
261
			$scope.showSpinner();
262
	
263
			var map = {};
264
			angular.forEach(params, function(param, pos){
265
	            if (param.name) {
266
	            	map[param.name] = param.value
267
	            }
268
			});
269
			
270
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
271
	        $http.post('repoApi.update', $.param({
272
	      		'id'    : $scope.currentRepoApi.repoId,
273
	      		'iface' : $scope.currentRepoApi.id,
274
	      		'accessParams' : JSON.stringify(map)
275
	      	})).success(function(data) {
276
	      		$scope.showNotification('Api correctly saved !');
277
	        	$scope.loadApi(); 
278
	        }).error(function() {
279
	        	$scope.showError('Something really bad must have happened to our fellow hamster..');
280
	        	$scope.hideSpinner();
281
	        });
282
		};
283
		
284
		
285
		$scope.updateSets = function(selection, accessParams) {
286
			var s = selection.join();
287
			angular.forEach(accessParams, function(param, pos){
288
	            if (param.name == 'set') {
289
	            	param.value = s;
290
	            }
291
			});
292
		}
293
		
294
		$scope.listSets = function(accessParams) {
295
			var baseUrl = '';
296
			
297
			$scope.selectedSets = [];
298
			$scope.currentSets = [];
299
			
300
			angular.forEach(accessParams, function(param, pos){
301
	            if (param.name == 'baseUrl') {
302
	            	baseUrl = param.value
303
	            }
304
	            if (param.name == 'set') {
305
	            	$scope.selectedSets = param.value.split(",");
306
	            }
307
			});
308
			
309
			if (!baseUrl) {
310
				$scope.showError("baseUrl param is missing");
311
				return;
312
			}
313

  
314
			$scope.showSpinner();
315
			$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
316
	        $http.post("listValidValuesForParam.do", $.param({
317
	        	'protocol' : 'oai',
318
	        	'param'    : 'set',
319
	        	'baseUrl'  : baseUrl
320
	        })).success(function(data) {
321
				$scope.hideSpinner();
322
	        	$scope.currentSets = data;
323
	        	angular.forEach($scope.currentSets, function(curr, pos1) {
324
		        	angular.forEach($scope.selectedSets, function(sel, pos2) {
325
		        		if (curr.id.trim() == sel.trim()) {
326
		        			curr.selected = true;
327
		        		}
328
		        	});
329
				});
330
	        }).error(function() {
331
				$scope.hideSpinner();
332
				$scope.showError("baseUrl param is missing");
333
			});
334
	        
335
		};
336
		
337
		
338
		$scope.verifyMetaWf = function(ds, wf) {
339
			var compliance = '';
340
			var type = '';
341
			angular.forEach(ds.commonParams, function(p,pos) {
342
	        	if (p.id == 'compliance') {
343
	        		compliance = p.value;
344
	        	}
345
	        	if (p.id == 'typology') {
346
	        		type = p.value;
347
	        	}
348
			});
349
			
350
			return (compliance && type && $scope.isValidTerm(compliance, wf.compliances) && $scope.isValidTerm(type, wf.ifaceTypes)); 
351
		}
352

  
353
		$scope.isValidTerm = function(term, list) {
354
			
355
			if (list.length == 0) {
356
				return true;
357
			}
358
			var res = false;
359
			angular.forEach(list, function(curr,pos) {
360
	        	if (term.lastIndexOf(curr, 0) === 0) { // implementation of term.startsWith(curr)
361
	        		res = true;
362
	        	}
363
			});
364
			return res;
365
		}
366

  
367
		$scope.overrideApiCompliance = function(level) {
368
			$scope.showSpinner();
369
			$http.get('repoApiCompliance.update?id=' + $scope.currentRepoApi.repoId + '&iface=' + $scope.currentRepoApi.id + '&compliance=' + level)
370
	        .success(
371
	        		function(data) {
372
	        			$scope.hideSpinner();
373
	        			$scope.showNotification('Api correctly updated !');
374
	        			$scope.loadApi(); 
375
	        		}
376
	        ).error(
377
	        		function() {
378
	        			$scope.showError('Something really bad must have happened to our fellow hamster..');
379
	        			$scope.hideSpinner();
380
	        		}
381
	        );
382
		}
383
		
384
		$scope.resetApiCompliance = function() {
385
			$scope.showSpinner();
386
			$http.get('repoApiCompliance.reset?id=' + $scope.currentRepoApi.repoId + '&iface=' + $scope.currentRepoApi.id)
387
	        .success(
388
	        		function(data) {
389
	        			$scope.hideSpinner();
390
	        			$scope.showNotification('Api correctly updated !');
391
	        			$scope.loadApi(); 
392
	        		}
393
	        ).error(
394
	        		function() {
395
	        			$scope.showError('Something really bad must have happened to our fellow hamster..');
396
	        			$scope.hideSpinner();
397
	        		}
398
	        );
399
		}
400
				
401
    	$scope.loadApi();
402
	}
403
		
404
 ]);
405

  
modules/dnet-modular-repositories-ui/tags/dnet-modular-repositories-ui-4.0.6/src/main/java/eu/dnetlib/functionality/modular/ui/repositories/RepoApisEntryPointController.java
1
package eu.dnetlib.functionality.modular.ui.repositories;
2

  
3
import java.io.StringReader;
4
import java.util.ArrayList;
5
import java.util.Collections;
6
import java.util.List;
7
import java.util.Set;
8

  
9
import javax.annotation.Resource;
10
import javax.servlet.http.HttpServletRequest;
11
import javax.servlet.http.HttpServletResponse;
12

  
13
import org.dom4j.Document;
14
import org.dom4j.Node;
15
import org.dom4j.io.SAXReader;
16
import org.springframework.beans.factory.annotation.Required;
17
import org.springframework.ui.ModelMap;
18

  
19
import com.google.common.base.Splitter;
20
import com.google.common.collect.Lists;
21
import com.google.common.collect.Sets;
22
import com.google.gson.Gson;
23

  
24
import eu.dnetlib.enabling.datasources.rmi.DatasourceManagerService;
25
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
26
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
27
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
28
import eu.dnetlib.functionality.modular.ui.ModuleEntryPoint;
29
import eu.dnetlib.miscutils.collections.Pair;
30

  
31
public class RepoApisEntryPointController extends ModuleEntryPoint {
32

  
33
	@Resource
34
	private UniqueServiceLocator serviceLocator;
35

  
36
	@Resource
37
	private RepoUIUtils repoUIUtils;
38

  
39
	private String compatibilityLevelsVocabulary;
40

  
41
	private String validatorAddress;
42
	private String validatorServiceAddress;
43

  
44
	public class RepoHIWorkflow implements Comparable<RepoHIWorkflow> {
45

  
46
		private String id;
47
		private String name;
48
		private Set<String> ifaceTypes;
49
		private Set<String> compliances;
50
		private List<Pair<String, String>> fields;
51

  
52
		/**
53
		 * Instantiates a new repo hi workflow.
54
		 *
55
		 * @param id
56
		 *            the id
57
		 * @param name
58
		 *            the name
59
		 * @param ifaceTypes
60
		 *            the iface types
61
		 * @param compliances
62
		 *            the compliances
63
		 * @param fields
64
		 *            the fields
65
		 */
66
		public RepoHIWorkflow(final String id, final String name, final Set<String> ifaceTypes, final Set<String> compliances,
67
				final List<Pair<String, String>> fields) {
68
			super();
69
			this.id = id;
70
			this.name = name;
71
			this.ifaceTypes = ifaceTypes;
72
			this.compliances = compliances;
73
			this.fields = fields;
74
		}
75

  
76
		public String getId() {
77
			return id;
78
		}
79

  
80
		public String getName() {
81
			return name;
82
		}
83

  
84
		public Set<String> getIfaceTypes() {
85
			return ifaceTypes;
86
		}
87

  
88
		public Set<String> getCompliances() {
89
			return compliances;
90
		}
91

  
92
		@Override
93
		public int compareTo(final RepoHIWorkflow o) {
94
			return getName().compareTo(o.getName());
95
		}
96

  
97
		/**
98
		 * @return the fields
99
		 */
100
		public List<Pair<String, String>> getFields() {
101
			return fields;
102
		}
103

  
104
		/**
105
		 * @param fields
106
		 *            the fields to set
107
		 */
108
		public void setFields(final List<Pair<String, String>> fields) {
109
			this.fields = fields;
110
		}
111

  
112
	}
113

  
114
	private RepoHIWorkflow parseQuery(final String input) {
115
		final SAXReader reader = new SAXReader();
116
		try {
117
			final Document doc = reader.read(new StringReader(input));
118

  
119
			final String id = doc.valueOf("//id");
120
			final String name = doc.valueOf("//name");
121
			final String type = doc.valueOf("//types");
122
			final String compliance = doc.valueOf("//compliances");
123
			final Set<String> ifcTypes = Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().split(type));
124
			final Set<String> compliances = Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().split(compliance));
125

  
126
			final List<Pair<String, String>> fields = new ArrayList<Pair<String, String>>();
127
			for (final Object o : doc.selectNodes(".//FIELD")) {
128
				final Node currentNode = (Node) o;
129
				final String key = currentNode.valueOf("@name");
130
				final String value = currentNode.getText();
131
				fields.add(new Pair<String, String>(key, value));
132
			}
133
			return new RepoHIWorkflow(id, name, ifcTypes, compliances, fields);
134
		} catch (final Exception e) {
135
			return null;
136
		}
137
	}
138

  
139
	private List<RepoHIWorkflow> listRepoHIWorkflows() throws ISLookUpException {
140

  
141
		final String xquery =
142
				"for $x in collection('/db/DRIVER/WorkflowDSResources/WorkflowDSResourceType') where $x//WORKFLOW_TYPE='REPO_HI' return <result> <id>{$x//RESOURCE_IDENTIFIER/@value/string()}</id> <name>{$x//WORKFLOW_NAME/text()}</name> <types>{$x//PARAM[@name='expectedInterfaceTypologyPrefixes']/text()}</types> <compliances>{$x//PARAM[@name='expectedCompliancePrefixes']/text()}</compliances> {$x//FIELD} </result>";
143
		final List<RepoHIWorkflow> list = Lists.newArrayList();
144
		for (final String s : serviceLocator.getService(ISLookUpService.class).quickSearchProfile(xquery)) {
145
			final RepoHIWorkflow repoHiInfo = parseQuery(s);
146
			if (repoHiInfo != null) {
147
				list.add(repoHiInfo);
148
			}
149
		}
150
		Collections.sort(list);
151
		return list;
152
	}
153

  
154
	@Override
155
	protected void initialize(final ModelMap map, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
156
		final Gson gson = new Gson();
157
		map.addAttribute("availableRepohiWfs", gson.toJson(listRepoHIWorkflows()));
158
		map.addAttribute("compatibilityLevels", gson.toJson(repoUIUtils.fetchVocabularyTerms(getCompatibilityLevelsVocabulary())));
159
		map.addAttribute("browseFields", gson.toJson(serviceLocator.getService(DatasourceManagerService.class).listBrowsableFields()));
160
		map.addAttribute("validatorAddress", getValidatorAddress());
161
		map.addAttribute("validatorServiceAddress", getValidatorServiceAddress());
162
	}
163

  
164
	public String getCompatibilityLevelsVocabulary() {
165
		return compatibilityLevelsVocabulary;
166
	}
167

  
168
	@Required
169
	public void setCompatibilityLevelsVocabulary(final String compatibilityLevelsVocabulary) {
170
		this.compatibilityLevelsVocabulary = compatibilityLevelsVocabulary;
171
	}
172

  
173
	public String getValidatorAddress() {
174
		return validatorAddress;
175
	}
176

  
177
	@Required
178
	public void setValidatorAddress(final String validatorAddress) {
179
		this.validatorAddress = validatorAddress;
180
	}
181

  
182
	public String getValidatorServiceAddress() {
183
		return validatorServiceAddress;
184
	}
185

  
186
	@Required
187
	public void setValidatorServiceAddress(final String validatorServiceAddress) {
188
		this.validatorServiceAddress = validatorServiceAddress;
189
	}
190

  
191
}
modules/dnet-modular-repositories-ui/tags/dnet-modular-repositories-ui-4.0.6/src/main/java/eu/dnetlib/functionality/modular/ui/repositories/RepoUIUtils.java
1
package eu.dnetlib.functionality.modular.ui.repositories;
2

  
3
import java.io.StringReader;
4
import java.util.Collections;
5
import java.util.List;
6
import java.util.Map;
7
import java.util.Set;
8

  
9
import javax.annotation.Resource;
10

  
11
import org.antlr.stringtemplate.StringTemplate;
12
import org.apache.commons.io.IOUtils;
13
import org.apache.commons.lang.StringEscapeUtils;
14
import org.apache.commons.lang.math.NumberUtils;
15
import org.apache.commons.logging.Log;
16
import org.apache.commons.logging.LogFactory;
17
import org.dom4j.Document;
18
import org.dom4j.Node;
19
import org.dom4j.io.SAXReader;
20
import org.springframework.core.io.ClassPathResource;
21

  
22
import com.google.common.collect.Lists;
23
import com.google.common.collect.Maps;
24
import com.google.common.collect.Sets;
25

  
26
import eu.dnetlib.data.collector.rmi.CollectorService;
27
import eu.dnetlib.data.collector.rmi.ProtocolDescriptor;
28
import eu.dnetlib.data.collector.rmi.ProtocolParameter;
29
import eu.dnetlib.enabling.datasources.rmi.DatasourceConstants;
30
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
31
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
32
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
33
import eu.dnetlib.functionality.modular.ui.repositories.objects.RepoInterfaceEntry;
34
import eu.dnetlib.functionality.modular.ui.repositories.objects.RepoMetaWfEntry;
35
import eu.dnetlib.functionality.modular.ui.repositories.objects.SimpleParamEntry;
36
import eu.dnetlib.functionality.modular.ui.repositories.objects.VocabularyEntry;
37
import eu.dnetlib.msro.workflows.util.WorkflowsConstants.WorkflowStatus;
38

  
39
public class RepoUIUtils {
40

  
41
	@Resource
42
	private UniqueServiceLocator serviceLocator;
43

  
44
	private ClassPathResource getRepoApiQueryTmpl = new ClassPathResource("/eu/dnetlib/functionality/modular/ui/repositories/templates/getRepoApi.xquery.st");
45

  
46
	private static final Log log = LogFactory.getLog(RepoUIUtils.class);
47

  
48
	private Map<String, List<ProtocolParameter>> parametersMap = Maps.newHashMap();
49

  
50
	public RepoInterfaceEntry getApi(final String repoId, final String ifaceId) throws Exception {
51
		final RepoInterfaceEntry ifc = new RepoInterfaceEntry();
52

  
53
		final StringTemplate st = new StringTemplate(IOUtils.toString(getRepoApiQueryTmpl.getInputStream()));
54
		st.setAttribute("dsId", repoId);
55
		st.setAttribute("ifaceId", ifaceId);
56

  
57
		final String query = st.toString();
58

  
59
		final SAXReader reader = new SAXReader();
60

  
61
		final String s = serviceLocator.getService(ISLookUpService.class).getResourceProfileByQuery(query);
62

  
63
		final Document doc = reader.read(new StringReader(s));
64

  
65
		ifc.setId(doc.valueOf("/api/id"));
66
		ifc.setLabel(doc.valueOf("/api/label"));
67
		ifc.setRepoId(doc.valueOf("/api/repo/@id"));
68
		ifc.setRepoName(StringEscapeUtils.unescapeHtml(doc.valueOf("/api/repo")));
69
		ifc.setRepoCountry(doc.valueOf("/api/repo/@country"));
70
		ifc.setRepoPrefix(doc.valueOf("/api/repo/@prefix"));
71

  
72
		final String protocol = doc.valueOf("/api/protocol");
73
		ifc.setProtocol(protocol);
74

  
75
		final Set<String> toVerifyParams = getParameterNamesForProtocol(ifc.getProtocol());
76
		for (Object o : doc.selectNodes("/api/commonParams/param")) {
77
			final Node n = (Node) o;
78
			ifc.getCommonParams().add(new SimpleParamEntry(n.valueOf("@name"), n.getText()));
79
		}
80

  
81
		log.debug("****** " + toVerifyParams);
82
		for (Object o : doc.selectNodes("/api/accessParams/param")) {
83
			final Node n = (Node) o;
84
			final String pname = n.valueOf("@name");
85
			if (toVerifyParams.contains(pname)) {
86
				ifc.getAccessParams().add(new SimpleParamEntry(pname, n.getText()));
87
				toVerifyParams.remove(pname);
88
			} else {
89
				log.warn("Invalid param [" + pname + "] for protocol " + protocol + " in repo " + repoId);
90
			}
91
		}
92
		for (String pname : toVerifyParams) {
93
			ifc.getAccessParams().add(new SimpleParamEntry(pname, ""));
94
			log.info("Adding missing param [" + pname + "] for protocol " + protocol + " in repo " + repoId);
95
		}
96

  
97
		for (Object o : doc.selectNodes("/api/extraFields/field")) {
98
			final Node n = (Node) o;
99
			final String name = n.valueOf("@name");
100
			final String value = n.getText();
101
			if (name.equalsIgnoreCase(DatasourceConstants.OVERRIDING_COMPLIANCE_FIELD)) {
102
				for (SimpleParamEntry e : ifc.getCommonParams()) {
103
					if (e.getName().equals("compliance")) {
104
						// The original compliance (assigned by the validator) is stored in otherValue
105
						e.setOtherValue(e.getValue());
106
						e.setValue(value);
107
					}
108
				}
109
			} else if (name.equalsIgnoreCase("last_aggregation_date")) {
110
				ifc.setAggrDate(value);
111
			} else if (name.equalsIgnoreCase("last_aggregation_total")) {
112
				ifc.setAggrTotal(NumberUtils.toInt(value, 0));
113
			} else if (name.equalsIgnoreCase("last_aggregation_mdId")) {
114
				ifc.setAggrMdId(value);
115
			} else if (name.equalsIgnoreCase("last_collection_date")) {
116
				ifc.setCollDate(value);
117
			} else if (name.equalsIgnoreCase("last_collection_total")) {
118
				ifc.setCollTotal(NumberUtils.toInt(value, 0));
119
			} else if (name.equalsIgnoreCase("last_collection_mdId")) {
120
				ifc.setCollMdId(value);
121
			} else if (name.equalsIgnoreCase("last_download_date")) {
122
				ifc.setDownloadDate(value);
123
			} else if (name.equalsIgnoreCase("last_download_total")) {
124
				ifc.setDownloadTotal(NumberUtils.toInt(value, 0));
125
			} else if (name.equalsIgnoreCase("last_download_objId")) {
126
				ifc.setDownloadObjId(value);
127
			} else {
128
				ifc.getOtherParams().add(new SimpleParamEntry(name, value));
129
			}
130
		}
131

  
132
		for (Object o : doc.selectNodes("//metaWF")) {
133
			final Node n = (Node) o;
134

  
135
			final String id = n.valueOf("./id");
136
			final String name = n.valueOf("./name");
137
			final String status = n.valueOf("./status");
138
			final String repoByeWfId = n.valueOf("./destroyWorkflow");
139

  
140
			int progress = 0;
141
			try {
142
				switch (WorkflowStatus.valueOf(status)) {
143
				case MISSING:
144
					progress = 0;
145
					break;
146
				case ASSIGNED:
147
					progress = 25;
148
					break;
149
				case WAIT_SYS_SETTINGS:
150
					progress = 50;
151
					break;
152
				case WAIT_USER_SETTINGS:
153
					progress = 75;
154
					break;
155
				case EXECUTABLE:
156
					progress = 100;
157
					break;
158
				}
159
			} catch (Exception e) {
160
				progress = 0;
161
			}
162
			ifc.getMetaWFs().add(new RepoMetaWfEntry(id, name, status, repoByeWfId, progress));
163
		}
164

  
165
		return ifc;
166
	}
167

  
168
	public List<VocabularyEntry> fetchVocabularyTerms(final String voc) throws ISLookUpException {
169
		final String xquery = "for $x in collection('/db/DRIVER/VocabularyDSResources/VocabularyDSResourceType')[.//VOCABULARY_NAME/@code = '"
170
				+ voc.trim() + "']//TERM return concat($x/@code, ' @@@ ', $x/@english_name)";
171

  
172
		final List<VocabularyEntry> list = Lists.newArrayList();
173
		for (String s : serviceLocator.getService(ISLookUpService.class).quickSearchProfile(xquery)) {
174
			final String[] arr = s.split("@@@");
175
			list.add(new VocabularyEntry(arr[0].trim(), arr[1].trim()));
176
		}
177
		Collections.sort(list);
178

  
179
		return list;
180
	}
181

  
182
	private Set<String> getParameterNamesForProtocol(final String protocol) {
183
		if (parametersMap.isEmpty()) {
184
			for (ProtocolDescriptor d : serviceLocator.getService(CollectorService.class).listProtocols()) {
185
				parametersMap.put(d.getName().toLowerCase(), d.getParams());
186
			}
187
		}
188
		final Set<String> res = Sets.newHashSet();
189
		if (parametersMap.containsKey(protocol.toLowerCase())) {
190
			res.add("baseUrl");
191
			for (ProtocolParameter p : parametersMap.get(protocol.toLowerCase())) {
192
				res.add(p.getName());
193
			}
194
		}
195

  
196
		return res;
197
	}
198

  
199
}
modules/dnet-modular-repositories-ui/tags/dnet-modular-repositories-ui-4.0.6/src/main/resources/eu/dnetlib/web/resources/js/chosen/chosen.jquery.js
1
/*!
2
Chosen, a Select Box Enhancer for jQuery and Prototype
3
by Patrick Filler for Harvest, http://getharvest.com
4

  
5
Version 1.4.2
6
Full source at https://github.com/harvesthq/chosen
7
Copyright (c) 2011-2015 Harvest http://getharvest.com
8

  
9
MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md
10
This file is generated by `grunt build`, do not edit it by hand.
11
*/
12

  
13
(function() {
14
  var $, AbstractChosen, Chosen, SelectParser, _ref,
15
    __hasProp = {}.hasOwnProperty,
16
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
17

  
18
  SelectParser = (function() {
19
    function SelectParser() {
20
      this.options_index = 0;
21
      this.parsed = [];
22
    }
23

  
24
    SelectParser.prototype.add_node = function(child) {
25
      if (child.nodeName.toUpperCase() === "OPTGROUP") {
26
        return this.add_group(child);
27
      } else {
28
        return this.add_option(child);
29
      }
30
    };
31

  
32
    SelectParser.prototype.add_group = function(group) {
33
      var group_position, option, _i, _len, _ref, _results;
34
      group_position = this.parsed.length;
35
      this.parsed.push({
36
        array_index: group_position,
37
        group: true,
38
        label: this.escapeExpression(group.label),
39
        title: group.title ? group.title : void 0,
40
        children: 0,
41
        disabled: group.disabled,
42
        classes: group.className
43
      });
44
      _ref = group.childNodes;
45
      _results = [];
46
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
47
        option = _ref[_i];
48
        _results.push(this.add_option(option, group_position, group.disabled));
49
      }
50
      return _results;
51
    };
52

  
53
    SelectParser.prototype.add_option = function(option, group_position, group_disabled) {
54
      if (option.nodeName.toUpperCase() === "OPTION") {
55
        if (option.text !== "") {
56
          if (group_position != null) {
57
            this.parsed[group_position].children += 1;
58
          }
59
          this.parsed.push({
60
            array_index: this.parsed.length,
61
            options_index: this.options_index,
62
            value: option.value,
63
            text: option.text,
64
            html: option.innerHTML,
65
            title: option.title ? option.title : void 0,
66
            selected: option.selected,
67
            disabled: group_disabled === true ? group_disabled : option.disabled,
68
            group_array_index: group_position,
69
            group_label: group_position != null ? this.parsed[group_position].label : null,
70
            classes: option.className,
71
            style: option.style.cssText
72
          });
73
        } else {
74
          this.parsed.push({
75
            array_index: this.parsed.length,
76
            options_index: this.options_index,
77
            empty: true
78
          });
79
        }
80
        return this.options_index += 1;
81
      }
82
    };
83

  
84
    SelectParser.prototype.escapeExpression = function(text) {
85
      var map, unsafe_chars;
86
      if ((text == null) || text === false) {
87
        return "";
88
      }
89
      if (!/[\&\<\>\"\'\`]/.test(text)) {
90
        return text;
91
      }
92
      map = {
93
        "<": "&lt;",
94
        ">": "&gt;",
95
        '"': "&quot;",
96
        "'": "&#x27;",
97
        "`": "&#x60;"
98
      };
99
      unsafe_chars = /&(?!\w+;)|[\<\>\"\'\`]/g;
100
      return text.replace(unsafe_chars, function(chr) {
101
        return map[chr] || "&amp;";
102
      });
103
    };
104

  
105
    return SelectParser;
106

  
107
  })();
108

  
109
  SelectParser.select_to_array = function(select) {
110
    var child, parser, _i, _len, _ref;
111
    parser = new SelectParser();
112
    _ref = select.childNodes;
113
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
114
      child = _ref[_i];
115
      parser.add_node(child);
116
    }
117
    return parser.parsed;
118
  };
119

  
120
  AbstractChosen = (function() {
121
    function AbstractChosen(form_field, options) {
122
      this.form_field = form_field;
123
      this.options = options != null ? options : {};
124
      if (!AbstractChosen.browser_is_supported()) {
125
        return;
126
      }
127
      this.is_multiple = this.form_field.multiple;
128
      this.set_default_text();
129
      this.set_default_values();
130
      this.setup();
131
      this.set_up_html();
132
      this.register_observers();
133
      this.on_ready();
134
    }
135

  
136
    AbstractChosen.prototype.set_default_values = function() {
137
      var _this = this;
138
      this.click_test_action = function(evt) {
139
        return _this.test_active_click(evt);
140
      };
141
      this.activate_action = function(evt) {
142
        return _this.activate_field(evt);
143
      };
144
      this.active_field = false;
145
      this.mouse_on_container = false;
146
      this.results_showing = false;
147
      this.result_highlighted = null;
148
      this.allow_single_deselect = (this.options.allow_single_deselect != null) && (this.form_field.options[0] != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false;
149
      this.disable_search_threshold = this.options.disable_search_threshold || 0;
150
      this.disable_search = this.options.disable_search || false;
151
      this.enable_split_word_search = this.options.enable_split_word_search != null ? this.options.enable_split_word_search : true;
152
      this.group_search = this.options.group_search != null ? this.options.group_search : true;
153
      this.search_contains = this.options.search_contains || false;
154
      this.single_backstroke_delete = this.options.single_backstroke_delete != null ? this.options.single_backstroke_delete : true;
155
      this.max_selected_options = this.options.max_selected_options || Infinity;
156
      this.inherit_select_classes = this.options.inherit_select_classes || false;
157
      this.display_selected_options = this.options.display_selected_options != null ? this.options.display_selected_options : true;
158
      this.display_disabled_options = this.options.display_disabled_options != null ? this.options.display_disabled_options : true;
159
      return this.include_group_label_in_selected = this.options.include_group_label_in_selected || false;
160
    };
161

  
162
    AbstractChosen.prototype.set_default_text = function() {
163
      if (this.form_field.getAttribute("data-placeholder")) {
164
        this.default_text = this.form_field.getAttribute("data-placeholder");
165
      } else if (this.is_multiple) {
166
        this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || AbstractChosen.default_multiple_text;
167
      } else {
168
        this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || AbstractChosen.default_single_text;
169
      }
170
      return this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || AbstractChosen.default_no_result_text;
171
    };
172

  
173
    AbstractChosen.prototype.choice_label = function(item) {
174
      if (this.include_group_label_in_selected && (item.group_label != null)) {
175
        return "<b class='group-name'>" + item.group_label + "</b>" + item.html;
176
      } else {
177
        return item.html;
178
      }
179
    };
180

  
181
    AbstractChosen.prototype.mouse_enter = function() {
182
      return this.mouse_on_container = true;
183
    };
184

  
185
    AbstractChosen.prototype.mouse_leave = function() {
186
      return this.mouse_on_container = false;
187
    };
188

  
189
    AbstractChosen.prototype.input_focus = function(evt) {
190
      var _this = this;
191
      if (this.is_multiple) {
192
        if (!this.active_field) {
193
          return setTimeout((function() {
194
            return _this.container_mousedown();
195
          }), 50);
196
        }
197
      } else {
198
        if (!this.active_field) {
199
          return this.activate_field();
200
        }
201
      }
202
    };
203

  
204
    AbstractChosen.prototype.input_blur = function(evt) {
205
      var _this = this;
206
      if (!this.mouse_on_container) {
207
        this.active_field = false;
208
        return setTimeout((function() {
209
          return _this.blur_test();
210
        }), 100);
211
      }
212
    };
213

  
214
    AbstractChosen.prototype.results_option_build = function(options) {
215
      var content, data, _i, _len, _ref;
216
      content = '';
217
      _ref = this.results_data;
218
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
219
        data = _ref[_i];
220
        if (data.group) {
221
          content += this.result_add_group(data);
222
        } else {
223
          content += this.result_add_option(data);
224
        }
225
        if (options != null ? options.first : void 0) {
226
          if (data.selected && this.is_multiple) {
227
            this.choice_build(data);
228
          } else if (data.selected && !this.is_multiple) {
229
            this.single_set_selected_text(this.choice_label(data));
230
          }
231
        }
232
      }
233
      return content;
234
    };
235

  
236
    AbstractChosen.prototype.result_add_option = function(option) {
237
      var classes, option_el;
238
      if (!option.search_match) {
239
        return '';
240
      }
241
      if (!this.include_option_in_results(option)) {
242
        return '';
243
      }
244
      classes = [];
245
      if (!option.disabled && !(option.selected && this.is_multiple)) {
246
        classes.push("active-result");
247
      }
248
      if (option.disabled && !(option.selected && this.is_multiple)) {
249
        classes.push("disabled-result");
250
      }
251
      if (option.selected) {
252
        classes.push("result-selected");
253
      }
254
      if (option.group_array_index != null) {
255
        classes.push("group-option");
256
      }
257
      if (option.classes !== "") {
258
        classes.push(option.classes);
259
      }
260
      option_el = document.createElement("li");
261
      option_el.className = classes.join(" ");
262
      option_el.style.cssText = option.style;
263
      option_el.setAttribute("data-option-array-index", option.array_index);
264
      option_el.innerHTML = option.search_text;
265
      if (option.title) {
266
        option_el.title = option.title;
267
      }
268
      return this.outerHTML(option_el);
269
    };
270

  
271
    AbstractChosen.prototype.result_add_group = function(group) {
272
      var classes, group_el;
273
      if (!(group.search_match || group.group_match)) {
274
        return '';
275
      }
276
      if (!(group.active_options > 0)) {
277
        return '';
278
      }
279
      classes = [];
280
      classes.push("group-result");
281
      if (group.classes) {
282
        classes.push(group.classes);
283
      }
284
      group_el = document.createElement("li");
285
      group_el.className = classes.join(" ");
286
      group_el.innerHTML = group.search_text;
287
      if (group.title) {
288
        group_el.title = group.title;
289
      }
290
      return this.outerHTML(group_el);
291
    };
292

  
293
    AbstractChosen.prototype.results_update_field = function() {
294
      this.set_default_text();
295
      if (!this.is_multiple) {
296
        this.results_reset_cleanup();
297
      }
298
      this.result_clear_highlight();
299
      this.results_build();
300
      if (this.results_showing) {
301
        return this.winnow_results();
302
      }
303
    };
304

  
305
    AbstractChosen.prototype.reset_single_select_options = function() {
306
      var result, _i, _len, _ref, _results;
307
      _ref = this.results_data;
308
      _results = [];
309
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
310
        result = _ref[_i];
311
        if (result.selected) {
312
          _results.push(result.selected = false);
313
        } else {
314
          _results.push(void 0);
315
        }
316
      }
317
      return _results;
318
    };
319

  
320
    AbstractChosen.prototype.results_toggle = function() {
321
      if (this.results_showing) {
322
        return this.results_hide();
323
      } else {
324
        return this.results_show();
325
      }
326
    };
327

  
328
    AbstractChosen.prototype.results_search = function(evt) {
329
      if (this.results_showing) {
330
        return this.winnow_results();
331
      } else {
332
        return this.results_show();
333
      }
334
    };
335

  
336
    AbstractChosen.prototype.winnow_results = function() {
337
      var escapedSearchText, option, regex, results, results_group, searchText, startpos, text, zregex, _i, _len, _ref;
338
      this.no_results_clear();
339
      results = 0;
340
      searchText = this.get_search_text();
341
      escapedSearchText = searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
342
      zregex = new RegExp(escapedSearchText, 'i');
343
      regex = this.get_search_regex(escapedSearchText);
344
      _ref = this.results_data;
345
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
346
        option = _ref[_i];
347
        option.search_match = false;
348
        results_group = null;
349
        if (this.include_option_in_results(option)) {
350
          if (option.group) {
351
            option.group_match = false;
352
            option.active_options = 0;
353
          }
354
          if ((option.group_array_index != null) && this.results_data[option.group_array_index]) {
355
            results_group = this.results_data[option.group_array_index];
356
            if (results_group.active_options === 0 && results_group.search_match) {
357
              results += 1;
358
            }
359
            results_group.active_options += 1;
360
          }
361
          option.search_text = option.group ? option.label : option.html;
362
          if (!(option.group && !this.group_search)) {
363
            option.search_match = this.search_string_match(option.search_text, regex);
364
            if (option.search_match && !option.group) {
365
              results += 1;
366
            }
367
            if (option.search_match) {
368
              if (searchText.length) {
369
                startpos = option.search_text.search(zregex);
370
                text = option.search_text.substr(0, startpos + searchText.length) + '</em>' + option.search_text.substr(startpos + searchText.length);
371
                option.search_text = text.substr(0, startpos) + '<em>' + text.substr(startpos);
372
              }
373
              if (results_group != null) {
374
                results_group.group_match = true;
375
              }
376
            } else if ((option.group_array_index != null) && this.results_data[option.group_array_index].search_match) {
377
              option.search_match = true;
378
            }
379
          }
380
        }
381
      }
382
      this.result_clear_highlight();
383
      if (results < 1 && searchText.length) {
384
        this.update_results_content("");
385
        return this.no_results(searchText);
386
      } else {
387
        this.update_results_content(this.results_option_build());
388
        return this.winnow_results_set_highlight();
389
      }
390
    };
391

  
392
    AbstractChosen.prototype.get_search_regex = function(escaped_search_string) {
393
      var regex_anchor;
394
      regex_anchor = this.search_contains ? "" : "^";
395
      return new RegExp(regex_anchor + escaped_search_string, 'i');
396
    };
397

  
398
    AbstractChosen.prototype.search_string_match = function(search_string, regex) {
399
      var part, parts, _i, _len;
400
      if (regex.test(search_string)) {
401
        return true;
402
      } else if (this.enable_split_word_search && (search_string.indexOf(" ") >= 0 || search_string.indexOf("[") === 0)) {
403
        parts = search_string.replace(/\[|\]/g, "").split(" ");
404
        if (parts.length) {
405
          for (_i = 0, _len = parts.length; _i < _len; _i++) {
406
            part = parts[_i];
407
            if (regex.test(part)) {
408
              return true;
409
            }
410
          }
411
        }
412
      }
413
    };
414

  
415
    AbstractChosen.prototype.choices_count = function() {
416
      var option, _i, _len, _ref;
417
      if (this.selected_option_count != null) {
418
        return this.selected_option_count;
419
      }
420
      this.selected_option_count = 0;
421
      _ref = this.form_field.options;
422
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
423
        option = _ref[_i];
424
        if (option.selected) {
425
          this.selected_option_count += 1;
426
        }
427
      }
428
      return this.selected_option_count;
429
    };
430

  
431
    AbstractChosen.prototype.choices_click = function(evt) {
432
      evt.preventDefault();
433
      if (!(this.results_showing || this.is_disabled)) {
434
        return this.results_show();
435
      }
436
    };
437

  
438
    AbstractChosen.prototype.keyup_checker = function(evt) {
439
      var stroke, _ref;
440
      stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
441
      this.search_field_scale();
442
      switch (stroke) {
443
        case 8:
444
          if (this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0) {
445
            return this.keydown_backstroke();
446
          } else if (!this.pending_backstroke) {
447
            this.result_clear_highlight();
448
            return this.results_search();
449
          }
450
          break;
451
        case 13:
452
          evt.preventDefault();
453
          if (this.results_showing) {
454
            return this.result_select(evt);
455
          }
456
          break;
457
        case 27:
458
          if (this.results_showing) {
459
            this.results_hide();
460
          }
461
          return true;
462
        case 9:
463
        case 38:
464
        case 40:
465
        case 16:
466
        case 91:
467
        case 17:
468
          break;
469
        default:
470
          return this.results_search();
471
      }
472
    };
473

  
474
    AbstractChosen.prototype.clipboard_event_checker = function(evt) {
475
      var _this = this;
476
      return setTimeout((function() {
477
        return _this.results_search();
478
      }), 50);
479
    };
480

  
481
    AbstractChosen.prototype.container_width = function() {
482
      if (this.options.width != null) {
483
        return this.options.width;
484
      } else {
485
        return "" + this.form_field.offsetWidth + "px";
486
      }
487
    };
488

  
489
    AbstractChosen.prototype.include_option_in_results = function(option) {
490
      if (this.is_multiple && (!this.display_selected_options && option.selected)) {
491
        return false;
492
      }
493
      if (!this.display_disabled_options && option.disabled) {
494
        return false;
495
      }
496
      if (option.empty) {
497
        return false;
498
      }
499
      return true;
500
    };
501

  
502
    AbstractChosen.prototype.search_results_touchstart = function(evt) {
503
      this.touch_started = true;
504
      return this.search_results_mouseover(evt);
505
    };
506

  
507
    AbstractChosen.prototype.search_results_touchmove = function(evt) {
508
      this.touch_started = false;
509
      return this.search_results_mouseout(evt);
510
    };
511

  
512
    AbstractChosen.prototype.search_results_touchend = function(evt) {
513
      if (this.touch_started) {
514
        return this.search_results_mouseup(evt);
515
      }
516
    };
517

  
518
    AbstractChosen.prototype.outerHTML = function(element) {
519
      var tmp;
520
      if (element.outerHTML) {
521
        return element.outerHTML;
522
      }
523
      tmp = document.createElement("div");
524
      tmp.appendChild(element);
525
      return tmp.innerHTML;
526
    };
527

  
528
    AbstractChosen.browser_is_supported = function() {
529
      if (window.navigator.appName === "Microsoft Internet Explorer") {
530
        return document.documentMode >= 8;
531
      }
532
      if (/iP(od|hone)/i.test(window.navigator.userAgent)) {
533
        return false;
534
      }
535
      if (/Android/i.test(window.navigator.userAgent)) {
536
        if (/Mobile/i.test(window.navigator.userAgent)) {
537
          return false;
538
        }
539
      }
540
      return true;
541
    };
542

  
543
    AbstractChosen.default_multiple_text = "Select Some Options";
544

  
545
    AbstractChosen.default_single_text = "Select an Option";
546

  
547
    AbstractChosen.default_no_result_text = "No results match";
548

  
549
    return AbstractChosen;
550

  
551
  })();
552

  
553
  $ = jQuery;
554

  
555
  $.fn.extend({
556
    chosen: function(options) {
557
      if (!AbstractChosen.browser_is_supported()) {
558
        return this;
559
      }
560
      return this.each(function(input_field) {
561
        var $this, chosen;
562
        $this = $(this);
563
        chosen = $this.data('chosen');
564
        if (options === 'destroy' && chosen instanceof Chosen) {
565
          chosen.destroy();
566
        } else if (!(chosen instanceof Chosen)) {
567
          $this.data('chosen', new Chosen(this, options));
568
        }
569
      });
570
    }
571
  });
572

  
573
  Chosen = (function(_super) {
574
    __extends(Chosen, _super);
575

  
576
    function Chosen() {
577
      _ref = Chosen.__super__.constructor.apply(this, arguments);
578
      return _ref;
579
    }
580

  
581
    Chosen.prototype.setup = function() {
582
      this.form_field_jq = $(this.form_field);
583
      this.current_selectedIndex = this.form_field.selectedIndex;
584
      return this.is_rtl = this.form_field_jq.hasClass("chosen-rtl");
585
    };
586

  
587
    Chosen.prototype.set_up_html = function() {
588
      var container_classes, container_props;
589
      container_classes = ["chosen-container"];
590
      container_classes.push("chosen-container-" + (this.is_multiple ? "multi" : "single"));
591
      if (this.inherit_select_classes && this.form_field.className) {
592
        container_classes.push(this.form_field.className);
593
      }
594
      if (this.is_rtl) {
595
        container_classes.push("chosen-rtl");
596
      }
597
      container_props = {
598
        'class': container_classes.join(' '),
599
        'style': "width: " + (this.container_width()) + ";",
600
        'title': this.form_field.title
601
      };
602
      if (this.form_field.id.length) {
603
        container_props.id = this.form_field.id.replace(/[^\w]/g, '_') + "_chosen";
604
      }
605
      this.container = $("<div />", container_props);
606
      if (this.is_multiple) {
607
        this.container.html('<ul class="chosen-choices"><li class="search-field"><input type="text" value="' + this.default_text + '" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chosen-drop"><ul class="chosen-results"></ul></div>');
608
      } else {
609
        this.container.html('<a class="chosen-single chosen-default" tabindex="-1"><span>' + this.default_text + '</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" /></div><ul class="chosen-results"></ul></div>');
610
      }
611
      this.form_field_jq.hide().after(this.container);
612
      this.dropdown = this.container.find('div.chosen-drop').first();
613
      this.search_field = this.container.find('input').first();
614
      this.search_results = this.container.find('ul.chosen-results').first();
615
      this.search_field_scale();
616
      this.search_no_results = this.container.find('li.no-results').first();
617
      if (this.is_multiple) {
618
        this.search_choices = this.container.find('ul.chosen-choices').first();
619
        this.search_container = this.container.find('li.search-field').first();
620
      } else {
621
        this.search_container = this.container.find('div.chosen-search').first();
622
        this.selected_item = this.container.find('.chosen-single').first();
623
      }
624
      this.results_build();
625
      this.set_tab_index();
626
      return this.set_label_behavior();
627
    };
628

  
629
    Chosen.prototype.on_ready = function() {
630
      return this.form_field_jq.trigger("chosen:ready", {
631
        chosen: this
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff