gvsig-scripting / org.gvsig.scripting / trunk / org.gvsig.scripting / org.gvsig.scripting.app / org.gvsig.scripting.app.mainplugin / src / main / resources-plugin / scripting / lib / gvsig_2_0_0 / __init__.py @ 462
History | View | Annotate | Download (30.9 KB)
1 |
# -*- coding: utf-8 -*-
|
---|---|
2 |
#
|
3 |
# File: gvsig.py
|
4 |
#
|
5 |
# Copyright (c) 2011 by Model Driven Development sl and Antonio Carrasco Valero
|
6 |
#
|
7 |
# GNU General Public License (GPL)
|
8 |
#
|
9 |
# This program is free software; you can redistribute it and/or
|
10 |
# modify it under the terms of the GNU General Public License
|
11 |
# as published by the Free Software Foundation; either version 2
|
12 |
# of the License, or (at your option) any later version.
|
13 |
#
|
14 |
# This program is distributed in the hope that it will be useful,
|
15 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
16 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
17 |
# GNU General Public License for more details.
|
18 |
#
|
19 |
# You should have received a copy of the GNU General Public License
|
20 |
# along with this program; if not, write to the Free Software
|
21 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
22 |
# 02110-1301, USA.
|
23 |
#
|
24 |
#
|
25 |
|
26 |
"""
|
27 |
This module contains classes and functions to manage gvSIG Project,
|
28 |
gvSIG DocumentView, gvSIG TableDocument and Layers.
|
29 |
Also contais functions to manage vectorial data and other utility
|
30 |
functions
|
31 |
"""
|
32 |
|
33 |
__author__ = """Antonio Carrasco Valero
|
34 |
Model Driven Development sl and Antonio Carrasco Valero
|
35 |
<carrasco@modeldd.org>
|
36 |
Victor Acevedo Royer <vacevedor@gvsig.com>, <vacevedor@gmail.com>
|
37 |
"""
|
38 |
|
39 |
__docformat__ = 'plaintext'
|
40 |
|
41 |
from java.awt import Color |
42 |
|
43 |
from java.lang import RuntimeException |
44 |
from java.lang import Throwable |
45 |
import java.lang.IndexOutOfBoundsException |
46 |
|
47 |
from java.util.prefs import Preferences |
48 |
|
49 |
from org.gvsig.app import ApplicationLocator |
50 |
from org.gvsig.app.project.documents.view import ViewDocument |
51 |
from org.gvsig.app.project.documents.table import TableDocument |
52 |
|
53 |
from org.gvsig.fmap.crs import CRSFactory |
54 |
|
55 |
from org.gvsig.fmap.mapcontext import MapContextLocator |
56 |
from org.gvsig.fmap.mapcontext.layers import FLayers |
57 |
|
58 |
from org.gvsig.fmap.dal import DALLocator, DataTypes |
59 |
from org.gvsig.fmap.dal.feature import EditableFeature, \ |
60 |
EditableFeatureType, FeatureQueryOrder |
61 |
from org.gvsig.fmap.dal.feature.impl import DefaultEditableFeature |
62 |
|
63 |
from org.gvsig.fmap.geom import Geometry |
64 |
|
65 |
from org.gvsig.tools import ToolsLocator |
66 |
|
67 |
import thread |
68 |
import random |
69 |
|
70 |
|
71 |
def runTask(name, function, *args): |
72 |
manager = ToolsLocator.getTaskStatusManager() |
73 |
status = manager.createDefaultSimpleTaskStatus(name) |
74 |
status.add() |
75 |
args = list(args)
|
76 |
args.append(status) |
77 |
try:
|
78 |
thread.start_new_thread(function, tuple(args))
|
79 |
status.terminate() |
80 |
except Exception,e: |
81 |
status.abort() |
82 |
raise e
|
83 |
|
84 |
|
85 |
class WrapperToJava(object): |
86 |
"""Creates a wrapper that allows python object access to the Java object
|
87 |
properties and methods
|
88 |
"""
|
89 |
def __init__(self, javaobj): |
90 |
if javaobj == None: |
91 |
raise RuntimeException("Can't create "+ self.__class__.__name__) |
92 |
self._javaobj = javaobj
|
93 |
|
94 |
def __call__(self): |
95 |
return self._javaobj |
96 |
|
97 |
def __getattr__(self,name): |
98 |
return getattr(self._javaobj,name) |
99 |
|
100 |
class Project(WrapperToJava): |
101 |
"""Represents a gvSIG project (org.gvsig.app.project.DefaultProject)"""
|
102 |
|
103 |
def __init__(self, project): |
104 |
WrapperToJava.__init__(self, project)
|
105 |
|
106 |
def getView(self, name=None): |
107 |
"""
|
108 |
Returns active view, or view called 'name' or None
|
109 |
:param name: view name
|
110 |
:type name: string
|
111 |
"""
|
112 |
if name == None: |
113 |
try:
|
114 |
activeDocument = self.getActiveDocument()
|
115 |
if activeDocument == None: |
116 |
return None |
117 |
if isinstance(activeDocument, ViewDocument): |
118 |
return View(activeDocument)
|
119 |
except Exception, ex: |
120 |
raise Exception("%s"%repr(ex)) |
121 |
else:
|
122 |
views = self.getViews()
|
123 |
if len(views) >0: |
124 |
for view in views: |
125 |
if name == view.getName():
|
126 |
return View(view)
|
127 |
|
128 |
return None |
129 |
|
130 |
def getTable(self, name=None): |
131 |
"""
|
132 |
Returns active Table Document, or Table Document called 'name' or None
|
133 |
:param name: Table Document name
|
134 |
:type name: string
|
135 |
"""
|
136 |
if name == None: |
137 |
try:
|
138 |
activeDocument = self.getActiveDocument()
|
139 |
if activeDocument == None: |
140 |
return None |
141 |
if isinstance(activeDocument, TableDocument): |
142 |
return Table(activeDocument)
|
143 |
except Exception, ex: |
144 |
raise Exception("%s"%repr(ex)) |
145 |
else:
|
146 |
tables = self.getDocuments("project.document.table") |
147 |
if len(tables) >0: |
148 |
for table in tables: |
149 |
if name == table.getName():
|
150 |
return Table(table)
|
151 |
|
152 |
return None |
153 |
|
154 |
def getProjectionCode(self): |
155 |
"""Returns Project projection code name string. This value is the
|
156 |
projects default projection that is fixed in Preferences tool, View
|
157 |
options. It's used when no view projection is defined.
|
158 |
|
159 |
"""
|
160 |
return self.getProjection().getFullCode() |
161 |
|
162 |
|
163 |
class View(WrapperToJava): |
164 |
"""
|
165 |
Represents gvSIG view document
|
166 |
(org.gvsig.app.project.documents.view.DefaultViewDocument).
|
167 |
"""
|
168 |
def __init__(self,view): |
169 |
WrapperToJava.__init__(self,view)
|
170 |
|
171 |
def getLayer(self, name=None): |
172 |
"""
|
173 |
Returns one view layer. If name is None returns active
|
174 |
layer if the view has one, if name is not None returns layer called name
|
175 |
else returns None.
|
176 |
:param name: view name in Table Of Contents
|
177 |
:type name: string
|
178 |
:return: View
|
179 |
:return: None
|
180 |
"""
|
181 |
map = self.getMapContext();
|
182 |
if name == None: |
183 |
activeLayers = map.getLayers().getActives()
|
184 |
if len(activeLayers) != 1 : |
185 |
return None |
186 |
for layer in activeLayers: |
187 |
if not isinstance(layer, FLayers): |
188 |
return Layer(layer)
|
189 |
return None |
190 |
|
191 |
ls = self.getLayers()
|
192 |
for i in xrange(ls.getLayersCount()): |
193 |
l = ls.getLayer(i) |
194 |
if l.name == name:
|
195 |
return Layer(l)
|
196 |
|
197 |
return None |
198 |
|
199 |
def getMap(self): |
200 |
# org.gvsig.fmap.mapcontext.MapContext
|
201 |
"""Returns view mapContext"""
|
202 |
return self.getMapContext(); |
203 |
|
204 |
def addLayer(self, layer): |
205 |
"""
|
206 |
Adds a new layer to the view
|
207 |
:param layer: layer to add
|
208 |
:type layer: Layer
|
209 |
"""
|
210 |
if isinstance(layer, Layer): |
211 |
layer =layer() |
212 |
self.getMapContext().getLayers().addLayer(layer)
|
213 |
|
214 |
def getLayers(self): |
215 |
"""Returns iterable view layers set"""
|
216 |
map = self.getMapContext()
|
217 |
return Layers(map.getLayers()) |
218 |
|
219 |
def getGraphicsLayer(self): |
220 |
"""Returns view graphics layer
|
221 |
org.gvsig.fmap.mapcontext.layers.vectorial.impl.DefaultGraphicLayer
|
222 |
"""
|
223 |
return self.getMapContext().getGraphicsLayer() |
224 |
|
225 |
def getProjectionCode(self): |
226 |
"""Returns string view projection code name"""
|
227 |
return self.getProjection().getFullCode() |
228 |
|
229 |
def isProjected(self): |
230 |
"""Returns if view projection is projected."""
|
231 |
self.getProjection().isProjected()
|
232 |
|
233 |
class Layers(WrapperToJava): |
234 |
"""Iterable layers set
|
235 |
(org.gvsig.fmap.mapcontext.layers.FLayers)
|
236 |
"""
|
237 |
def __init__(self,layers): |
238 |
WrapperToJava.__init__(self, layers)
|
239 |
|
240 |
def __len__(self): |
241 |
return self.getLayersCount() |
242 |
|
243 |
def __getitem__(self, index): |
244 |
return self.getLayer(index) |
245 |
|
246 |
def __iter__(self): |
247 |
return LayersIterator(self) |
248 |
|
249 |
class LayersIterator(object): |
250 |
|
251 |
def __init__(self,layers): |
252 |
self.__layers = layers
|
253 |
self.__index = -1 |
254 |
|
255 |
def next(self): |
256 |
self.__index+=1 |
257 |
if self.__index >= self.__layers.getLayersCount() : |
258 |
raise StopIteration() |
259 |
return Layer(self.__layers.getLayer(self.__index)) |
260 |
|
261 |
class Store(WrapperToJava): |
262 |
"""Represents gvsig store. It's used as Table/Layer objects store
|
263 |
(org.gvsig.fmap.dal.feature.impl.DefaultFeatureStore)
|
264 |
"""
|
265 |
def __init__(self,store): |
266 |
WrapperToJava.__init__(self, store)
|
267 |
#self.data = None
|
268 |
self.fset = None |
269 |
|
270 |
def features(self, expresion = None, sortBy="", asc=True): |
271 |
"""Returns layer features set (FeatureSet class), with all layer features,
|
272 |
or selected featured if there are (could be empty feature set) or None if
|
273 |
gets an Exception.
|
274 |
:param expresion: filter to apply to the feature set to select
|
275 |
determinates features that match with expression
|
276 |
:type expresion: string
|
277 |
:param sortBy: name of attribute to sort
|
278 |
:type sortby: string
|
279 |
:param: asc: order
|
280 |
:type asc: boolean
|
281 |
:return: FeatureSet
|
282 |
"""
|
283 |
if expresion == None and sortBy =="": |
284 |
self.fset = self.getFeatureSet() |
285 |
else:
|
286 |
try:
|
287 |
application = ApplicationLocator.getManager() |
288 |
datamanager = application.getDataManager() |
289 |
query = self.createFeatureQuery()
|
290 |
if sortBy != "": |
291 |
order = FeatureQueryOrder() |
292 |
order.add(sortBy, asc) |
293 |
query.setOrder(order) |
294 |
if expresion != None: |
295 |
query.setFilter(datamanager.createExpresion(expresion)) |
296 |
self.fset = self.getFeatureSet(query) |
297 |
except Exception, e: |
298 |
return None |
299 |
|
300 |
return FeatureSet(self.fset) |
301 |
|
302 |
def edit(self): |
303 |
"""Set store in edition mode"""
|
304 |
if not self.isEditing(): |
305 |
self().edit()
|
306 |
|
307 |
def append(self, *valuesList, **values): |
308 |
"""
|
309 |
Creates a new feature from given values and insert it in the feature
|
310 |
set. If an error occurs raises RuntimeException.
|
311 |
:param values: dictionary with name property value or list named params
|
312 |
:type values: dict
|
313 |
"""
|
314 |
try:
|
315 |
if len(valuesList) ==1: |
316 |
values.update(valuesList[0])
|
317 |
|
318 |
if not self.isEditing(): |
319 |
self.edit()
|
320 |
f = self.createNewFeature()
|
321 |
|
322 |
if f == None: |
323 |
raise RuntimeError("Failed to create a new Feature") |
324 |
for k,v in values.iteritems(): |
325 |
f.set(k,v) |
326 |
self.insert(f)
|
327 |
except Throwable, ex:
|
328 |
raise RuntimeException("Can't append values %s to layer %s (%s)" % ( |
329 |
repr(values),
|
330 |
self.getName(),
|
331 |
str(ex)
|
332 |
) |
333 |
) |
334 |
|
335 |
def updateSchema(self, schema): |
336 |
"""
|
337 |
Updates store FeatureType. If an error occurs raises
|
338 |
RuntimeException.
|
339 |
"""
|
340 |
try:
|
341 |
self().update(schema._javaobj)
|
342 |
except Throwable, ex:
|
343 |
raise RuntimeException(repr(ex)) |
344 |
|
345 |
def update(self, feature): |
346 |
"""
|
347 |
Updates exist feature in the layer featureSet
|
348 |
:param editableFeature: editableFeature
|
349 |
:type editableFeature: Java editableFeature
|
350 |
"""
|
351 |
if not self.isEditing(): |
352 |
self.edit()
|
353 |
|
354 |
if not isinstance(feature, EditableFeature): |
355 |
feature = feature._javaobj |
356 |
self.fset.update(feature)
|
357 |
|
358 |
def getSchema(self): |
359 |
"""Returns store data attributtes"""
|
360 |
return Schema(self.getDefaultFeatureType()) |
361 |
|
362 |
def commit(self): |
363 |
"""
|
364 |
Finish store edition saving changes. If an error occurs raises Throwable
|
365 |
Exception.
|
366 |
"""
|
367 |
try:
|
368 |
self.finishEditing()
|
369 |
except Throwable, ex:
|
370 |
self.abort()
|
371 |
raise Throwable("Can't finish layer edition, cancelling changes. %s" % repr(ex)) |
372 |
|
373 |
def abort(self): |
374 |
"""Finish store edition withoout saving changes and disposes itself"""
|
375 |
self.cancelEditing()
|
376 |
self.dispose()
|
377 |
|
378 |
def getSelection(self): |
379 |
"""Returns store features selected set"""
|
380 |
return FeatureSet(self().getSelection()) |
381 |
|
382 |
class __DefaultTable__(WrapperToJava): |
383 |
def __init__(self,document, data): |
384 |
self.data = Store(data)
|
385 |
WrapperToJava.__init__(self,document)
|
386 |
self.selection = None |
387 |
|
388 |
def features(self, expresion = None, sortBy="", asc=True): |
389 |
"""
|
390 |
Returns data features set
|
391 |
:param expresion: filter to apply to the feature set to select
|
392 |
determinates features that match with expression
|
393 |
:type expresion: string
|
394 |
:return: FeatureSet
|
395 |
"""
|
396 |
return self.data.features(expresion, sortBy, asc) |
397 |
|
398 |
def edit(self): |
399 |
"""Sets data in edition mode"""
|
400 |
|
401 |
self.data.edit()
|
402 |
|
403 |
def append(self, *valuesList, **values): |
404 |
"""
|
405 |
Creates a new feature from given values and insert it in the feature set
|
406 |
:param values: dictionary with name property value or list named params
|
407 |
:type values: dict
|
408 |
"""
|
409 |
self.data.append(*valuesList, **values)
|
410 |
|
411 |
def updateSchema(self, schema): |
412 |
"""
|
413 |
Updates data data attributes properties with the given schema
|
414 |
"""
|
415 |
self.data.updateSchema(schema)
|
416 |
|
417 |
def update(self, feature): |
418 |
"""
|
419 |
Updates exist feature in the featureSet with the given feature
|
420 |
:param editableFeature: editableFeature
|
421 |
:type editableFeature: Java editableFeature
|
422 |
"""
|
423 |
self.data.update(feature)
|
424 |
|
425 |
def getSchema(self): |
426 |
"""Returns data attributes definition"""
|
427 |
return self.data.getSchema() |
428 |
|
429 |
def commit(self): |
430 |
"""Finish edition saving changes"""
|
431 |
self.data.commit()
|
432 |
|
433 |
def abort(self): |
434 |
"""Finish edition without saving changes"""
|
435 |
self.data.abort()
|
436 |
|
437 |
def getSelection(self): |
438 |
"""Returns features selected set"""
|
439 |
if self.selection == None: |
440 |
self.selection = Selection(self.data.getSelection()) |
441 |
|
442 |
return self.selection |
443 |
|
444 |
def select(self, selection): |
445 |
"""Inserts features in the features selection set"""
|
446 |
self.getSelection().select(selection)
|
447 |
|
448 |
def deselect(self, selection): |
449 |
"""Remove features in the features selection set"""
|
450 |
self.getSelection().deselect(selection)
|
451 |
|
452 |
def isSelected(feature): |
453 |
"""Returns True if given feature is selected"""
|
454 |
self.getSelection().isSelect(feature)
|
455 |
|
456 |
def getProjectionCode(self): |
457 |
"""Returns projection code name"""
|
458 |
return self.getProjection().getFullCode() |
459 |
|
460 |
|
461 |
class Table(__DefaultTable__): |
462 |
"""Represents gvsig table document
|
463 |
(org.gvsig.app.project.documents.table.TableDocument)
|
464 |
"""
|
465 |
def __init__(self,table): |
466 |
__DefaultTable__.__init__(self, table, table.getStore())
|
467 |
|
468 |
def getAssociatedLayer(self): |
469 |
"""Returns table associated layer or None if there're not associated
|
470 |
layer
|
471 |
"""
|
472 |
if self._javaobj.getAssociatedLayer(): |
473 |
return Layer(self._javaobj.getAssociatedLayer()) |
474 |
|
475 |
return None |
476 |
|
477 |
class Layer(__DefaultTable__): |
478 |
"""Represents gvsig layer document. It's a wrapper from
|
479 |
org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect class
|
480 |
"""
|
481 |
def __init__(self,layer): |
482 |
__DefaultTable__.__init__(self, layer, layer.getFeatureStore())
|
483 |
|
484 |
def getTypeVectorLayer(self): |
485 |
"""
|
486 |
Returns layer DefaultGeometryType class
|
487 |
To get the geometryType use DefaultGeometryType getType() method
|
488 |
To get the geometrySubType use DefaultGeometryType getSubType() method
|
489 |
"""
|
490 |
return self().getTypeVectorLayer() |
491 |
|
492 |
class FeatureSet(WrapperToJava): |
493 |
"""Represents gvSIG FeatureSet
|
494 |
(org.gvsig.fmap.dal.feature.impl.featureset.DefaultFeatureSet)
|
495 |
"""
|
496 |
def __init__(self,featureSet): |
497 |
WrapperToJava.__init__(self,featureSet)
|
498 |
|
499 |
def getCount(self): |
500 |
"""Returns the number of elements in the featureSet"""
|
501 |
return self.getSize() |
502 |
|
503 |
def update(self, feature): |
504 |
"""
|
505 |
Updates exist feature in the featureSet
|
506 |
:param editableFeature: editableFeature
|
507 |
:type editableFeature: Java editableFeature
|
508 |
"""
|
509 |
if not isinstance(feature, EditableFeature) and \ |
510 |
not isinstance(feature, DefaultEditableFeature): |
511 |
feature = feature._javaobj |
512 |
self().update(feature)
|
513 |
|
514 |
def __iter__(self): |
515 |
return Iterator(self.fastIterator()) |
516 |
|
517 |
class Selection(FeatureSet): |
518 |
"""Manage selected features set from a store. Represents gvSIG
|
519 |
org.gvsig.fmap.dal.feature.impl.DefaultFeatureSelection.
|
520 |
"""
|
521 |
def __init__(self, featureSet): |
522 |
FeatureSet.__init__(self, featureSet)
|
523 |
|
524 |
def select(self, selection): |
525 |
"""Inserts features in the features selection set"""
|
526 |
if isinstance(selection,Feature) or isinstance(selection, FeatureSet): |
527 |
self._javaobj.select(selection._javaobj)
|
528 |
else:
|
529 |
self._javaobj.select(selection)
|
530 |
|
531 |
def deselect(self, selection): |
532 |
"""Removes features in the features selection set"""
|
533 |
if isinstance(selection,Feature) or isinstance(selection, FeatureSet): |
534 |
self._javaobj.deselect(selection._javaobj)
|
535 |
else:
|
536 |
self._javaobj.deselect(selection)
|
537 |
|
538 |
def isSelected(feature): |
539 |
"""Returns True if given feature is selected"""
|
540 |
if isinstance(feature, Feature): |
541 |
self._javaobj.isSelect(feature._javaobj)
|
542 |
else:
|
543 |
self._javaobj.isSelect(feature)
|
544 |
|
545 |
def getCount(self): |
546 |
"""Returns the number of elements in the selection"""
|
547 |
return self.getSelectedCount() |
548 |
|
549 |
|
550 |
class Iterator(WrapperToJava): |
551 |
|
552 |
def __init__(self,iterator): |
553 |
WrapperToJava.__init__(self,iterator)
|
554 |
|
555 |
def next(self): |
556 |
if not self.hasNext(): |
557 |
raise StopIteration() |
558 |
return Feature(self().next()) |
559 |
|
560 |
class Feature(WrapperToJava): |
561 |
"""Represents feature data It's a wrapper from gvSIG
|
562 |
org.gvsig.fmap.dal.feature.impl.DefaultFeature class
|
563 |
"""
|
564 |
def __init__(self,feature): |
565 |
WrapperToJava.__init__(self,feature)
|
566 |
self.featureNoEditable = None |
567 |
|
568 |
def geometry(self): |
569 |
"""Returns feature geometry"""
|
570 |
return self.getDefaultGeometry() |
571 |
|
572 |
def getValues(self): |
573 |
"""Returns dictionary with the pair name, value, feature attributes"""
|
574 |
descriptor = self.getType()
|
575 |
items = dict()
|
576 |
for attr in descriptor.getAttributeDescriptors(): |
577 |
name = attr.getName() |
578 |
value = self.get(attr.getName())
|
579 |
items[name] = value |
580 |
return items
|
581 |
|
582 |
def edit(self): |
583 |
"""Returns editable feature instance"""
|
584 |
if not isinstance(self._javaobj, EditableFeature): |
585 |
self.featureNoEditable = self._javaobj |
586 |
self._javaobj = self._javaobj.getEditable() |
587 |
|
588 |
def __getitem__(self,key): |
589 |
return self.get(key) |
590 |
|
591 |
def __getattr__(self,name): |
592 |
#
|
593 |
#FIX console error when try to introspect feature object
|
594 |
if name in ('__methods__'): |
595 |
return dict() |
596 |
elif name in ('__members__'): |
597 |
return self.getValues().keys() |
598 |
elif name == '__dict__': |
599 |
return self.getValues() |
600 |
|
601 |
try:
|
602 |
v = getattr(self._javaobj, name, None) |
603 |
if v == None: |
604 |
v = self().get(name)
|
605 |
return v
|
606 |
except Throwable, ex:
|
607 |
raise RuntimeException("Can't access to attribute %s of feature (%s)" % (name, str(ex))) |
608 |
|
609 |
class Schema(WrapperToJava): |
610 |
"""Stores data properties definition. Represents gvSIG FeatureType
|
611 |
(org.gvsig.fmap.dal.feature.impl.DefaultFeatureType)
|
612 |
"""
|
613 |
|
614 |
def __init__(self, featureType): |
615 |
WrapperToJava.__init__(self,featureType)
|
616 |
self.featureTypeNoEditable = None |
617 |
|
618 |
def append(self, name, type, size=None, default=None, precision=4): |
619 |
"""Adds new property to feature properties definition. If error occurs
|
620 |
raises RuntimeError.
|
621 |
:param name: Feature property name
|
622 |
:type name: String
|
623 |
:param type: Feature property type
|
624 |
:type name: String
|
625 |
:param size: Feature property size
|
626 |
:type size: int
|
627 |
:param default: Feature property default value
|
628 |
:return: new atribute
|
629 |
"""
|
630 |
if not isinstance(self._javaobj, EditableFeatureType): |
631 |
self.modify()
|
632 |
|
633 |
if isinstance(type, str): |
634 |
try:
|
635 |
application = ApplicationLocator.getManager() |
636 |
datamanager = application.getDataManager() |
637 |
dataTypes = application.getDataTypesManager() |
638 |
type = dataTypes.getType(type) #dataType constant value from string |
639 |
except:
|
640 |
raise RuntimeError( |
641 |
"Feature Property Data type (%s) is not valid. name=%s, type=%s, size=%s, default=%s)" % (
|
642 |
type,
|
643 |
name, |
644 |
type,
|
645 |
size, |
646 |
default |
647 |
) |
648 |
) |
649 |
if isinstance(type, int): |
650 |
try:
|
651 |
type = dataTypes.get(type)
|
652 |
except:
|
653 |
raise RuntimeError( |
654 |
"Data type (%s) is not valid. name=%s, type=%s, size=%s, default=%s)" % (
|
655 |
type,
|
656 |
name, |
657 |
type,
|
658 |
size, |
659 |
default |
660 |
) |
661 |
) |
662 |
|
663 |
attribute = self.add(name, type.getType()) |
664 |
|
665 |
if size != None: |
666 |
attribute.setSize(size) |
667 |
|
668 |
if default != None: |
669 |
attribute.setDefaultValue(default) |
670 |
|
671 |
if precision != None and type.getType() in (DataTypes.DOUBLE, DataTypes.FLOAT): |
672 |
attribute.setPrecision(precision) |
673 |
|
674 |
if type.getType() == DataTypes.GEOMETRY and self.getDefaultGeometryAttributeName()==None: |
675 |
self.setDefaultGeometryAttributeName(name)
|
676 |
|
677 |
return attribute
|
678 |
|
679 |
def __getitem__(self, name): |
680 |
try:
|
681 |
return self.ftype.getAttributeDescriptor(name) |
682 |
except java.lang.IndexOutOfBoundsException:
|
683 |
raise StopIteration |
684 |
|
685 |
def get(self, name, default=None): |
686 |
"""Returns a feature attribute descriptor that contains information about
|
687 |
one feature attribute, such as its name, data type or precision.
|
688 |
:param name: Attribute name
|
689 |
:type name: string
|
690 |
:param default: Value to return if no attribute name found.
|
691 |
:return: AttributeDescriptor
|
692 |
"""
|
693 |
x = self.getAttributeDescriptor(name)
|
694 |
if x == None: |
695 |
return default
|
696 |
return x
|
697 |
|
698 |
def getAttrNames(self): |
699 |
"""Returns a list with attributes names"""
|
700 |
if not self.getAttributeDescriptors(): |
701 |
return None |
702 |
|
703 |
return [attr.getName() for attr in self.getAttributeDescriptors()] |
704 |
|
705 |
|
706 |
def getCopy(self): |
707 |
"""Returns a itself clone"""
|
708 |
return Schema(self().getCopy()) |
709 |
|
710 |
def modify(self): |
711 |
"""Sets edit mode"""
|
712 |
if not isinstance(self._javaobj, EditableFeatureType): |
713 |
self.featureTypeNoEditable = self._javaobj |
714 |
self._javaobj = self._javaobj.getEditable() |
715 |
|
716 |
|
717 |
#=====================#
|
718 |
# Vectorial Functions #
|
719 |
#=====================#
|
720 |
|
721 |
def createSchema(schema = None): |
722 |
"""Returns attributes definition. If Schema is recived then makes a copy and
|
723 |
returns editable instance. Otherwise returns empty Schema.
|
724 |
:param schema: Schema to make a copy
|
725 |
:type schema: Schema
|
726 |
"""
|
727 |
if isinstance(schema, Schema): |
728 |
try:
|
729 |
s = schema.getCopy() |
730 |
s.modify() |
731 |
return s
|
732 |
except:
|
733 |
pass
|
734 |
|
735 |
application = ApplicationLocator.getManager() |
736 |
datamanager = application.getDataManager() |
737 |
return Schema(datamanager.createFeatureType())
|
738 |
|
739 |
def createLayer(schema, servertype, layertype=None, **parameters): |
740 |
"""
|
741 |
Returns new layer
|
742 |
:param schema: layer data definition
|
743 |
:type schema: Schema
|
744 |
:param servertype:
|
745 |
:type servertype: string
|
746 |
:return: new layer
|
747 |
:rtype: Layer
|
748 |
:raise: RuntimeException
|
749 |
"""
|
750 |
if layertype == None: |
751 |
layertype = servertype |
752 |
servertype = "FilesystemExplorer"
|
753 |
|
754 |
if layertype == "Shape" : |
755 |
if schema.get("GEOMETRY",None) == None: |
756 |
raise RuntimeException("Shape need a field named GEOMETRY in the schema") |
757 |
|
758 |
if parameters["geometryType"] == None: |
759 |
raise RuntimeException("Invalid geometry type for new layer") |
760 |
|
761 |
#try:
|
762 |
if True: |
763 |
application = ApplicationLocator.getManager() |
764 |
datamanager = application.getDataManager() |
765 |
|
766 |
mapcontextmanager = application.getMapContextManager() |
767 |
|
768 |
server_parameters = datamanager.createServerExplorerParameters(servertype) |
769 |
copyToDynObject(parameters, server_parameters) |
770 |
|
771 |
server = datamanager.openServerExplorer(servertype, server_parameters) |
772 |
|
773 |
store_parameters = server.getAddParameters(layertype) |
774 |
copyToDynObject(parameters, store_parameters) |
775 |
store_parameters.setDefaultFeatureType(schema()) |
776 |
|
777 |
server.add(layertype, store_parameters, True)
|
778 |
|
779 |
store = datamanager.openStore(layertype, store_parameters) |
780 |
|
781 |
layer = mapcontextmanager.createLayer(store.getName(), store) |
782 |
|
783 |
return Layer(layer)
|
784 |
#except Throwable, ex:
|
785 |
# raise RuntimeException("Can't create layer, "+ str(ex), ex)
|
786 |
|
787 |
def loadShapeFile(shpFile, CRS="CRS:84"): |
788 |
"""
|
789 |
Add existing shape file to the view. Returns Layer shape file
|
790 |
:param shpFile: absolute file path
|
791 |
:type: shpFile: string
|
792 |
:param CRS: projection code
|
793 |
:type CRS: string
|
794 |
:return: the shape
|
795 |
:type return: Layer
|
796 |
"""
|
797 |
layer = loadLayer('Shape', shpFile=shpFile, CRS=CRS)
|
798 |
currentView().addLayer(layer) |
799 |
layer.setActive(True)
|
800 |
return Layer(layer)
|
801 |
|
802 |
def loadLayer(layerType, **parameters): |
803 |
try:
|
804 |
application = ApplicationLocator.getManager() |
805 |
datamanager = application.getDataManager() |
806 |
mapcontextmanager = application.getMapContextManager() |
807 |
store_parameters = datamanager.createStoreParameters(layerType) |
808 |
copyToDynObject(parameters, store_parameters) |
809 |
store = datamanager.openStore(layerType, store_parameters) |
810 |
layer = mapcontextmanager.createLayer(store.getName(), store) |
811 |
except Throwable, ex:
|
812 |
raise RuntimeException("Can't load layer, "+ str(ex),ex) |
813 |
|
814 |
return layer
|
815 |
|
816 |
def createShape(definition, filename, geometryType, CRS="CRS:84"): |
817 |
"""
|
818 |
Return new shape layer
|
819 |
:param definition: layer data definition
|
820 |
:type definition: Schema
|
821 |
:param filename: absolute path for shape files.
|
822 |
:type filename: string
|
823 |
:param geometryType: geometry type for shape
|
824 |
:type geometryType: string
|
825 |
:return: new shape layer
|
826 |
:rtype: Layer
|
827 |
"""
|
828 |
return createLayer(
|
829 |
definition, |
830 |
"FilesystemExplorer",
|
831 |
"Shape",
|
832 |
shpFile=filename, |
833 |
CRS=CRS, |
834 |
geometryType = geometryType |
835 |
) |
836 |
|
837 |
def createTable(schema, servertype, tableType=None, **parameters): |
838 |
"""Creates a new Table document"""
|
839 |
if tableType == None: |
840 |
tableType = servertype |
841 |
servertype = "FilesystemExplorer"
|
842 |
|
843 |
try:
|
844 |
application = ApplicationLocator.getManager() |
845 |
datamanager = application.getDataManager() |
846 |
|
847 |
server_parameters = datamanager.createServerExplorerParameters(servertype) |
848 |
copyToDynObject(parameters, server_parameters) |
849 |
|
850 |
server = datamanager.openServerExplorer(servertype, server_parameters) |
851 |
|
852 |
store_parameters = server.getAddParameters(tableType) |
853 |
copyToDynObject(parameters, store_parameters) |
854 |
store_parameters.setDefaultFeatureType(schema()) |
855 |
|
856 |
server.add(tableType, store_parameters, True)
|
857 |
|
858 |
store = datamanager.openStore(tableType, store_parameters) |
859 |
|
860 |
return Table(store)
|
861 |
|
862 |
except Throwable, ex:
|
863 |
raise RuntimeException("Can't create table, "+ str(ex)) |
864 |
|
865 |
def createDBF(definition, DbfFile, CRS="CRS:84"): |
866 |
"""
|
867 |
Creates a new dbf document
|
868 |
:param definition: layer data definition
|
869 |
:type definition: Schema
|
870 |
:param DbfFile: absolute path for shape files.
|
871 |
:type DbfFile: string
|
872 |
:return: new dbf
|
873 |
:rtype: Table
|
874 |
"""
|
875 |
return createTable(
|
876 |
definition, |
877 |
"FilesystemExplorer",
|
878 |
"DBF",
|
879 |
DbfFile=DbfFile, |
880 |
CRS=CRS, |
881 |
) |
882 |
|
883 |
#=====================#
|
884 |
# Documents Functions #
|
885 |
#=====================#
|
886 |
|
887 |
def currentProject(): |
888 |
"""
|
889 |
Returns current gvSIG proyect
|
890 |
:return: Proyect
|
891 |
"""
|
892 |
application = ApplicationLocator.getManager() |
893 |
project = application.getCurrentProject() |
894 |
return Project(project)
|
895 |
|
896 |
def currentDocument(documentClass = None): |
897 |
"""
|
898 |
Returns the current active document if it's a DocumentTable or
|
899 |
DocumentView2D return None
|
900 |
:return: Active document, None
|
901 |
"""
|
902 |
application = ApplicationLocator.getManager() |
903 |
|
904 |
if documentClass == None: |
905 |
doc = application.getActiveDocument() |
906 |
else:
|
907 |
doc = application.getActiveDocument(documentClass) |
908 |
if isinstance(doc, TableDocument): |
909 |
return Table(doc)
|
910 |
if isinstance(doc, ViewDocument): |
911 |
return View(doc)
|
912 |
|
913 |
return None |
914 |
|
915 |
def currentTable(): |
916 |
"""
|
917 |
Returns active table document or None
|
918 |
:return: Table or None
|
919 |
"""
|
920 |
return currentDocument(TableDocument)
|
921 |
|
922 |
def currentView(): |
923 |
"""
|
924 |
Returns the current active view document or None
|
925 |
:return: View or None
|
926 |
"""
|
927 |
return currentDocument(ViewDocument)
|
928 |
|
929 |
def currentLayer(): |
930 |
"""
|
931 |
Returns current view active layer or None
|
932 |
:return: gvSIG active layer
|
933 |
"""
|
934 |
try:
|
935 |
return currentView().getLayer()
|
936 |
except:
|
937 |
return None |
938 |
|
939 |
#=====================#
|
940 |
# Simbology Functions #
|
941 |
#=====================#
|
942 |
COLORS = { |
943 |
'black': Color.black,
|
944 |
'blue': Color.blue,
|
945 |
'cyan': Color.cyan,
|
946 |
'darkGray': Color.darkGray,
|
947 |
'gray': Color.gray,
|
948 |
'green': Color.green,
|
949 |
'lightGray': Color.lightGray,
|
950 |
'magenta': Color.magenta,
|
951 |
'orange': Color.orange,
|
952 |
'pink': Color.pink,
|
953 |
'red': Color.red,
|
954 |
'white': Color.white,
|
955 |
'yellow': Color.yellow,
|
956 |
} |
957 |
|
958 |
def simplePointSymbol(color=None): |
959 |
"""
|
960 |
Returns simple point symbol using parameter color. If no color
|
961 |
use a ramdom color
|
962 |
:param color: String color name or Java awt Color
|
963 |
:return: gvSIG point symbol
|
964 |
"""
|
965 |
if isinstance(color, str) and COLORS.has_key(color.lower()): |
966 |
color = COLORS.get(color) |
967 |
|
968 |
if not isinstance(color, Color): |
969 |
color = getDefaultColor() |
970 |
|
971 |
return MapContextLocator.getSymbolManager().createSymbol(
|
972 |
Geometry.TYPES.POINT, color) |
973 |
|
974 |
def simpleLineSymbol(color=None): |
975 |
"""
|
976 |
Returns simple line symbol using parameter color. If no color use a
|
977 |
ramdom color
|
978 |
:param color: String color name or Java awt Color
|
979 |
:return: gvSIG line symbol
|
980 |
|
981 |
"""
|
982 |
if isinstance(color, str) and COLORS.has_key(color.lower()): |
983 |
color = COLORS.get(color) |
984 |
|
985 |
if not isinstance(color, Color): |
986 |
color = getDefaultColor() |
987 |
|
988 |
return MapContextLocator.getSymbolManager().createSymbol(
|
989 |
Geometry.TYPES.CURVE, color) |
990 |
|
991 |
def simplePolygonSymbol(color = None): |
992 |
"""
|
993 |
Returns simple polygon symbol using parameter color. If no color
|
994 |
use a ramdom color.
|
995 |
:param color: String color name or Java awt Color
|
996 |
:return: gvSIG polygon symbol
|
997 |
"""
|
998 |
if isinstance(color, str) and COLORS.has_key(color.lower()): |
999 |
color = COLORS.get(color) |
1000 |
|
1001 |
if not isinstance(color, Color): |
1002 |
color = getDefaultColor() |
1003 |
|
1004 |
return MapContextLocator.getSymbolManager().createSymbol(
|
1005 |
Geometry.TYPES.SURFACE, color) |
1006 |
|
1007 |
|
1008 |
#=========================================#
|
1009 |
# gvSIG Application Preferences Functions #
|
1010 |
#=========================================#
|
1011 |
|
1012 |
def getDataFolder(): |
1013 |
"""
|
1014 |
Returns gvSIG data folder. This folder is defined in application
|
1015 |
preferences. If is not defined returns None.
|
1016 |
"""
|
1017 |
return Preferences.userRoot().node("gvsig.foldering").get('DataFolder', None) |
1018 |
|
1019 |
def getProjectsFolder(): |
1020 |
"""
|
1021 |
Returns gvSIG projects folder. This folder is defined in application
|
1022 |
preferences. If is not defined returns None.
|
1023 |
"""
|
1024 |
return Preferences.userRoot().node("gvsig.foldering").get( |
1025 |
'ProjectsFolder', None) |
1026 |
|
1027 |
def getColorFromRGB(r, g, b, a=None): |
1028 |
"""
|
1029 |
Returns an sRGB color with the specified red, green, blue, and alpha
|
1030 |
(optional) values in the range (0 - 255).
|
1031 |
"""
|
1032 |
if a:
|
1033 |
color = Color(r, g, b, a) |
1034 |
else:
|
1035 |
color = Color(r, g, b) |
1036 |
|
1037 |
return color
|
1038 |
|
1039 |
def getDefaultColor(c = None): |
1040 |
"""Returns gvsig default symbol fill color or ramdom color"""
|
1041 |
if MapContextLocator.getSymbolManager().isDefaultSymbolFillColorAleatory():
|
1042 |
color = Color(random.randint(0-255), |
1043 |
random.randint(0-255), |
1044 |
random.randint(0-255) |
1045 |
) |
1046 |
else:
|
1047 |
sp = MapContextLocator.getSymbolManager().getSymbolPreferences() |
1048 |
color = sp.getDefaultSymbolFillColor() |
1049 |
|
1050 |
return color
|
1051 |
|
1052 |
#================#
|
1053 |
# OTHER #
|
1054 |
#================#
|
1055 |
|
1056 |
def getCRS(crs): |
1057 |
"""Returns Projection from string code (i.e. CRS:84) if exist or None if
|
1058 |
not.
|
1059 |
"""
|
1060 |
try:
|
1061 |
return CRSFactory.getCRS(crs)
|
1062 |
except:
|
1063 |
return None |
1064 |
|
1065 |
def copyToDynObject(values, target): |
1066 |
definition = target.getDynClass(); |
1067 |
fields = definition.getDynFields(); |
1068 |
for field in fields: |
1069 |
name = field.getName() |
1070 |
keys = values.keys() |
1071 |
for k in keys: |
1072 |
if k.lower() == name.lower():
|
1073 |
target.setDynValue(name, values[name]) |
1074 |
break
|
1075 |
# ====================================
|
1076 |
#
|
1077 |
|
1078 |
def main(): |
1079 |
layer = currentLayer() |
1080 |
schema = createSchema() |
1081 |
schema.append("ID", "String", 50) |
1082 |
schema.append("GEOMETRY", "Geometry") |
1083 |
|
1084 |
output = createLayer( |
1085 |
schema, |
1086 |
"FilesystemExplorer",
|
1087 |
"Shape",
|
1088 |
shpFile="/tmp/pp.shp",
|
1089 |
CRS="EPSG:23030",
|
1090 |
geometryType=POINT |
1091 |
) |
1092 |
|
1093 |
for feature in layer.features(): |
1094 |
point = feature.geometry().centroid() |
1095 |
output.append(ID=feature.ID, GEOMETRY=point) |
1096 |
|
1097 |
output.commit() |
1098 |
|
1099 |
currentView().addLayer(output()) |