def intersects(self, buffer1, theDataSet2):
     result = [False, []]
     if theDataSet2.getSpatialIndex() != None:
         for featureReference in theDataSet2.query(buffer1):
             feature2 = featureReference.getFeature()
             line2 = feature2.getDefaultGeometry().toLines() # Boundary
             if line2.intersects(buffer1):
                 result[0] = True
                 break
     else:
         if self.expression == None:
             self.expression = ExpressionEvaluatorLocator.getManager().createExpression()
             self.expressionBuilder = ExpressionEvaluatorLocator.getManager().createExpressionBuilder()
             # self.expressionBuilder = GeometryExpressionEvaluatorLocator.getManager().createExpressionBuilder()
             store2 = theDataSet2.getFeatureStore()
             self.geomName = store2.getDefaultFeatureType().getDefaultGeometryAttributeName()
         self.expression.setPhrase(
             self.expressionBuilder.ifnull(
                 self.expressionBuilder.column(self.geomName),
                 self.expressionBuilder.constant(False),
                 self.expressionBuilder.ST_Intersects(
                     self.expressionBuilder.ST_ExteriorRing(
                         self.expressionBuilder.geometry(buffer1)
                     ),
                     self.expressionBuilder.column(self.geomName)
                 )
             ).toString()
         )
         if theDataSet2.findFirst(self.expression) != None:
             result[0] = True
     return result
 def intersects(self, line1, theDataSet2):
     result= [False, []]
     if theDataSet2.getSpatialIndex() != None:
         for featureReference in theDataSet2.query(line1):
             feature2 = featureReference.getFeature()
             line2 = feature2.getDefaultGeometry()
             if line1.intersects(line2):
                 result[0] = True
                 result[1].append(feature2)
     else:
         if self.expression == None:
             self.expression = ExpressionEvaluatorLocator.getManager().createExpression()
             self.expressionBuilder = ExpressionEvaluatorLocator.getManager().createExpressionBuilder()
             # self.expressionBuilder = GeometryExpressionEvaluatorLocator.getManager().createExpressionBuilder()
             store2 = theDataSet2.getFeatureStore()
             self.geomName = store2.getDefaultFeatureType().getDefaultGeometryAttributeName()
         self.expression.setPhrase(
             self.expressionBuilder.ifnull(
                 self.expressionBuilder.column(self.geomName),
                 self.expressionBuilder.constant(False),
                 self.expressionBuilder.ST_Intersection(
                     self.expressionBuilder.geometry(line1),
                     self.expressionBuilder.column(self.geomName)
                 )
             ).toString()
         )
         features2 = theDataSet2.findAll(self.expression)
         for feature2 in features2:
             result[0] = True
             result[1].append(feature2)
     return result
Esempio n. 3
0
 def setDynmicSymbologyLabeling(self, store):
     mcm = MapContextLocator.getMapContextManager()
     vl = mcm.createLegend(DynamicVectorLegend.NAME)
     expression = ExpressionEvaluatorLocator.getManager().createExpression()
     
     expression.setPhrase("COUTLINE")
     vl.setOutlineColor(expression.clone())
     
     expression.setPhrase("CFILL")
     vl.setFillColor(expression.clone())
     
     expression.setPhrase("CSIZE")
     vl.setSize(expression.clone())
     
     expression.setPhrase("CROTATION")
     vl.setRotation(expression.clone())
     
     self.layer.setLegend(vl)
 
 
     # Set dynamic labeling
 
     sm = SymbologyLocator.getSymbologyManager()
     dynamicLabeling  = sm.createLabelingStrategy(DynamicLabelingStrategy.NAME)
     
     expression = ExpressionEvaluatorLocator.getManager().createExpression()
     
     expression.setPhrase("LROTATION")
     dynamicLabeling.setRotation(expression.clone())
     
     expression.setPhrase("LTEXT")
     dynamicLabeling.setText(expression.clone())
     
     expression.setPhrase("LHEIGHT")
     dynamicLabeling.setHeight(expression.clone())
     
     expression.setPhrase("LCOLOR")
     dynamicLabeling.setColor(expression.clone())
     
     expression.setPhrase("LFONT")
     dynamicLabeling.setFont(expression.clone())
     
     expression.setPhrase("LFONTS")
     dynamicLabeling.setFontStyle(expression.clone())
     
     expression.setPhrase("LUNIT")
     dynamicLabeling.setUnit(expression.clone())
     
     expression.setPhrase("LREF")
     dynamicLabeling.setReferenceSystem(expression.clone())
     
     
     self.layer.setLabelingStrategy(dynamicLabeling)
     self.layer.setIsLabeled(True)
Esempio n. 4
0
def main(*args):
  # Test pq con original phrase no funciona
  store = gvsig.currentLayer().getFeatureStore()
  dm = DALLocator.getDataManager()
  filterExpression = ExpressionEvaluatorLocator.getManager().createExpression()
  filterExpression.setPhrase("")
  spatialGeometry = geom.createGeometryFromWKT("POLYGON ((-74.26662451007567 40.497289998, -74.26662451007567 40.517289997999995, -74.24930400199999 40.527289998, -74.2319834939243 40.517289997999995, -74.2319834939243 40.497289998, -74.24930400199999 40.487289997999994, -74.26662451007567 40.497289998))")
  spatialGeometry.setProjection(gvsig.currentLayer().getProjection())
  
  ## store, exp, spatialGeometry
  print "Spatial"
  builder = ExpressionEvaluatorLocator.getManager().createExpressionBuilder()
  """
  expr1 = builder.and(
      builder.custom(exp.getPhrase()),
      builder.ST_Intersects(
        builder.geometry(spatialGeometry),
        builder.column("GEOMETRY")
      )
  ).toString()
  """
  expr1 = builder.ST_Intersects(
      builder.geometry(spatialGeometry),
      builder.column("GEOMETRY")
    ).toString()
  ## Creating new expression
  eva = ExpressionEvaluatorLocator.getManager().createExpression()
  eva.setPhrase(expr1)
  evaluator = DALLocator.getDataManager().createExpresion(eva)
  
  # Query
  fq = store.createFeatureQuery()
  fq.addFilter(evaluator)
  fq.retrievesAllAttributes()
  fset = store.getFeatureSet(fq)
  print "SIZE: ",fset.getSize()

  ### Reusing expression
  
  cloneExpression = filterExpression.clone()
  print "not cloning"
  cloneExpression.setPhrase(expr1)
  evaluator = DALLocator.getDataManager().createExpresion(cloneExpression)
  
  ## Query
  fq = store.createFeatureQuery()
  fq.addFilter(evaluator)
  fq.retrievesAllAttributes()
  fset = store.getFeatureSet(fq)
  print "SIZE: ",fset.getSize()
Esempio n. 5
0
 def contains(self, polygon1, theDataSet2):
     result = False
     if theDataSet2.getSpatialIndex() != None:
         for featureReference in theDataSet2.query(polygon1):
             feature2 = featureReference.getFeature()
             point2 = feature2.getDefaultGeometry()
             if polygon1.contains(point2):
                 result = True
                 break
     else:
         if self.expression == None:
             manager = ExpressionEvaluatorLocator.getManager()
             self.expression = manager.createExpression()
             self.expressionBuilder = manager.createExpressionBuilder()
             store2 = theDataSet2.getFeatureStore()
             self.geomName = store2.getDefaultFeatureType(
             ).getDefaultGeometryAttributeName()
         self.expression.setPhrase(
             self.expressionBuilder.ifnull(
                 self.expressionBuilder.column(self.geomName),
                 self.expressionBuilder.constant(False),
                 self.expressionBuilder.ST_Contains(
                     self.expressionBuilder.geometry(polygon1),
                     self.expressionBuilder.column(
                         self.geomName))).toString())
         if theDataSet2.findFirst(self.expression) != None:
             result = True
     return result
Esempio n. 6
0
def main1(*args):
    from org.gvsig.expressionevaluator import ExpressionEvaluatorLocator
    manager = ExpressionEvaluatorLocator.getManager()
    symbolTable = manager.createSymbolTable()
    symbolTable.addVar("A", 2)
    expression = "[A]"
    code = manager.compile(expression)
    out = manager.evaluate(symbolTable, code)
    print out, type(out)
Esempio n. 7
0
    def __init__(self, plan, factory, tolerance, dataSet1, dataSet2):
        AbstractTopologyRule.__init__(self, plan, factory, tolerance, dataSet1,
                                      dataSet2)
        self.addAction(DeletePointAction())

        self.expression = ExpressionEvaluatorLocator.getManager(
        ).createExpression()
        self.expressionBuilder = GeometryExpressionEvaluatorLocator.getManager(
        ).createExpressionBuilder()
        self.geomName = None
Esempio n. 8
0
def main3(*args):

    from org.gvsig.expressionevaluator import ExpressionEvaluatorLocator

    manager = ExpressionEvaluatorLocator.getManager()
    expression = "COS(0)"
    evaluator = manager.createEvaluator(expression)
    print evaluator.getSymbolTable()
    symbolTable = manager.createSymbolTable()
    symbolTable.addVar("A", 2)
    symbolTable.addVar("B", 3)
    evaluator.setSymbolTable(symbolTable)
    print evaluator.compile()
Esempio n. 9
0
def main4(*args):
    from org.gvsig.expressionevaluator import ExpressionEvaluatorLocator
    manager = ExpressionEvaluatorLocator.getManager()
    symbols = manager.createSymbolTable()
    interpreter = manager.createInterpreter()
    symbols.setSymbolTable(interpreter.getSymbolTable())
    interpreter.setSymbolTable(symbols)

    expression = "n*sin(90)"
    code = manager.compile(expression)

    symbols.addVar("n",5)
    out = interpreter.run(code)
    print out
Esempio n. 10
0
def main2(*args):
  store = gvsig.currentLayer().getFeatureStore()
  dm = DALLocator.getDataManager()
  i="True"
  evaluator = dm.createExpresion(i)
  fq = store.createFeatureQuery()
  fq.addFilter(evaluator)
  fq.retrievesAllAttributes()
  fset = store.getFeatureSet(fq)
  count = 0
  for f in fset:
    count+=1
  print count
  ###
  print "Spatial"
  spatialGeometry = geom.createGeometryFromWKT("POLYGON ((-74.26662451007567 40.497289998, -74.26662451007567 40.517289997999995, -74.24930400199999 40.527289998, -74.2319834939243 40.517289997999995, -74.2319834939243 40.497289998, -74.24930400199999 40.487289997999994, -74.26662451007567 40.497289998))")
  spatialGeometry.setProjection(gvsig.currentLayer().getProjection())
  builder = ExpressionEvaluatorLocator.getManager().createExpressionBuilder()
  expr1 = builder.and(
      builder.custom(i),
      builder.ST_Intersects(
        builder.geometry(spatialGeometry),
        builder.column("GEOMETRY")
      )
  ).toString()
  eva = ExpressionEvaluatorLocator.getManager().createExpression()
  eva.setPhrase(expr1)
  
  evaluator = DALLocator.getDataManager().createExpresion(eva)
  fq = store.createFeatureQuery()
  fq.addFilter(evaluator)
  fq.retrievesAllAttributes()
  fset = store.getFeatureSet(fq)
  count = 0
  for f in fset:
    count+=1
  print count
def main(*args):
    fset = gvsig.currentLayer().getFeatureStore().getFeatureSet()
    field = "resblob"
    formatName = "PNG"  #https://docs.oracle.com/javase/tutorial/2d/images/saveimage.html
    ft = gvsig.currentLayer().getFeatureStore().getDefaultFeatureType(
    ).getAttributeDescriptor("id")
    outparams = {
        "option": 2,
        "params": {
            "path": File("/home/osc/Working/exportimages/"),
            "field": ft
        }
    }
    exp = ExpressionEvaluatorLocator.getManager().createExpression()
    exp.setPhrase("CONCAT('/home/osc/Working/exportimages/', id)")
    outparams = {"option": 3, "params": {"expression": exp}}
    processExportImage(fset, field, formatName, outparams)
def getFeatureSetForGeoprocess(store, filterExpression, spatialGeometry=None, geomFieldName="GEOMETRY"):
  if filterExpression==None: #.getPhrase()=="": #org.gvsig.expressionevaluator.Expression
    if store.getSelection().getSize()==0:
      builder = GeometryExpressionEvaluatorLocator.getGeometryExpressionEvaluatorManager().createExpressionBuilder()
      expr1 = builder.ST_Intersects(
            builder.geometry(spatialGeometry),
            builder.column(geomFieldName)
          ).toString()
      
      #cloneExpression = filterExpression.clone()
      cloneExpression = ExpressionEvaluatorLocator.getManager().createExpression()
      cloneExpression.setPhrase(expr1)
      evaluator = DALLocator.getDataManager().createFilter(cloneExpression)
      """
      exp = ExpressionEvaluatorLocator.getManager().createExpression()
      exp.setPhrase(expr1)
      evaluator = DALLocator.getDataManager().createExpresion(exp)
      """
      fq = store.createFeatureQuery()
      fq.addFilter(cloneExpression)
      #fq.retrievesAllAttributes()
      #fq.addAttributeName("Id")
      featuresLayer = store.getFeatureSet(fq)
      return featuresLayer
    else:
      featuresLayer = store.getSelection()
      return featuresLayer
  else:
    builder = GeometryExpressionEvaluatorLocator.getGeometryExpressionEvaluatorManager().createExpressionBuilder()
    expr2 = builder.and(
        builder.custom(filterExpression.getPhrase()),
        builder.ST_Intersects(
          builder.geometry(spatialGeometry),
          builder.column("GEOMETRY")
        )
    ).toString()
    cloneExpression = filterExpression.clone()
    cloneExpression.setPhrase(expr2)
    fq = store.createFeatureQuery()
    fq.addFilter(cloneExpression)
    #fq.retrievesAllAttributes()
    featuresLayer = store.getFeatureSet(fq)
    return featuresLayer
Esempio n. 13
0
  def getFilter(self):
    if (self.checkModify()==False):
      return None
    tipoAccidente = self.tipoAccidente.getSelectedItem().getValue()
    dateDesde = self.pickerFechaDesde.get()
    dateHasta = self.pickerFechaHasta.get()
    
    expManager= ExpressionEvaluatorLocator.getManager()
    exp = expManager.createExpression()
    builder = expManager.createExpressionBuilder()

    if (tipoAccidente!=""):
      builder.and(builder.eq(
        builder.variable("TIPO_ACC_COLISION"), 
        builder.constant(tipoAccidente)
        )
      )

    if (dateDesde!=None and dateHasta != None):
      builder.and(
        builder.and(
          builder.ge(
            builder.variable("FECHA_ACCIDENTE"),
            builder.date(dateDesde)
          ),
          builder.le(
            builder.variable("FECHA_ACCIDENTE"), 
            builder.date(dateHasta) #builder.function(FUNCTION_DATE,dateFormat.format(dateHasta), dateFormat)
          )
        )
      )
    elif (dateDesde!=None):
      builder.and(builder.ge(
            builder.variable("FECHA_ACCIDENTE"), 
            builder.date(dateDesde)
          ))
    elif (dateHasta!=None):
      builder.and(builder.le(
              builder.variable("FECHA_ACCIDENTE"), 
              builder.date(dateHasta)
            ))
    return builder.value()
Esempio n. 14
0
def main1(*args):

    from org.gvsig.expressionevaluator import ExpressionEvaluatorLocator

    manager = ExpressionEvaluatorLocator.getManager()
    interpreter = manager.createInterpreter()
    #print interpreter
    symbolTable = manager.createSymbolTable()
    symbolTable.addVar("A", 2)
    symbolTable.addVar("B", 3)
    
    expression = "COS(0)"
    code = manager.compile(expression)
    
    symbol = interpreter.getSymbolTable()
    symbol  = MyTable()

    interpreter.setSymbolTable(symbol)
    out = interpreter.run(code)
    print out
def main(*args):
  proportionX = 1
  proportionY = 1
  nameFieldHour = "CDATE"
  nameFieldDay = "CMPLNT_FR_"
  nameFieldHour = "CMPLNT_FR_"
  dm = DALLocator.getDataManager()
  evaluator = dm.createExpresion("")
  exp = ExpressionEvaluatorLocator.getManager().createExpression()
  exp.setPhrase('')
  print evaluator
  expression = exp
  xi = 0
  yi = 0
  store = gvsig.currentLayer().getFeatureStore()
  aoristicClockGrid(store,
                      proportionX,
                      proportionY,
                      nameFieldHour,
                      nameFieldDay,
                      expression,
                      0,
                      0)
  def createExpression(self):
    expManager= ExpressionEvaluatorLocator.getManager()
    exp = expManager.createExpression()
    builder = expManager.createExpressionBuilder()
    # Accidente
    codAccidente = self.txtCodAccidente.getText()
    #Codigo
    if (codAccidente!=""):
      builder.set(
        builder.like(
            builder.variable("ID_ACCIDENTE"), 
            builder.constant(codAccidente)
          )
      )
    # Carretera
    carreteraValue = self.tabControllerCarretera.getFilter()
    if (carreteraValue!=None):
      builder.and(carreteraValue)

    # Fecha y tipo
    fechaValue = self.tabControllerFecha.getFilter()
    if (fechaValue!=None):
      builder.and(fechaValue)
    # Victimas
    victimasValue = self.tabControllerVictimas.getFilter()
    if (victimasValue!=None):
      builder.and(victimasValue)

    # Acumulada
    accumulatedFilter = self.simplifiedPanel.getAccumulatedFilter()
    if(accumulatedFilter!=None):
      builder.and(builder.toValue(accumulatedFilter))
    try:
      exp.setPhrase(builder.toString())
    except:
      exp.setPhrase("")
    return exp
 def intersects(self, buffer1, theDataSet2):
     result = False
     if theDataSet2.getSpatialIndex() != None:
         for featureReference in theDataSet2.query(buffer1):
             feature2 = featureReference.getFeature()
             line2 = feature2.getDefaultGeometry()
             numVertices = line2.getNumVertices()
             if buffer1.intersects(line2.getVertex(0)) or buffer1.intersects(line2.getVertex(numVertices - 1)):
                 result = True
                 break
     else:
         if self.expression == None:
             manager = ExpressionEvaluatorLocator.getManager()
             self.expression = manager.createExpression()
             self.expressionBuilder = manager.createExpressionBuilder()
             store2 = theDataSet2.getFeatureStore()
             self.geomName = store2.getDefaultFeatureType().getDefaultGeometryAttributeName()
         self.expression.setPhrase(
             self.expressionBuilder.ifnull(
                 self.expressionBuilder.column(self.geomName),
                 self.expressionBuilder.constant(False),
                 self.expressionBuilder.or(
                     self.expressionBuilder.ST_Intersects(
                         self.expressionBuilder.function("ST_StartPoint", self.expressionBuilder.column(self.geomName)),
                         self.expressionBuilder.geometry(buffer1, buffer1.getProjection())
                     ),
                     self.expressionBuilder.ST_Intersects(
                         self.expressionBuilder.function("ST_EndPoint", self.expressionBuilder.column(self.geomName)),
                         self.expressionBuilder.geometry(buffer1, buffer1.getProjection())
                     )
                 )
             ).toString()
         )
         if theDataSet2.findFirst(self.expression) != None:
             result = True
     return result
    def updateRealField(self, columnSelectedDescriptor, store, exp, expFilter,
                        useFilterType, dialog, prefs):
        i18nManager = ToolsLocator.getI18nManager()
        try:
            ftype = store.getDefaultFeatureType()
            s = ExpressionEvaluatorLocator.getManager().createSymbolTable()
            fst = DALLocator.getDataManager().createFeatureSymbolTable()
            s.addSymbolTable(fst)
            store.edit()
            #store.beginComplexNotification() #beginEditingGroup("field-calculator-update")
            # Create fset
            if useFilterType == 0:
                fset = store.getSelection()
                if store.getSelection().getSize() == 0:
                    logger("Selection is empty", LOGGER_WARN)
                    self.taskStatus.message(
                        i18nManager.getTranslation("_Selection_is_empty"))
                    return
            elif useFilterType == 1:
                if expFilter != None and not expFilter.isPhraseEmpty(
                ) and not expFilter.isEmpty():
                    fq = store.createFeatureQuery()
                    fq.addFilter(expFilter)
                    fq.retrievesAllAttributes()
                    fset = store.getFeatureSet(fq)
                else:
                    fset = store.getFeatureSet()
            else:
                fset = store.getFeatureSet()
            # set taskstatus
            self.taskStatus.setRangeOfValues(0, fset.getSize())
            self.taskStatus.setCurValue(0)
            self.taskStatus.add()

            # Limit of changes before commit
            limit = prefs["limit_rows_in_memory"]

            # Update features
            for f in fset:
                if self.taskStatus.isCancellationRequested():
                    break
                fst.setFeature(f)
                v = exp.execute(s)  # value de la expression
                c = f.getEditable()
                c.set(columnSelectedDescriptor.getName(), v)
                fset.update(c)
                #if commitingMode:
                if limit != -1 and self.store.getPendingChangesCount() > limit:
                    fset.commitChanges()
                #self.taskStatus.setCurValue(count)
                self.taskStatus.incrementCurrentValue()

        except:
            ex = sys.exc_info()[1]
            #ex.__class__.__name__, str(ex)
            logger("Exception updated features: " + str(ex), LOGGER_ERROR)

        finally:
            #store.endEditingGroup()
            try:
                DisposeUtils.disposeQuietly(fset)
            except:
                logger("Not able to dispone fset", LOGGER_ERROR)
            if self.modeExitTool:
                try:
                    store.finishEditing()
                except:
                    logger("Not able to save store changes", LOGGER_ERROR)
                    try:
                        store.cancelEditing()
                    except:
                        logger("Not able to cancel editing", LOGGER_ERROR)
                if self.editingMode:
                    try:
                        store.edit()
                    except:
                        logger("Not able to put store into editing mode",
                               LOGGER_ERROR)
            else:
                logger("Field Calculator Tool expression applied", LOGGER_INFO)
                if self.editingMode == False:
                    try:
                        store.finishEditing()
                    except:
                        logger("Not able to puto layer into editing again",
                               LOGGER_ERROR)
Esempio n. 19
0
  def getFilter(self): #getFilter
    if (self.checkModify()==False):
      return None
    provincia = self.provincia.getSelectedItem().getValue()
    titularidad = self.titularidad.getSelectedItem().getValue()
    carretera = self.carretera.getText()
    pkInicio = self.pki.getText()
    pkInicioUmbral = self.pkiu.getText()
    pkFin = self.pkf.getText()
    pkFinUmbral = self.pkfu.getText()
    sentido = self.sentido.getSelectedItem().getValue()
    
    expManager= ExpressionEvaluatorLocator.getManager()
    exp = expManager.createExpression()
    builder = expManager.createExpressionBuilder()

    if (provincia!=""):
      builder.and(builder.eq(
        builder.variable("COD_PROVINCIA"), 
        builder.constant(provincia)
        )
      )
    if (titularidad!=""):
      builder.and(builder.eq(
        builder.variable("TITULARIDAD_VIA"), 
        builder.constant(titularidad)
        )
      )
      
    if (carretera!=""):
      builder.and(builder.eq(
        builder.variable("CARRETERA"), 
        builder.constant(carretera)
        )
      )
    if pkInicio!="":
      pkInicioTotal = float(pkInicio)
      if pkInicioUmbral!="":
        pkInicioTotal += float("0."+pkInicioUmbral)
    
    if pkFin!="":
      pkFinTotal = float(pkFin)
      if pkFinUmbral!="":
        pkFinTotal += float("0."+pkFinUmbral)
    
    if pkInicio != "" and pkFin != "":
      builder.and(
        builder.and(
          builder.ge(
            builder.variable("KM"), 
            builder.constant(pkInicioTotal)
          ),
          builder.le(
            builder.variable("KM"), 
            builder.constant(pkFinTotal)
          )
        )
      )
    elif pkInicio != "":
      builder.and(
          builder.ge(
            builder.variable("KM"), 
            builder.constant(pkInicioTotal)
          )
        )
    elif pkFin != "":
      builder.and(
          builder.le(
            builder.variable("KM"), 
            builder.constant(pkFinTotal)
          )
        )
    if (sentido!=""):
      builder.and(builder.eq(
        builder.variable("SENTIDO"), 
        builder.constant(sentido)
        )
      )
    return builder.value()
    def process(self, filterType):#btnProcess_click(self, *args):
        store = self.layer.getFeatureStore()

        # TODO: if field is empty, return all features filter

        if filterType=="basicFilter":
            ft = store.getDefaultFeatureType()
            builder = store.createExpressionBuilder()
            field = self.cmbFields.getSelectedItem().getValue()
            if field==None:
              return
            nameField = field.getName()
            if nameField=="":
              return
            if len(self.valuesList.getSelectedValuesList()) == 0:
              return
            if len(self.valuesList.getSelectedValuesList()) == 1:
              value = self.valuesList.getSelectedValuesList()[0]

              ## Eq expression
              expFilter = builder.eq(
                    builder.column(nameField),
                    builder.constant(value)
                    ).toString()
            else:
              expFilter = ""
              for value in self.valuesList.getSelectedValuesList():
                partialExpFilter = builder.eq(
                    builder.column(nameField),
                    builder.constant(value)
                    ).toString()
                if expFilter=="": 
                  expFilter += partialExpFilter
                else:
                  expFilter = builder.or( builder.custom(expFilter), builder.custom(partialExpFilter)).toString()
              #expFilter = expFilter.toString()
            logger("Filter applied: " + expFilter, LOGGER_INFO)
            exp = ExpressionEvaluatorLocator.getManager().createExpression()
            exp.setPhrase(expFilter)
            evaluator = DALLocator.getDataManager().createExpresion(exp)
            fq = store.createFeatureQuery()
            fq.retrievesAllAttributes()
            fq.setFilter(evaluator)
            fq.retrievesAllAttributes()
            
            # UPDATE VALUES
            #fset = store.getFeatureSet(fq)
            fq.addFilter(exp)
            
            if isinstance(fq, Evaluator):
                self.layer.addBaseFilter(fq)
            else:
                self.layer.setBaseQuery(fq)
        elif filterType=="advancedFilter":
            expression = self.expBuilder.getExpression()
            fq = store.createFeatureQuery()
            fq.retrievesAllAttributes()
            #for field  in store.getDefaultFeatureType().getAttrNames():
            #    fq.addAttributeName(field)
            fq.setFilter(expression)
            self.layer.setBaseQuery(fq)

        else:
            return
        #self.view.getWindowOfView()
        fixMapcontextInvalidate(self.view.getMapContext())
Esempio n. 21
0
  def getFilter(self):
    if (self.checkModify()==False):
      return None
    expManager= ExpressionEvaluatorLocator.getManager()
    exp = expManager.createExpression()
    builder = expManager.createExpressionBuilder()
    
    categoria = self.categoria.getSelectedItem().getValue()
    peligrosas = self.peligrosas.isSelected()
    mortalesOperador = self.mortalesOperador.getSelectedItem().getValue()
    operator1 = self.operator1.getSelectedItem().getValue()
    gravesOperador = self.gravesOperador.getSelectedItem().getValue()
    operator2 = self.operator2.getSelectedItem().getValue()
    levesOperador = self.levesOperador.getSelectedItem().getValue()

    mortales = self.mortales.getText()
    graves = self.graves.getText()
    leves = self.leves.getText()
    
    if (categoria!=""):
      if (categoria==self.CATEGORIA_CON_VICTIMAS):
        builder.and(builder.gt(
          builder.variable("TOTAL_VICTIMAS"), 
          builder.constant(0)
          )
        )
      elif (categoria==self.CATEGORIA_CON_DANOS):
        builder.and(builder.eq(
          builder.variable("TOTAL_VICTIMAS"), 
          builder.constant(0)
          )
        )
    if (peligrosas):
        dataManager = DALLocator.getDataManager()
        #EXISTS(SELECT LID_VEHICULO FROM ARENA2_VEHICULOS WHERE ARENA2_ACCIDENTES.ID_ACCIDENTE = ARENA2_VEHICULOS.ID_ACCIDENTE AND  MP LIMIT 1)
        dalbuilder = dataManager.createDALExpressionBuilder() #DALExpressionBuilder
        peligrosasfilter = dalbuilder.exists(dalbuilder.select()
          .column("LID_VEHICULO")
          .from("ARENA2_VEHICULOS")
          .limit(1)
          .where(
          dalbuilder.expression().and(
            dalbuilder.expression().eq(
              dalbuilder.expression().getattr("ARENA2_ACCIDENTES","ID_ACCIDENTE"),
              dalbuilder.expression().getattr("ARENA2_VEHICULOS","ID_ACCIDENTE")
            ),
            dalbuilder.expression().column("MP")
          )).toValue())
        builder.and(peligrosasfilter)

    # TOTAL -> Juntos en allbuilder. como apoyo opbuilder
    opbuilder = expManager.createExpressionBuilder()
    allBuilder = expManager.createExpressionBuilder()
    valueMortales = None
    if (mortales!=""):
      valueMortales = opbuilder.binaryOperator(
        mortalesOperador,
        opbuilder.variable("TOTAL_MUERTOS"), 
        opbuilder.constant(mortales, DataTypes.INT)
        )
      
      allBuilder.and(valueMortales)

    valueGraves = None
    if (graves!=""):
      valueGraves = opbuilder.binaryOperator(
        gravesOperador,
        opbuilder.variable("TOTAL_GRAVES"), 
        opbuilder.constant(graves, DataTypes.INT)
        )
      if (valueMortales!=""):
        if (operator1 == ExpressionBuilder.OPERATOR_AND):
          allBuilder.and(valueGraves)
        elif (operator1 == ExpressionBuilder.OPERATOR_OR):
          allBuilder.or(valueGraves)
          

    valueLeves = None
    if (leves!=""):
      valueLeves = opbuilder.binaryOperator(
        levesOperador,
        opbuilder.variable("TOTAL_LEVES"), 
        opbuilder.constant(leves, DataTypes.INT)
        )
      
      if (valueMortales!="" or valueGraves!=""):
        if (operator2 == ExpressionBuilder.OPERATOR_AND):
          allBuilder.and(valueLeves)
        elif (operator2 == ExpressionBuilder.OPERATOR_OR):
          allBuilder.or(valueLeves)

    allValue = allBuilder.value()
    if (allValue!=None): # Unimos TOTAL_ con builder
      builder.and(allValue)
    
    return builder.value()
Esempio n. 22
0
    def check(self, taskStatus, report, feature1):
        #SimpleTaskStatus taskStatus,
        #TopologyReport report,
        #Feature feature1

        try:
            logger("tak", LOGGER_INFO)
            if (self.expression == None):
                manager = ExpressionEvaluatorLocator.getManager()
                self.expression = manager.createExpression()
                self.expressionBuilder = manager.createExpressionBuilder()
                self.geomName = feature1.getType(
                ).getDefaultGeometryAttributeName()

            polygon = feature1.getDefaultGeometry()
            if (polygon == None):
                return
            #logger("1", LOGGER_INFO)

            theDataSet = self.getDataSet1()
            #logger("2", LOGGER_INFO)
            if theDataSet.getSpatialIndex() != None:
                #logger("if", LOGGER_INFO)
                for reference in theDataSet.query(polygon):
                    #FeatureReference reference
                    # Misma feature
                    #logger("ref"+str(reference), LOGGER_INFO)
                    if (reference.equals(feature1.getReference())):
                        continue

                    feature = reference.getFeature()
                    otherPolygon = feature.getDefaultGeometry()
                    if (otherPolygon != None
                            and polygon.overlaps(otherPolygon)):
                        error = polygon.intersection(otherPolygon)
                        report.addLine(self, theDataSet, None, polygon, error,
                                       feature1.getReference(), None, False,
                                       "The polygon overlay with others.")
                        break

            else:
                logger("else", LOGGER_INFO)
                self.expression.setPhrase(
                    self.expressionBuilder.ifnull(
                        self.expressionBuilder.column(self.geomName),
                        self.expressionBuilder.constant(False),
                        self.expressionBuilder.ST_Overlaps(
                            self.expressionBuilder.column(self.geomName),
                            self.expressionBuilder.geometry(
                                polygon))).toString())
                feature = theDataSet.findFirst(self.expression)
                if feature != None:
                    otherPolygon = feature.getDefaultGeometry()
                    error = None
                    if otherPolygon != None:
                        error = polygon.difference(otherPolygon)

                    report.addLine(self, theDataSet, None, polygon, error,
                                   feature1.getReference(), None, False,
                                   "The polygon overlay with others.")
                logger("end", LOGGER_INFO)
        except:  # Exception as ex:
            #logger("2 Can't check feature."+str(ex), LOGGER_WARN)
            ex = sys.exc_info()[1]
            logger("Can't execute rule. Class Name:" + ex.__class__.__name__ +
                   " Except:" + str(ex))
        finally:
            pass
def processExportImage(featureSet,
                       field,
                       formatName,
                       outparams,
                       taskStatus=None):
    if not formatName in ["PNG", "JPEG", "GIF"]:
        logger("Not valid format for export images", LOGGER_ERROR)
        return
    sm = ToolsSwingLocator.getToolsSwingManager()
    si = sm.createSimpleImage()
    if taskStatus != None:
        taskStatus.setRangeOfValues(0, featureSet.getSize())
    if isinstance(field, FeatureAttributeDescriptor):
        field = field.getName()
    try:
        ooption = outparams["option"]
        oparams = outparams["params"]
        n = 0
        if ooption == 1:
            for f in featureSet:
                if taskStatus != None:
                    n += 1
                    taskStatus.setCurValue(n)
                    if taskStatus.isCancellationRequested():
                        return
                value = f.get(field)
                if value == None or value == "":
                    continue
                si.set(value)
                im = si.getBufferedImage()
                if im == None:
                    logger(
                        "Not able to get Bufferded Image from field " +
                        str(field) + " value:" + str(value), LOGGER_ERROR)
                    continue
                # Save image
                ofield = oparams["field"]
                if isinstance(ofield, FeatureAttributeDescriptor):
                    ofield = ofield.getName()
                output = f.get(ofield)
                ImageIO.write(im, formatName, output)
        elif ooption == 2:
            for f in featureSet:
                if taskStatus != None:
                    n += 1
                    taskStatus.setCurValue(n)
                    if taskStatus.isCancellationRequested():
                        return
                value = f.get(field)
                if value == None or value == "":
                    continue
                si.set(value)
                im = si.getBufferedImage()
                if im == None:
                    logger(
                        "Not able to get Bufferded Image from field " +
                        str(field) + " value:" + str(value), LOGGER_ERROR)
                    continue
                ofield = oparams["field"]
                if isinstance(ofield, FeatureAttributeDescriptor):
                    ofield = ofield.getName()
                oname = f.get(ofield)
                if oname == None or oname == "": continue
                outputPath = oparams["path"].getAbsolutePath()
                output = getUniqueValueFileByField(oname, outputPath,
                                                   formatName)
                ImageIO.write(im, formatName, output)
        elif ooption == 3:
            s = ExpressionEvaluatorLocator.getManager().createSymbolTable()
            fst = DALLocator.getDataManager().createFeatureSymbolTable()
            s.addSymbolTable(fst)
            exp = oparams["expression"]
            if exp.isEmpty():
                logger("Expression is empty", LOGGER_ERROR)
                return
            for f in featureSet:
                if taskStatus != None:
                    n += 1
                    taskStatus.setCurValue(n)
                    if taskStatus.isCancellationRequested():
                        return
                value = f.get(field)
                if value == None or value == "":
                    continue
                si.set(value)
                im = si.getBufferedImage()
                fst.setFeature(f)
                output = exp.execute(s)
                outputex = output + "." + formatName.lower()
                if os.path.exists(outputex):
                    logger("Already exists: " + outputex, LOGGER_ERROR)
                    continue
                ImageIO.write(im, formatName, File(outputex))

    except:
        ex = str(sys.exc_info()[1])
        logger(
            "Not able to export: " + ex + " caused on: " +
            ex.__class__.__name__, LOGGER_ERROR)
        try:
            DisposeUtils.disposeQuietly(featureSet)
        except:
            logger("Not able dispose export images feature set", LOGGER_ERROR)
Esempio n. 24
0
    def check(self, taskStatus, report, feature1):
        #SimpleTaskStatus taskStatus,
        #TopologyReport report,
        #Feature feature1

        try:
            print "Starts with: ", feature1.Name
            logger("si", LOGGER_INFO)

            if (self.expression == None):
                manager = ExpressionEvaluatorLocator.getManager()
                self.expression = manager.createExpression()
                self.expressionBuilder = manager.createExpressionBuilder()
                self.geomName = feature1.getType(
                ).getDefaultGeometryAttributeName()

            line = feature1.getDefaultGeometry()

            if line == None:
                return

            tolerance = self.getTolerance()
            numVertexLine = line.getNumVertices()
            lista = [line.getVertex(0), line.getVertex(numVertexLine - 1)]

            for vertex in lista:
                noError = False
                print "One end of the line ", feature1.get(
                    "Name"), "is: ", vertex

                if tolerance != 0:
                    vertexTolerance = vertex.buffer(tolerance)
                else:
                    vertexTolerance = vertex

                theDataSet = self.getDataSet1()
                if theDataSet.getSpatialIndex() != None:
                    for reference in theDataSet.query(vertexTolerance):
                        #FeatureReference reference

                        feature = reference.getFeature()
                        otherLine = feature.getDefaultGeometry()

                        print "Analyzing vertex of ", feature1.Name, " with line ", feature.Name

                        if (reference.equals(feature1.getReference())):
                            print "Same entity"
                            print numVertexLine
                            if numVertexLine > 2:
                                endVertex = line.getVertex(0)
                                print type(endVertex)
                                cloneLine = line.cloneGeometry()
                                if lista.index(vertex) == 0:
                                    cloneLine.removeVertex(0)
                                    if cloneLine.intersects(vertexTolerance):
                                        print "Intersects with itself"
                                        noError = True

                                    else:
                                        print "No intersects with itself"
                                else:
                                    cloneLine.removeVertex(numVertexLine - 1)
                                    if cloneLine.intersects(vertexTolerance):
                                        print "Intersects with itself"
                                        noError = True

                                    else:
                                        print "No intersects with itself"

                        if (vertexTolerance.intersects(otherLine)
                                and not line.equals(otherLine)):
                            print "Intersects vertex", feature1.Name, " with line ", feature.Name
                            noError = True
                            break

                    logger("previous report", LOGGER_INFO)
                    if noError == False:
                        error = vertex
                        ver = vertex.convertToWKT()
                        logger("report", LOGGER_INFO)
                        print "The mistake is: ", error
                        report.addLine(self, theDataSet, None, line, error,
                                       feature1.getReference(), None, 0, 0,
                                       False, "The point is dangling", ver)

                    else:
                        print "Intersects"

            else:
                logger("else", LOGGER_INFO)
                self.expression.setPhrase(
                    self.expressionBuilder.ifnull(
                        self.expressionBuilder.column(self.geomName),
                        self.expressionBuilder.constant(False),
                        self.expressionBuilder.ST_Overlaps(
                            self.expressionBuilder.column(self.geomName),
                            self.expressionBuilder.geometry(line))).toString())
                feature = theDataSet.findFirst(self.expression)
                if feature != None:
                    otherPoint = feature.getDefaultGeometry()
                    error = None
                    if otherPoint != None:
                        error = point.difference(otherPoint)

                    report.addLine(self, theDataSet, None, point, error,
                                   feature1.getReference(), None, False,
                                   "The point is dangling")
                logger("end", LOGGER_INFO)
        except:
            #logger("2 Can't check feature."+str(ex), LOGGER_WARN)
            ex = sys.exc_info()[1]
            logger("Can't execute rule. Class Name:" + ex.__class__.__name__ +
                   " Except:" + str(ex))
        finally:
            pass
Esempio n. 25
0
 def checkGaps(self, polygon1, theDataSet2, tolerance1):
     result = [False, []]
     if theDataSet2.getSpatialIndex() != None:
         if not self.hasGaps: 
             self.findGaps(polygon1, theDataSet2, tolerance1)
         if self.hasGaps:
             result[0] = True
             self.hasGaps = False
     else:
         if self.expression == None:
             self.expression = ExpressionEvaluatorLocator.getManager().createExpression()
             self.expressionBuilder = ExpressionEvaluatorLocator.getManager().createExpressionBuilder()
             # self.expressionBuilder = GeometryExpressionEvaluatorLocator.getManager().createExpressionBuilder()
             store2 = theDataSet2.getFeatureStore()
             self.geomName = store2.getDefaultFeatureType().getDefaultGeometryAttributeName()
         self.expression.setPhrase(
             self.expressionBuilder.ifnull(
                 self.expressionBuilder.column(self.geomName),
                 self.expressionBuilder.constant(False),
                 self.expressionBuilder.and(
                     self.expressionBuilder.ST_Intersects(
                         self.expressionBuilder.geometry(polygon1),
                         self.expressionBuilder.ST_Difference(
                             self.expressionBuilder.ST_MakePolygon(
                                 self.expressionBuilder.ST_ExteriorRing(
                                     self.expressionBuilder.ST_Union(
                                         self.expressionBuilder.geometry(polygon1),
                                         self.expressionBuilder.column(self.geomName)
                                     )
                                 )
                             ),
                             self.expressionBuilder.ST_Union(
                                 self.expressionBuilder.geometry(polygon1),
                                 self.expressionBuilder.column(self.geomName)
                             )
                         )
                     ),
                     self.expressionBuilder.gt(
                         self.expressionBuilder.ST_Length(
                             self.expressionBuilder.ST_Intersection(
                                 self.expressionBuilder.geometry(polygon1),
                                     self.expressionBuilder.ST_Difference(
                                         self.expressionBuilder.ST_MakePolygon(
                                             self.expressionBuilder.ST_ExteriorRing(
                                                 self.expressionBuilder.ST_Union(
                                                     self.expressionBuilder.geometry(polygon1),
                                                     self.expressionBuilder.column(self.geomName)
                                                 )
                                             )
                                         ),
                                         self.expressionBuilder.ST_Union(
                                             self.expressionBuilder.geometry(polygon1),
                                             self.expressionBuilder.column(self.geomName)
                                         )
                                     )
                             )
                         ),
                         self.expressionBuilder.constant(0.0)
                     )
                 )
             ).toString()
         )
         if theDataSet2.findFirst(self.expression) != None:
             result[0] = True
     return result
def processImportFields(tableTarget,
                        fieldTarget,
                        tableSource,
                        fieldSource,
                        data,
                        translator,
                        taskStatus=None):
    ### Init processimportfields"
    # Update ft
    #translator = NamesTranslator.createTrimTranslator(11)

    storeTarget = tableTarget.getFeatureStore()
    storeSource = tableSource.getFeatureStore()
    ftTarget = storeTarget.getDefaultFeatureType()
    ftSource = storeSource.getDefaultFeatureType()

    #Names translator init
    #for attr in ftTarget:
    #  translator.addSource(attr.getName())
    #
    if storeTarget == storeSource:
        logger("Can't use same store for import tables", LOGGER_ERROR)
        return
    # Checks
    ## Ningun del nombre de los campos nuevos usados existe ya en la tabla previa
    for d in data:
        used = ftTarget.getAttributeDescriptor(d['idname'])
        if used != None:
            logger("Field " + d['idname'] + " already created in table",
                   LOGGER_ERROR)
            return

    # Process
    newftTarget = gvsig.createFeatureType(ftTarget)
    newftSource = gvsig.createFeatureType(ftSource)

    for d in data:
        name = d["idfield"]
        descriptor = newftSource.getEditableAttributeDescriptor(name)
        newname = d["idname"]
        descriptor.setName(newname)
        newftTarget.addLike(descriptor)

    try:
        storeTarget.edit()
        storeTarget.update(newftTarget)
        storeTarget.commit()
    except:
        logger("Not able to update feature type", LOGGER_ERROR)
        return

    # Update values
    storeTarget.edit()
    fsetSource = tableSource.getFeatureStore().getFeatureSet()

    if taskStatus != None:
        taskStatus.setRangeOfValues(0, fsetSource.getSize())
        taskStatus.setCurValue(0)
        taskStatus.add()

    for fSource in fsetSource:
        if taskStatus != None and taskStatus.isCancellationRequested():
            break
        if taskStatus != None:
            taskStatus.incrementCurrentValue()
        # QUERY
        builder = storeTarget.createExpressionBuilder()
        ## Eq expression
        expFilter = builder.eq(builder.column(fieldTarget),
                               builder.constant(
                                   fSource.get(fieldSource))).toString()

        exp = ExpressionEvaluatorLocator.getManager().createExpression()
        exp.setPhrase(expFilter)
        evaluator = DALLocator.getDataManager().createExpresion(exp)
        #filterValue = str(field2)+"="+str(fTarget.get(fieldTarget))
        fqTarget = storeTarget.createFeatureQuery()
        fqTarget.setFilter(evaluator)

        #for d in data: #need al attributos to get editable valid
        #  if not ftSource.getAttributeDescriptor(d["idfield"]).isReadOnly():
        #    fq1.addAttributeName(d["idname"])
        #defaultGeometry =  ftTarget.getDefaultGeometryAttributeName()
        #fqTarget.addAttributeName(defaultGeometry)
        fqTarget.retrievesAllAttributes()

        # UPDATE VALUES
        fsetTarget = storeTarget.getFeatureSet(fqTarget)
        for ftTarget in fsetTarget:
            efTarget = ftTarget.getEditable()
            for d in data:
                if newftTarget.getAttributeDescriptor(
                        d["idname"]).isReadOnly():
                    #logger("Field is read only", LOGGER_WARN)
                    continue
                value = fSource.get(d["idfield"])
                efTarget.set(d["idname"], value)
            fsetTarget.update(efTarget)
        if storeTarget.canCommitChanges(
        ) and storeTarget.getPendingChangesCount() > 100000:
            storeTarget.commitChanges()
    storeTarget.commit()
    try:
        pass
    except:
        ex = sys.exc_info()[1]
        logger("Not able to update features value: " + str(ex), LOGGER_ERROR)
        try:
            DisposeUtils.disposeQuietly(fsetTarget)
            DisposeUtils.disposeQuietly(fsetSource)
            store1.cancelEditing()
        except:
            logger("Not able to cancel editing", LOGGER_ERROR)
    finally:
        DisposeUtils.disposeQuietly(fsetTarget)
        DisposeUtils.disposeQuietly(fsetSource)
Esempio n. 27
0
  def check(self, taskStatus, report, feature1):
    #SimpleTaskStatus taskStatus, 
    #TopologyReport report, 
    #Feature feature1

    try:

      if (self.expression == None):
        manager = ExpressionEvaluatorLocator.getManager()
        self.expression = manager.createExpression()
        self.expressionBuilder = manager.createExpressionBuilder()
        self.geomName = feature1.getType().getDefaultGeometryAttributeName()

      point = feature1.getDefaultGeometry()
      tolerance = self.getTolerance()
      pointTolerance = point.buffer(tolerance)

      if point==None:
        return

      if pointTolerance==None:
        pointTolerance = point

      theDataSet = self.getDataSet1()
      if theDataSet.getSpatialIndex() != None:
        for reference in theDataSet.query(pointTolerance):
            #FeatureReference reference
            # Same feature
            if reference.equals(feature1.getReference()):
              continue;
            
            feature = reference.getFeature()
            otherPoint = feature.getDefaultGeometry()
            if otherPoint!=None and not pointTolerance.disjoint(otherPoint):
              error = point
              report.addLine(self,
                theDataSet,
                None,
                point,
                error,
                feature1.getReference(),
                None,
                -1,
                -1,
                False,
                "The point is not disjoint.",
                ""
              )
              break
            
      else:
        logger("else", LOGGER_INFO)
        self.expression.setPhrase(self.expressionBuilder.ifnull(
            self.expressionBuilder.column(self.geomName),
            self.expressionBuilder.constant(False),
            self.expressionBuilder.ST_Disjoint(
              self.expressionBuilder.column(self.geomName),
              self.expressionBuilder.geometry(pointTolerance)
            )
          ).toString()
        )

        feature = theDataSet.findFirst(self.expression)
        if feature != None:
            otherPoint = feature.getDefaultGeometry()
            error = None
            if otherPoint != None:
              error = point
              
            report.addLine(self,
              theDataSet,
              None,
              point,
              error,
              feature1.getReference(),
              None,
              -1,
              -1,
              False,
              "The point is not disjoint."
              ""
            )
    except:
      ex = sys.exc_info()[1]
      logger("Can't execute rule. Class Name:" + ex.__class__.__name__ + " Except:" + str(ex))
    finally:
      pass