Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/gt2/GT2Quadtree.java
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/gt2/GT2Quadtree.java	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/gt2/GT2Quadtree.java	(revision 38486)
@@ -0,0 +1,401 @@
+/*
+ * Created on 16-may-2006
+ *
+ * gvSIG. Sistema de Informaci�n Geogr�fica de la Generalitat Valenciana
+ *
+ * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
+ *
+ * For more information, contact:
+ *
+ *  Generalitat Valenciana
+ *   Conselleria d'Infraestructures i Transport
+ *   Av. Blasco Ib��ez, 50
+ *   46010 VALENCIA
+ *   SPAIN
+ *
+ *      +34 963862235
+ *   gvsig@gva.es
+ *      www.gvsig.gva.es
+ *
+ *    or
+ *
+ *   IVER T.I. S.A
+ *   Salamanca 50
+ *   46005 Valencia
+ *   Spain
+ *
+ *   +34 963163400
+ *   dac@iver.es
+ */
+/* CVS MESSAGES:
+ *
+ * $Id: QuadtreeGt2.java 10627 2007-03-06 17:10:21Z caballero $
+ * $Log$
+ * Revision 1.3  2007-03-06 17:08:59  caballero
+ * Exceptions
+ *
+ * Revision 1.2  2006/11/29 19:27:59  azabala
+ * bug fixed (caused when we query for a bbox which is greater or equal to a layer bbox)
+ *
+ * Revision 1.1  2006/05/24 21:58:04  azabala
+ * *** empty log message ***
+ *
+ *
+ */
+package org.gvsig.fmap.dal.index.spatial.gt2;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Stack;
+
+import com.vividsolutions.jts.geom.Envelope;
+
+import org.geotools.index.quadtree.Node;
+import org.geotools.index.quadtree.QuadTree;
+import org.geotools.index.quadtree.StoreException;
+import org.geotools.index.quadtree.fs.FileSystemIndexStore;
+import org.geotools.index.quadtree.fs.IndexHeader;
+
+import org.gvsig.fmap.dal.exception.DataException;
+import org.gvsig.fmap.dal.exception.InitializeException;
+import org.gvsig.fmap.dal.feature.FeatureStore;
+import org.gvsig.fmap.dal.feature.exception.FeatureIndexException;
+import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
+import org.gvsig.fmap.dal.feature.spi.index.AbstractFeatureIndexProvider;
+import org.gvsig.fmap.dal.feature.spi.index.FeatureIndexProvider;
+import org.gvsig.fmap.geom.Geometry;
+import org.gvsig.fmap.geom.primitive.Point;
+import org.gvsig.tools.exception.BaseException;
+
+/**
+ * This Quadtree spatial index implementation is based in a fork of
+ * org.geotools.index.quadtree.Quadtree implementation. <br>
+ * This implementation offers us:
+ * <ol>
+ * <li>Persistence of spatial index</li>
+ * </ol>
+ * We had to fork geotools quadtree for many reasons:
+ * <ol>
+ * <li>It was strongly dependent of SHP format, so it returned not only a num of
+ * rectangle, it also returned byte offset of this rectangle in shp file</li>
+ * <li>Query artifact wasnt run well at all</li>
+ * </ol>
+ * 
+ * @author azabala
+ * 
+ */
+public class GT2Quadtree extends AbstractFeatureIndexProvider implements
+    FeatureIndexProvider {
+
+    public static final String NAME = GT2Quadtree.class.getSimpleName();
+    /**
+     * Geotools quadtree implementation
+     */
+    QuadTree quadtree;
+    /**
+     * Persistent storage
+     */
+    String fileName;
+    /**
+     * Spatial index file extension
+     */
+    final String qExt = ".qix";
+    /**
+     * qix format has many versions, and allows different byte orders.
+     */
+    String byteOrder;
+    /**
+     * Bounds of the layer to index
+     */
+    // Envelope bounds;
+    /**
+     * Number of records of the layer to index
+     */
+    // int numRecs = 0;
+
+    boolean inMemory = false;
+
+    public GT2Quadtree() {
+
+    }
+
+    @Override
+    public void initialize() throws InitializeException {
+        try {
+            File file =
+                File.createTempFile(getFeatureStore().getName(), ".qix");
+            this.fileName = file.getAbsolutePath();
+            this.byteOrder = "NM";
+            this.quadtree = createQuadTree();
+            if (exists()) {
+                load();
+            }
+        } catch (IOException e) {
+            throw new InitializeException(e);
+        } catch (BaseException e) {
+            throw new InitializeException(e);
+        }
+    }
+
+    /**
+     * @return
+     * @throws DataException
+     */
+    private QuadTree createQuadTree() throws DataException {
+        org.gvsig.fmap.geom.primitive.Envelope env =
+            getFeatureStore().getEnvelope();
+        int featureCount = (int) getFeatureStore().getFeatureCount();
+        return new QuadTree(featureCount, toJtsEnvelope(env));
+    }
+
+    /**
+     * If the spatial index file exists and has content
+     */
+    public boolean exists() {
+        return (new File(fileName).length() != 0);
+    }
+
+    public void load() throws FeatureIndexException {
+        if (quadtree == null) {
+            load(new File(fileName));
+        }
+    }
+
+    public void load(File f) throws FeatureIndexException {
+        try {
+            FileSystemIndexStore store = new FileSystemIndexStore(f);
+            quadtree = store.load();
+            this.fileName = f.getAbsolutePath();
+        } catch (StoreException e) {
+            throw new FeatureIndexException(e);
+        }
+    }
+
+    /**
+     * Inserts an object in the index
+     */
+    public void insert(org.gvsig.fmap.geom.primitive.Envelope env, int index) {
+        if (env == null) {
+            throw new IllegalArgumentException("Envelope cannot be null");
+        }
+        Envelope e = toJtsEnvelope(env);
+        if (e == null) {
+            throw new IllegalStateException(
+                "JTS Envelope conversion returns null");
+        }
+        System.out.println("recno=" + index);
+        if (quadtree == null) {
+            throw new IllegalStateException("quadtree is null");
+        }
+        try {
+            quadtree.insert(index, toJtsEnvelope(env));
+        } catch (StoreException se) {
+            // TODO Auto-generated catch block
+            se.printStackTrace();
+        }
+    }
+
+    public void delete(org.gvsig.fmap.geom.primitive.Envelope env, int index) {
+        if (inMemory) {
+            quadtree.delete(toJtsEnvelope(env), index);
+        }
+    }
+
+    public Envelope toJtsEnvelope(org.gvsig.fmap.geom.primitive.Envelope env) {
+        if (env == null) {
+            return null;
+        }
+        Point min = env.getLowerCorner();
+        Point max = env.getUpperCorner();
+
+        return new Envelope(min.getX(), max.getX(), min.getY(), max.getY());
+    }
+
+    /**
+     * 
+     * @throws StoreException
+     * @deprecated
+     */
+    @Deprecated
+    void openQuadTree() throws StoreException {
+        if (quadtree == null) {
+            File file = new File(this.fileName);
+            // Intento de cargar todo el quadtree en memoria
+            FileSystemIndexStore store = new FileSystemIndexStore(file);
+            quadtree = store.load();
+        }
+    }
+
+    void openQuadTreeInMemory() throws StoreException {
+        if (quadtree == null) {
+            File file = new File(fileName);
+            // Intento de cargar todo el quadtree en memoria
+            FileSystemIndexStore store = new FileSystemIndexStore(file);
+            QuadTree filequadtree = store.load();
+            quadtree =
+                new QuadTree(filequadtree.getNumShapes(),
+                    filequadtree.getMaxDepth(), filequadtree.getRoot()
+                        .getBounds());
+            Stack nodes = new Stack();
+            nodes.push(filequadtree.getRoot());
+            while (nodes.size() != 0) {
+                Node node = (Node) nodes.pop();
+                Envelope nodeEnv = node.getBounds();
+                int[] shapeIds = node.getShapesId();
+                for (int i = 0; i < shapeIds.length; i++) {
+                    quadtree.insert(shapeIds[i], nodeEnv);
+                }
+                int numSubnodes = node.getNumSubNodes();
+                for (int i = 0; i < numSubnodes; i++) {
+                    nodes.push(node.getSubNode(i));
+                }
+            }// while
+            filequadtree.close();
+        }
+    }
+
+    public void flush() throws FeatureIndexException {
+        flush(new File(fileName));
+    }
+
+    public void flush(File f) throws FeatureIndexException {
+        byte order = 0;
+        if ((byteOrder == null) || byteOrder.equalsIgnoreCase("NM")) {
+            order = IndexHeader.NEW_MSB_ORDER;
+        } else
+            if (byteOrder.equalsIgnoreCase("NL")) {
+                order = IndexHeader.NEW_LSB_ORDER;
+            }
+        FileSystemIndexStore store = new FileSystemIndexStore(f, order);
+        try {
+            store.store(quadtree);
+            this.fileName = f.getAbsolutePath();
+        } catch (StoreException e) {
+            throw new FeatureIndexException(e);
+        }
+    }
+
+    public File getFile() {
+        return new File(this.fileName);
+    }
+
+    private FeatureStore getFeatureStore() {
+        return getFeatureIndexProviderServices()
+            .getFeatureStoreProviderServices().getFeatureStore();
+    }
+
+    public void delete(Object value, FeatureReferenceProviderServices fref) {
+
+        if (!isCompatibleOID(fref.getOID())) {
+            throw new IllegalArgumentException(
+                "OID not compatible. Must be an instance of Number within the Integer range.");
+        }
+
+        delete(((org.gvsig.fmap.geom.Geometry) value).getEnvelope(),
+            ((Number) fref.getOID()).intValue());
+    }
+
+    public void insert(Object value, FeatureReferenceProviderServices fref) {
+
+        if (!isCompatibleOID(fref.getOID())) {
+            throw new IllegalArgumentException(
+                "OID not compatible. Must be an instance of Number within the Integer range.");
+        }
+
+        insert(((org.gvsig.fmap.geom.Geometry) value).getEnvelope(),
+            ((Number) fref.getOID()).intValue());
+    }
+
+    public List match(Object value) throws FeatureIndexException {
+        if (quadtree == null) {
+            throw new IllegalStateException("This quadtree is null.");
+        }
+        if (value == null) {
+            throw new IllegalArgumentException("Envelope cannot be null.");
+        }
+        if (!(value instanceof org.gvsig.fmap.geom.primitive.Envelope)) {
+            throw new IllegalArgumentException("Not an envelope.");
+        }
+        org.gvsig.fmap.geom.primitive.Envelope env = null;
+        if (value instanceof org.gvsig.fmap.geom.primitive.Envelope) {
+            env = (org.gvsig.fmap.geom.primitive.Envelope) value;
+        } else
+            if (value instanceof Geometry) {
+                env = ((Geometry) value).getEnvelope();
+            }
+        return new LongList(quadtree.query(toJtsEnvelope(env)));
+    }
+
+    public List nearest(int count, Object value) throws FeatureIndexException {
+        throw new UnsupportedOperationException();
+    }
+
+    public boolean isMatchSupported() {
+        return true;
+    }
+
+    public boolean isNearestSupported() {
+        return false;
+    }
+
+    public boolean isNearestToleranceSupported() {
+        return false;
+    }
+
+    public boolean isRangeSupported() {
+        return false;
+    }
+
+    public List nearest(int count, Object value, Object tolerance)
+        throws FeatureIndexException {
+        throw new UnsupportedOperationException();
+    }
+
+    public List range(Object value1, Object value2)
+        throws FeatureIndexException {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Indicates whether the given OID's type is compatible
+     * with this provider
+     * 
+     * @param oid
+     * 
+     * @return
+     *         true if this index provider supports the given oid type
+     */
+    private boolean isCompatibleOID(Object oid) {
+        if (!(oid instanceof Number)) {
+            return false;
+        }
+
+        long num = ((Number) oid).longValue();
+
+        if ((num > Integer.MAX_VALUE) || (num < Integer.MIN_VALUE)) {
+            return false;
+        }
+
+        return true;
+    }
+
+    public void clear() throws DataException {
+        this.quadtree = createQuadTree();
+    }
+
+}
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/gt2/Gt2IndexLibrary.java
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/gt2/Gt2IndexLibrary.java	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/gt2/Gt2IndexLibrary.java	(revision 38486)
@@ -0,0 +1,58 @@
+/* gvSIG. Geographic Information System of the Valencian Government
+*
+* Copyright (C) 2007-2008 Infrastructures and Transports Department
+* of the Valencian Government (CIT)
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+* MA  02110-1301, USA.
+*
+*/
+
+/*
+* AUTHORS (In addition to CIT):
+* 2008 {{Company}}   {{Task}}
+*/
+
+
+package org.gvsig.fmap.dal.index.spatial.gt2;
+
+import org.gvsig.fmap.dal.DALLibrary;
+import org.gvsig.fmap.dal.DALLocator;
+import org.gvsig.fmap.dal.DataTypes;
+import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
+import org.gvsig.tools.library.AbstractLibrary;
+import org.gvsig.tools.library.LibraryException;
+
+public class Gt2IndexLibrary extends AbstractLibrary {
+
+    @Override
+    public void doRegistration() {
+        registerAsServiceOf(DALLibrary.class);
+    }
+
+	@Override
+	protected void doInitialize() throws LibraryException {
+	}
+
+	@Override
+	protected void doPostInitialize() throws LibraryException {
+    	DataManagerProviderServices man = (DataManagerProviderServices) DALLocator.getDataManager();
+
+    	if (!man.getFeatureIndexProviders().contains(GT2Quadtree.NAME)) {
+			man.registerFeatureIndexProvider(GT2Quadtree.NAME, "Quadtree index based on Geotools 2",
+					GT2Quadtree.class, DataTypes.GEOMETRY);
+    	}
+	}
+}
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jts/JTSQuadtree.java
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jts/JTSQuadtree.java	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jts/JTSQuadtree.java	(revision 38486)
@@ -0,0 +1,170 @@
+/*
+ * Created on 28-abr-2006
+ *
+ * gvSIG. Sistema de Informaci�n Geogr�fica de la Generalitat Valenciana
+ *
+ * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
+ *
+ * For more information, contact:
+ *
+ *  Generalitat Valenciana
+ *   Conselleria d'Infraestructures i Transport
+ *   Av. Blasco Ib��ez, 50
+ *   46010 VALENCIA
+ *   SPAIN
+ *
+ *      +34 963862235
+ *   gvsig@gva.es
+ *      www.gvsig.gva.es
+ *
+ *    or
+ *
+ *   IVER T.I. S.A
+ *   Salamanca 50
+ *   46005 Valencia
+ *   Spain
+ *
+ *   +34 963163400
+ *   dac@iver.es
+ */
+/* CVS MESSAGES:
+ *
+ * $Id: QuadtreeJts.java 11288 2007-04-19 17:32:50Z azabala $
+ * $Log$
+ * Revision 1.2  2007-04-19 17:32:50  azabala
+ * new constructor (fmap spatial index from an existing jts spatial index)
+ *
+ * Revision 1.1  2006/05/01 18:38:41  azabala
+ * primera version en cvs del api de indices espaciales
+ *
+ *
+ */
+package org.gvsig.fmap.dal.index.spatial.jts;
+
+import java.util.List;
+
+import com.vividsolutions.jts.geom.Envelope;
+import com.vividsolutions.jts.index.quadtree.Quadtree;
+
+import org.gvsig.fmap.dal.exception.DataException;
+import org.gvsig.fmap.dal.feature.exception.FeatureIndexException;
+import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
+import org.gvsig.fmap.dal.feature.spi.index.AbstractFeatureIndexProvider;
+import org.gvsig.fmap.dal.feature.spi.index.FeatureIndexProvider;
+import org.gvsig.fmap.geom.Geometry;
+import org.gvsig.fmap.geom.primitive.NullGeometry;
+import org.gvsig.fmap.geom.primitive.Point;
+
+/**
+ * Adapter for ISPatialIndex gvSIG's interface to
+ * JTS Quadtree.
+ * 
+ * 
+ * @author azabala
+ * 
+ */
+public class JTSQuadtree extends AbstractFeatureIndexProvider implements
+    FeatureIndexProvider {
+
+    public static final String NAME = JTSQuadtree.class.getName();
+
+    private Quadtree quadtree;
+
+    public JTSQuadtree() {
+    }
+
+    public void initialize() {
+        quadtree = createQuadtree();
+    }
+
+    private Quadtree createQuadtree() {
+        return new Quadtree();
+    }
+
+    private Envelope fromEnvelope(org.gvsig.fmap.geom.primitive.Envelope env) {
+        Point min = env.getLowerCorner();
+        Point max = env.getUpperCorner();
+        Envelope env2 =
+            new Envelope(min.getX(), max.getX(), min.getY(), max.getY());
+        return env2;
+    }
+
+    public void delete(Object o, FeatureReferenceProviderServices fref) {
+        Integer integer = new Integer(((Long) (fref).getOID()).intValue());
+        quadtree.remove(fromEnvelope(((Geometry) o).getEnvelope()), integer);
+    }
+
+    public void insert(Object o, FeatureReferenceProviderServices fref) {
+        if (o == null || o instanceof NullGeometry) {
+            return;
+        }
+        Integer integer = new Integer(((Long) (fref).getOID()).intValue());
+        quadtree.insert(fromEnvelope(((Geometry) o).getEnvelope()), integer);
+
+    }
+
+    public List match(Object value) throws FeatureIndexException {
+        org.gvsig.fmap.geom.primitive.Envelope env = null;
+        if (value instanceof org.gvsig.fmap.geom.primitive.Envelope) {
+            env = (org.gvsig.fmap.geom.primitive.Envelope) value;
+        } else
+            if (value instanceof Geometry) {
+                env = ((Geometry) value).getEnvelope();
+            }
+        return new LongList(quadtree.query(fromEnvelope(env)));
+    }
+
+    public List match(Object min, Object max) {
+        throw new UnsupportedOperationException(
+            "Can't perform this kind of search.");
+    }
+
+    public List nearest(int count, Object value) throws FeatureIndexException {
+        throw new UnsupportedOperationException(
+            "Can't perform this kind of search.");
+    }
+
+    public boolean isMatchSupported() {
+        return true;
+    }
+
+    public boolean isNearestSupported() {
+        return false;
+    }
+
+    public boolean isNearestToleranceSupported() {
+        return false;
+    }
+
+    public boolean isRangeSupported() {
+        return false;
+    }
+
+    public List nearest(int count, Object value, Object tolerance)
+        throws FeatureIndexException {
+        throw new UnsupportedOperationException();
+    }
+
+    public List range(Object value1, Object value2)
+        throws FeatureIndexException {
+        throw new UnsupportedOperationException();
+    }
+
+    public void clear() throws DataException {
+        quadtree = createQuadtree();
+    }
+}
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jts/JTSIndexLibrary.java
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jts/JTSIndexLibrary.java	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jts/JTSIndexLibrary.java	(revision 38486)
@@ -0,0 +1,58 @@
+/* gvSIG. Geographic Information System of the Valencian Government
+*
+* Copyright (C) 2007-2008 Infrastructures and Transports Department
+* of the Valencian Government (CIT)
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+* MA  02110-1301, USA.
+*
+*/
+
+/*
+* AUTHORS (In addition to CIT):
+* 2008 {{Company}}   {{Task}}
+*/
+
+package org.gvsig.fmap.dal.index.spatial.jts;
+
+import org.gvsig.fmap.dal.DALLibrary;
+import org.gvsig.fmap.dal.DALLocator;
+import org.gvsig.fmap.dal.DataTypes;
+import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
+import org.gvsig.tools.library.AbstractLibrary;
+import org.gvsig.tools.library.LibraryException;
+
+public class JTSIndexLibrary extends AbstractLibrary {
+
+    @Override
+    public void doRegistration() {
+        registerAsServiceOf(DALLibrary.class);
+    }
+
+	protected void doInitialize() throws LibraryException {
+	}
+
+	protected void doPostInitialize() throws LibraryException {
+    	DataManagerProviderServices man = (DataManagerProviderServices) DALLocator.getDataManager();
+
+
+    	if (!man.getFeatureIndexProviders().contains(JTSQuadtree.NAME)) {
+			man.registerFeatureIndexProvider(JTSQuadtree.NAME, "Quadtree index based on JTS",
+					JTSQuadtree.class, DataTypes.GEOMETRY);
+			man.setDefaultFeatureIndexProviderName(DataTypes.GEOMETRY, JTSQuadtree.NAME);
+    	}
+	}
+}
+
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jsi/JSIIndexLibrary.java
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jsi/JSIIndexLibrary.java	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jsi/JSIIndexLibrary.java	(revision 38486)
@@ -0,0 +1,62 @@
+/* gvSIG. Geographic Information System of the Valencian Government
+*
+* Copyright (C) 2007-2008 Infrastructures and Transports Department
+* of the Valencian Government (CIT)
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+* MA  02110-1301, USA.
+*
+*/
+
+/*
+* AUTHORS (In addition to CIT):
+* 2008 {{Company}}   {{Task}}
+*/
+
+package org.gvsig.fmap.dal.index.spatial.jsi;
+
+import org.gvsig.fmap.dal.DALLibrary;
+import org.gvsig.fmap.dal.DALLocator;
+import org.gvsig.fmap.dal.DataTypes;
+import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
+import org.gvsig.tools.library.AbstractLibrary;
+import org.gvsig.tools.library.LibraryException;
+
+public class JSIIndexLibrary extends AbstractLibrary {
+
+    @Override
+    public void doRegistration() {
+        registerAsServiceOf(DALLibrary.class);
+    }
+
+	@Override
+	protected void doInitialize() throws LibraryException {
+	}
+
+	@Override
+	protected void doPostInitialize() throws LibraryException {
+    	DataManagerProviderServices man = (DataManagerProviderServices) DALLocator.getDataManager();
+
+    	if (!man.getFeatureIndexProviders().contains(JSIPersistentRTree.NAME)) {
+			man.registerFeatureIndexProvider(JSIPersistentRTree.NAME, "Persistent RTree index based on JSI",
+					JSIPersistentRTree.class, DataTypes.GEOMETRY);
+    	}
+
+    	if (!man.getFeatureIndexProviders().contains(JSIRTree.NAME)) {
+			man.registerFeatureIndexProvider(JSIRTree.NAME, "RTree index based on JSI",
+					JSIRTree.class, DataTypes.GEOMETRY);
+    	}
+	}
+}
\ No newline at end of file
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jsi/JSIRTree.java
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jsi/JSIRTree.java	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jsi/JSIRTree.java	(revision 38486)
@@ -0,0 +1,305 @@
+/*
+ * Created on 15-may-2006
+ *
+ * gvSIG. Sistema de Informaci�n Geogr�fica de la Generalitat Valenciana
+ *
+ * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
+ *
+ * For more information, contact:
+ *
+ *  Generalitat Valenciana
+ *   Conselleria d'Infraestructures i Transport
+ *   Av. Blasco Ib��ez, 50
+ *   46010 VALENCIA
+ *   SPAIN
+ *
+ *      +34 963862235
+ *   gvsig@gva.es
+ *      www.gvsig.gva.es
+ *
+ *    or
+ *
+ *   IVER T.I. S.A
+ *   Salamanca 50
+ *   46005 Valencia
+ *   Spain
+ *
+ *   +34 963163400
+ *   dac@iver.es
+ */
+/* CVS MESSAGES:
+ *
+ * $Id: RTreeJsi.java 13884 2007-09-19 16:26:04Z jaume $
+ * $Log$
+ * Revision 1.5  2007-09-19 16:25:39  jaume
+ * ReadExpansionFileException removed from this context and removed unnecessary imports
+ *
+ * Revision 1.4  2007/06/27 20:17:30  azabala
+ * new spatial index (rix)
+ *
+ * Revision 1.3  2007/03/06 17:08:59  caballero
+ * Exceptions
+ *
+ * Revision 1.2  2006/06/05 16:59:08  azabala
+ * implementada busqueda de vecino mas proximo a partir de rectangulos
+ *
+ * Revision 1.1  2006/05/24 21:58:04  azabala
+ * *** empty log message ***
+ *
+ *
+ */
+package org.gvsig.fmap.dal.index.spatial.jsi;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+
+import com.infomatiq.jsi.IntProcedure;
+import com.infomatiq.jsi.Rectangle;
+import com.infomatiq.jsi.rtree.RTree;
+
+import org.gvsig.fmap.dal.exception.DataException;
+import org.gvsig.fmap.dal.exception.InitializeException;
+import org.gvsig.fmap.dal.feature.exception.FeatureIndexException;
+import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
+import org.gvsig.fmap.dal.feature.spi.index.AbstractFeatureIndexProvider;
+import org.gvsig.fmap.dal.feature.spi.index.FeatureIndexProvider;
+import org.gvsig.fmap.geom.Geometry;
+import org.gvsig.fmap.geom.primitive.Envelope;
+import org.gvsig.fmap.geom.primitive.Point;
+
+/**
+ * RTree spatial index implementation based in library
+ * JSI (java spatial index).
+ * 
+ * http://jsi.sourceforge.net/
+ * 
+ * This RTree has better performance that Spatial Index Library
+ * RTree, and that JTS'RTree, because
+ * it uses the GNU's Trove Collections API.
+ * 
+ * We are doing some probes with it, because it offers
+ * a Nearest Neighbour algorithm implementation
+ * (useful for Spatial Join geoprocess, for example).
+ * 
+ * It isnt persistent, and We've found some problems
+ * with delete operations.
+ * 
+ * 
+ * 
+ * 
+ * @author azabala
+ * @author jyarza
+ * 
+ */
+public class JSIRTree extends AbstractFeatureIndexProvider implements
+    FeatureIndexProvider {
+
+    public static final String NAME = JSIRTree.class.getSimpleName();
+
+    protected RTree rtree;
+
+    public JSIRTree() {
+    }
+
+    public void initialize() throws InitializeException {
+        this.rtree = createRTree();
+    }
+
+    private RTree createRTree() {
+        RTree rtree = new RTree();
+        Properties props = new Properties();
+        // props.setProperty("MaxNodeEntries", "500");
+        // props.setProperty("MinNodeEntries", "200");
+        rtree.init(props);
+        return rtree;
+    }
+
+    class ListIntProcedure implements IntProcedure {
+
+        ArrayList solution = new ArrayList();
+
+        public boolean execute(int arg0) {
+            solution.add(new Integer(arg0));
+            return true;
+        }
+
+        public List getSolution() {
+            return solution;
+        }
+    }
+
+    protected List findNNearest(int numberOfNearest, Point point) {
+        com.infomatiq.jsi.Point jsiPoint =
+            new com.infomatiq.jsi.Point((float) point.getX(),
+                (float) point.getY());
+        return (List) rtree.nearest(jsiPoint, numberOfNearest);
+    }
+
+    public Iterator iterator() {
+        return rtree.iterator();
+    }
+
+    public int size() {
+        return rtree.size();
+    }
+
+    protected Rectangle toJsiRect(Envelope env) {
+        Point min = env.getLowerCorner();
+        Point max = env.getUpperCorner();
+
+        Rectangle jsiRect =
+            new Rectangle((float) min.getX(), (float) min.getY(),
+                (float) max.getX(), (float) max.getY());
+        return jsiRect;
+    }
+
+    public void insert(Object value, FeatureReferenceProviderServices fref) {
+        Envelope env = getEnvelope(value);
+
+        if (env == null) {
+            throw new IllegalArgumentException(
+                "value is neither Geometry or Envelope");
+        }
+
+        Object oid = fref.getOID();
+        if (!isCompatibleOID(oid)) {
+            throw new IllegalArgumentException("OID type not compatible: "
+                + oid.getClass().getName());
+        }
+
+        rtree.add(toJsiRect(env), ((Number) oid).intValue());
+    }
+
+    public void delete(Object value, FeatureReferenceProviderServices fref) {
+        Envelope env = getEnvelope(value);
+
+        if (env == null) {
+            throw new IllegalArgumentException(
+                "value is neither Geometry or Envelope");
+        }
+
+        Object oid = fref.getOID();
+        if (!isCompatibleOID(oid)) {
+            throw new IllegalArgumentException("OID type not compatible: "
+                + oid.getClass().getName());
+        }
+
+        rtree.delete(toJsiRect(env), ((Number) oid).intValue());
+    }
+
+    public List match(Object value) throws FeatureIndexException {
+        Envelope env = getEnvelope(value);
+
+        if (env == null) {
+            throw new IllegalArgumentException(
+                "value is neither Geometry or Envelope");
+        }
+        ListIntProcedure solution = new ListIntProcedure();
+        rtree.intersects(toJsiRect(env), solution);
+        return new LongList(solution.getSolution());
+    }
+
+    public List nearest(int count, Object value) {
+        if (value == null) {
+            throw new IllegalArgumentException("value is null");
+        }
+
+        if (value instanceof Point) {
+            Point p = (Point) value;
+            com.infomatiq.jsi.Point jsiPoint =
+                new com.infomatiq.jsi.Point((float) p.getDirectPosition()
+                    .getOrdinate(0), (float) p.getDirectPosition().getOrdinate(
+                    1));
+            return (List) rtree.nearest(jsiPoint, count);
+        } else {
+            Envelope env = getEnvelope(value);
+
+            if (env == null) {
+                throw new IllegalArgumentException(
+                    "value is neither Geometry or Envelope");
+            }
+            return new LongList((List) rtree.nearest(toJsiRect(env), count));
+        }
+    }
+
+    public boolean isMatchSupported() {
+        return true;
+    }
+
+    public boolean isNearestSupported() {
+        return true;
+    }
+
+    public boolean isNearestToleranceSupported() {
+        return false;
+    }
+
+    public boolean isRangeSupported() {
+        return false;
+    }
+
+    public List nearest(int count, Object value, Object tolerance)
+        throws FeatureIndexException {
+        throw new UnsupportedOperationException();
+    }
+
+    public List range(Object value1, Object value2)
+        throws FeatureIndexException {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Indicates whether the given OID's type is compatible
+     * with this provider
+     * 
+     * @param oid
+     * 
+     * @return
+     *         true if this index provider supports the given oid type
+     */
+    private boolean isCompatibleOID(Object oid) {
+        if (!(oid instanceof Number)) {
+            return false;
+        }
+
+        long num = ((Number) oid).longValue();
+
+        if (num > Integer.MAX_VALUE || num < Integer.MIN_VALUE) {
+            return false;
+        }
+
+        return true;
+    }
+
+    protected Envelope getEnvelope(Object value) {
+        Envelope env = null;
+
+        if (value instanceof Envelope) {
+            env = (Envelope) value;
+        } else
+            if (value instanceof Geometry) {
+                env = ((Geometry) value).getEnvelope();
+            }
+        return env;
+    }
+
+    public void clear() throws DataException {
+        rtree = createRTree();
+    }
+}
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jsi/JSIPersistentRTree.java
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jsi/JSIPersistentRTree.java	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/jsi/JSIPersistentRTree.java	(revision 38486)
@@ -0,0 +1,221 @@
+/*
+ * Created on 13-jun-2007
+ *
+ * gvSIG. Sistema de Informaci�n Geogr�fica de la Generalitat Valenciana
+ *
+ * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
+ *
+ * For more information, contact:
+ *
+ *  Generalitat Valenciana
+ *   Conselleria d'Infraestructures i Transport
+ *   Av. Blasco Ib��ez, 50
+ *   46010 VALENCIA
+ *   SPAIN
+ *
+ *      +34 963862235
+ *   gvsig@gva.es
+ *      www.gvsig.gva.es
+ *
+ *    or
+ *
+ *   IVER T.I. S.A
+ *   Salamanca 50
+ *   46005 Valencia
+ *   Spain
+ *
+ *   +34 963163400
+ *   dac@iver.es
+ */
+/* CVS MESSAGES:
+*
+* $Id: PersistentRTreeJsi.java 12380 2007-06-27 20:17:30Z azabala $
+* $Log$
+* Revision 1.1  2007-06-27 20:17:30  azabala
+* new spatial index (rix)
+*
+*
+*/
+package org.gvsig.fmap.dal.index.spatial.jsi;
+
+import java.awt.geom.Point2D;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.ByteOrder;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.FileChannel;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Properties;
+
+import javax.imageio.stream.FileImageOutputStream;
+
+import org.gvsig.fmap.dal.exception.InitializeException;
+import org.gvsig.fmap.dal.feature.exception.FeatureIndexException;
+import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
+import org.gvsig.fmap.geom.Geometry;
+import org.gvsig.fmap.geom.primitive.Envelope;
+
+import com.infomatiq.jsi.Rectangle;
+import com.infomatiq.jsi.rtree.RTree;
+
+/**
+ * Persistent spatial index which can resolve nearest neighbour queries.
+ * <br>
+ *
+ * To use:
+ *
+ * PersistentRTreeJsi sptidx = new PersistentRtreeJsi("/home/kk");
+ * if(sptidx.exists())
+ *  sptidx.load();
+ *
+ *
+ *  sptidx.add(rect, int);
+ *  ...
+ *  sptidx.add(rect2,int2);
+ *  sptidx.flush();
+ *
+ * @author azabala
+ *
+ */
+public class JSIPersistentRTree extends JSIRTree {
+
+	public static final String NAME = JSIPersistentRTree.class.getSimpleName();
+
+	/**
+	 * Spatial index file
+	 */
+	private File file;
+
+	private boolean hasChanged = false;
+	/**
+	 * Spatial index file extension
+	 */
+	final String rExt = ".rix";
+
+	private LinkedHashMap  rectangles;
+
+	public JSIPersistentRTree() {
+		super();
+	}
+
+	public void initialize() throws InitializeException {
+		super.initialize();
+		try {
+			file = File.createTempFile("RTreeJsi" + getFeatureIndexProviderServices().getTemporaryFileName(), rExt);
+			rectangles = new LinkedHashMap();
+			load(file);
+		} catch (IOException e) {
+			throw new InitializeException(e);
+		} catch (FeatureIndexException e) {
+			throw new InitializeException(e);
+		}
+	}
+
+	public void flush(File f) throws FeatureIndexException {
+		try {
+			if(! hasChanged) {
+				return;
+			}
+			RandomAccessFile file = new RandomAccessFile(f,
+															"rw");
+			FileImageOutputStream output = new FileImageOutputStream(file);
+			output.setByteOrder(ByteOrder.LITTLE_ENDIAN);
+			int numShapes = rtree.size();
+			output.writeInt(numShapes);
+
+			Iterator iterator = rtree.iterator();
+			int count = 0;
+			while(iterator.hasNext()){
+				Integer  idx = (Integer) iterator.next();
+				Rectangle nr = (Rectangle) rectangles.get(idx);
+				float xmin = nr.min[0];
+				float ymin = nr.min[1];
+
+				float xmax = nr.max[0];
+				float ymax = nr.max[1];
+
+				output.writeFloat(xmin);
+				output.writeFloat(ymin);
+				output.writeFloat(xmax);
+				output.writeFloat(ymax);
+
+				output.writeInt(idx.intValue());
+				count++;
+			}
+			output.flush();
+			output.close();
+			file.close();
+			hasChanged = false;
+		} catch (FileNotFoundException e) {
+			throw new FeatureIndexException(e);
+		} catch (IOException e) {
+			throw new FeatureIndexException(e);
+		}
+
+	}
+
+	private void load(File f) throws FeatureIndexException {
+		if (f == null) {
+			throw new IllegalArgumentException("File f cannot be null");
+		}
+
+		try {
+			if(! f.exists()){
+				return;
+			}
+			RandomAccessFile file = new RandomAccessFile(f, "r");
+			FileChannel channel = file.getChannel();
+			MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
+			buf.order(ByteOrder.LITTLE_ENDIAN);
+			int numShapes = buf.getInt();
+			for(int i = 0; i < numShapes; i++){
+				float xmin, ymin, xmax, ymax;
+				int shapeIndex;
+				xmin = buf.getFloat();
+				ymin = buf.getFloat();
+				xmax = buf.getFloat();
+				ymax = buf.getFloat();
+				shapeIndex = buf.getInt();
+
+				Rectangle jsiRect = new Rectangle(xmin, ymin, xmax, ymax);
+				rtree.add(jsiRect, shapeIndex);
+			}
+		}catch(Exception e){
+			throw new FeatureIndexException(e);
+		}
+	}
+
+	public void insert(Object value, FeatureReferenceProviderServices fref) {	
+		super.insert(value, fref);
+		Envelope env = getEnvelope(value);
+		rectangles.put(fref.getOID(), toJsiRect(env));
+		hasChanged = true;
+	}
+
+
+	public void delete(Object value, FeatureReferenceProviderServices fref) {
+		super.delete(value, fref);
+		rectangles.remove(fref.getOID());
+		hasChanged = true;
+	}
+
+}
+
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/spatialindex/SPTLIBIndexLibrary.java
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/spatialindex/SPTLIBIndexLibrary.java	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/spatialindex/SPTLIBIndexLibrary.java	(revision 38486)
@@ -0,0 +1,59 @@
+/* gvSIG. Geographic Information System of the Valencian Government
+*
+* Copyright (C) 2007-2008 Infrastructures and Transports Department
+* of the Valencian Government (CIT)
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+* MA  02110-1301, USA.
+*
+*/
+
+/*
+* AUTHORS (In addition to CIT):
+* 2008 {{Company}}   {{Task}}
+*/
+
+package org.gvsig.fmap.dal.index.spatial.spatialindex;
+
+import org.gvsig.fmap.dal.DALLibrary;
+import org.gvsig.fmap.dal.DALLocator;
+import org.gvsig.fmap.dal.DataTypes;
+import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
+import org.gvsig.tools.library.AbstractLibrary;
+import org.gvsig.tools.library.LibraryException;
+
+public class SPTLIBIndexLibrary extends AbstractLibrary {
+
+    @Override
+    public void doRegistration() {
+        registerAsServiceOf(DALLibrary.class);
+    }
+
+	@Override
+	protected void doInitialize() throws LibraryException {
+	}
+
+	@Override
+	protected void doPostInitialize() throws LibraryException {
+    	DataManagerProviderServices man = (DataManagerProviderServices) DALLocator.getDataManager();
+
+
+    	if (!man.getFeatureIndexProviders().contains(SPTLIBRTree.NAME)) {
+			man.registerFeatureIndexProvider(SPTLIBRTree.NAME, "RTree index based on spatialindex",
+					SPTLIBRTree.class, DataTypes.GEOMETRY);
+    	}
+	}
+}
+
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/spatialindex/SPTLIBRTree.java
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/spatialindex/SPTLIBRTree.java	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/src/org/gvsig/fmap/dal/index/spatial/spatialindex/SPTLIBRTree.java	(revision 38486)
@@ -0,0 +1,291 @@
+package org.gvsig.fmap.dal.index.spatial.spatialindex;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.gvsig.fmap.dal.exception.DataException;
+import org.gvsig.fmap.dal.exception.InitializeException;
+import org.gvsig.fmap.dal.feature.exception.FeatureIndexException;
+import org.gvsig.fmap.dal.feature.spi.FeatureReferenceProviderServices;
+import org.gvsig.fmap.dal.feature.spi.index.AbstractFeatureIndexProvider;
+import org.gvsig.fmap.dal.feature.spi.index.FeatureIndexProvider;
+import org.gvsig.fmap.geom.Geometry;
+import org.gvsig.fmap.geom.primitive.Envelope;
+import org.gvsig.fmap.geom.primitive.Point;
+
+import spatialindex.rtree.RTree;
+import spatialindex.spatialindex.IData;
+import spatialindex.spatialindex.INode;
+import spatialindex.spatialindex.IVisitor;
+import spatialindex.spatialindex.Region;
+import spatialindex.storagemanager.DiskStorageManager;
+import spatialindex.storagemanager.IBuffer;
+import spatialindex.storagemanager.IStorageManager;
+import spatialindex.storagemanager.PropertySet;
+import spatialindex.storagemanager.RandomEvictionsBuffer;
+
+/**
+ * <p>
+ * RTree spatial index based in spatial index library: <br>
+ * http://u-foria.org/marioh/spatialindex/index.html <br>
+ * marioh@cs.ucr.edu
+ * </p>
+ * It has the problem that spatial index file creation is a bit slowly (in
+ * comparation with other indexes).
+ */
+public class SPTLIBRTree extends AbstractFeatureIndexProvider implements
+    FeatureIndexProvider {
+
+    public static final String NAME = SPTLIBRTree.class.getSimpleName();
+    /**
+     * Page size of associated file
+     */
+    private static final int defaultPageSize = 32 * 1024;
+    private static final double defaultFillFactor = 0.85d;
+
+    /**
+     * Size of memory buffer of the index
+     */
+    private static final int BUFFER_SIZE = 25000;
+    RTree rtree;
+    String fileName;
+    IStorageManager diskfile;
+
+    public SPTLIBRTree() {
+
+    }
+
+    public void initialize() throws InitializeException {
+        try {
+            PropertySet ps = new PropertySet();
+            ps.setProperty("Overwrite", new Boolean(false));
+            // .idx and .dat extensions will be added.
+            fileName =
+                getFeatureIndexProviderServices().getNewFileName(null, null);
+            ps.setProperty("FileName", fileName);
+            ps.setProperty("PageSize", new Integer(defaultPageSize));
+            diskfile = new DiskStorageManager(ps);
+            rtree = createRTree();
+        } catch (SecurityException e) {
+            throw new InitializeException(e);
+        } catch (FileNotFoundException e) {
+            throw new InitializeException(e);
+        } catch (IOException e) {
+            throw new InitializeException(e);
+        }
+    }
+
+    /**
+     * If the spatial index file exists and has content
+     */
+    public boolean exists() {
+        return (new File(fileName + ".dat").length() != 0);
+    }
+
+    class RTreeVisitor implements IVisitor {
+
+        ArrayList solution = new ArrayList();
+
+        public void visitNode(INode n) {
+        }
+
+        public void visitData(IData d) {
+            solution.add(new Integer(d.getIdentifier()));
+        }
+
+        public List getSolution() {
+            return solution;
+        }
+    }
+
+    public List containtmentQuery(Envelope env) {
+        List solution = null;
+        Region region = createRegion(env);
+        RTreeVisitor visitor = new RTreeVisitor();
+        rtree.containmentQuery(region, visitor);
+        solution = visitor.getSolution();
+        return solution;
+    }
+
+    /**
+     * Warn! This RTree implemention doesnt care if 'index' entry has been
+     * indexed yet
+     */
+    public void insert(Envelope env, int index) {
+        rtree.insertData(null, createRegion(env), index);
+    }
+
+    private Region createRegion(Envelope env) {
+        double[] x = new double[2];
+        double[] y = new double[2];
+        x[0] = env.getLowerCorner().getX();
+        y[0] = env.getLowerCorner().getY();
+        x[1] = env.getUpperCorner().getX();
+        y[1] = env.getUpperCorner().getY();
+        return new Region(x, y);
+    }
+
+    /**
+     * Looks for N indexes nearest to the specified rect.
+     * 
+     * @param numberOfNearest
+     * @param rect
+     * @return
+     */
+    public List findNNearest(int numberOfNearest, Envelope env) {
+        List solution = null;
+        Region region = createRegion(env);
+        RTreeVisitor visitor = new RTreeVisitor();
+        rtree.nearestNeighborQuery(numberOfNearest, region, visitor);
+        solution = visitor.getSolution();
+        return solution;
+    }
+
+    /**
+     * Looks for the N indexes nearest to the specified point
+     * 
+     * @param numberOfNearest
+     * @param point
+     * @return
+     */
+    public List findNNearest(int numberOfNearest, Point point) {
+        List solution = null;
+        spatialindex.spatialindex.Point sptPoint =
+            new spatialindex.spatialindex.Point(new double[] { point.getX(),
+                point.getY() });
+        RTreeVisitor visitor = new RTreeVisitor();
+        rtree.nearestNeighborQuery(numberOfNearest, sptPoint, visitor);
+        solution = visitor.getSolution();
+        return solution;
+    }
+
+    public void flush() {
+        rtree.flush();
+    }
+
+    private RTree createRTree() {
+        // applies a main memory random buffer on top of the persistent
+        // storage manager
+        IBuffer buffer =
+            new RandomEvictionsBuffer(diskfile, BUFFER_SIZE, false);
+
+        // Create a new, empty, RTree with dimensionality 2, minimum load
+        // 70%, using "file" as
+        // the StorageManager and the RSTAR splitting policy.
+        PropertySet ps2 = new PropertySet();
+
+        Double f = new Double(defaultFillFactor);
+        ps2.setProperty("FillFactor", f);
+
+        Integer i = new Integer(2);
+        ps2.setProperty("Dimension", i);
+
+        File file = new File(fileName + ".dat");
+        if (file.length() != 0) {
+            ps2.setProperty("IndexIdentifier", new Integer(1));
+        }
+        return new RTree(ps2, buffer);
+    }
+
+    public void load(File f) throws FeatureIndexException {
+        createRTree();
+    }
+
+    public void flush(File f) throws FeatureIndexException {
+        flush();
+    }
+
+    public void close() {
+    }
+
+    public File getFile() {
+        return new File(fileName + ".dat");
+    }
+
+    public void delete(Object value, FeatureReferenceProviderServices fref) {
+        rtree.deleteData(createRegion(((Geometry) value).getEnvelope()),
+            ((Integer) fref.getOID()).intValue());
+    }
+
+    public void insert(Object value, FeatureReferenceProviderServices fref) {
+        Envelope env = null;
+        if (value instanceof Envelope) {
+            env = (Envelope) value;
+        } else
+            if (value instanceof Geometry) {
+                env = ((Geometry) value).getEnvelope();
+            }
+        rtree.insertData(null, createRegion(env),
+            ((Integer) fref.getOID()).intValue());
+    }
+
+    public List match(Object value) throws FeatureIndexException {
+        List solution = null;
+        Envelope env = null;
+        if (value instanceof Envelope) {
+            env = (Envelope) value;
+        } else
+            if (value instanceof Geometry) {
+                env = ((Geometry) value).getEnvelope();
+            }
+        Region region = createRegion(env);
+        RTreeVisitor visitor = new RTreeVisitor();
+        rtree.intersectionQuery(region, visitor);
+        solution = visitor.getSolution();
+        return new LongList(solution);
+    }
+
+    public List match(Object min, Object max) {
+        throw new UnsupportedOperationException();
+    }
+
+    public List nearest(int count, Object value) throws FeatureIndexException {
+        if (value instanceof Envelope) {
+            return this.findNNearest(count, (Envelope) value);
+        } else
+            if (value instanceof Point) {
+                return this.findNNearest(count, (Point) value);
+            } else
+                if (value instanceof Geometry) {
+                    return this.findNNearest(count,
+                        ((Geometry) value).getEnvelope());
+                } else {
+                    throw new IllegalArgumentException(
+                        "value must be either an Envelope or either a Point2D");
+                }
+    }
+
+    public boolean isMatchSupported() {
+        return true;
+    }
+
+    public boolean isNearestSupported() {
+        return true;
+    }
+
+    public boolean isNearestToleranceSupported() {
+        return false;
+    }
+
+    public boolean isRangeSupported() {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    public List nearest(int count, Object value, Object tolerance)
+        throws FeatureIndexException {
+        throw new UnsupportedOperationException();
+    }
+
+    public List range(Object value1, Object value2)
+        throws FeatureIndexException {
+        throw new UnsupportedOperationException();
+    }
+
+    public void clear() throws DataException {
+        rtree = createRTree();
+    }
+}
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/pom.xml
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/pom.xml	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/pom.xml	(revision 38486)
@@ -0,0 +1,366 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<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">
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>org.gvsig.fmap.dal.index.spatial
+	</artifactId>
+	<packaging>jar</packaging>
+	<version>2.0-SNAPSHOT</version>
+	<name>libFMap_dalindex</name>
+	<parent>
+		<groupId>org.gvsig</groupId>
+		<artifactId>gvsig-base-library-pom</artifactId>
+		<version>2.0-SNAPSHOT</version>
+	</parent>	
+	<properties>
+		<!-- gt2 -->
+		<gt2-jarIncludes>org/gvsig/fmap/dal/index/spatial/gt2/**
+		</gt2-jarIncludes>
+		<gt2-jarExcludes>NONE</gt2-jarExcludes>
+
+		<!-- jts -->
+		<jts-jarIncludes>org/gvsig/fmap/dal/index/spatial/jts/**
+		</jts-jarIncludes>
+		<jts-jarExcludes>NONE</jts-jarExcludes>
+
+		<!-- jsi -->
+		<jsi-jarIncludes>org/gvsig/fmap/dal/index/spatial/jsi/**
+		</jsi-jarIncludes>
+		<jsi-jarExcludes>NONE</jsi-jarExcludes>
+
+		<!-- spatialindex -->
+		<sptidx-jarIncludes>org/gvsig/fmap/dal/index/spatial/spatialindex/**
+		</sptidx-jarIncludes>
+		<sptidx-jarExcludes>NONE</sptidx-jarExcludes>
+
+		<build-dir>${basedir}/../build</build-dir>
+        <eclipse.project.name>libFMap_dalindex</eclipse.project.name>
+	</properties>
+
+	<dependencies>
+        <dependency>
+            <groupId>org.gvsig</groupId>
+            <artifactId>org.gvsig.tools.lib</artifactId>
+            <scope>compile</scope>
+        </dependency>
+		<dependency>
+			<groupId>org.gvsig</groupId>
+			<artifactId>org.gvsig.fmap.dal</artifactId>
+            <scope>compile</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.gvsig</groupId>
+			<artifactId>org.gvsig.fmap.dal</artifactId>
+			<classifier>spi</classifier>
+            <scope>compile</scope>
+		</dependency>
+        <dependency>
+            <groupId>org.gvsig</groupId>
+            <artifactId>org.gvsig.fmap.geometry</artifactId>
+            <scope>compile</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.gvsig</groupId>
+            <artifactId>org.gvsig.metadata.lib.basic.api</artifactId>
+            <scope>compile</scope>
+        </dependency>        
+        <dependency>
+            <groupId>org.gvsig</groupId>
+            <artifactId>org.gvsig.projection</artifactId>
+            <scope>compile</scope>
+        </dependency>
+		<dependency>
+			<groupId>com.vividsolutions</groupId>
+			<artifactId>jts</artifactId>
+            <scope>compile</scope>
+		</dependency>
+		<dependency>
+			<groupId>net.sf</groupId>
+			<artifactId>jsi</artifactId>
+            <scope>compile</scope>
+		</dependency>
+		<dependency>
+			<groupId>sil</groupId>
+			<artifactId>sil</artifactId>
+            <scope>compile</scope>
+		</dependency>
+		<dependency>
+			<groupId>gnu.trove</groupId>
+			<artifactId>trove</artifactId>
+            <scope>compile</scope>
+		</dependency>
+		<dependency>
+			<groupId>org.geotools</groupId>
+			<artifactId>gt2-main</artifactId>
+            <scope>compile</scope>
+		</dependency>		
+ 		<dependency>
+		    <groupId>spatialindex</groupId>
+   			<artifactId>spatialindex</artifactId>
+            <scope>compile</scope>
+   		</dependency>
+   		<dependency>
+            <groupId>org.gvsig</groupId>
+            <artifactId>org.gvsig.timesupport.lib.api</artifactId>
+            <scope>compile</scope>
+        </dependency>
+	</dependencies>
+	<build>
+		<sourceDirectory>src</sourceDirectory>
+		<testSourceDirectory>src-test</testSourceDirectory>
+		<testResources>
+			<testResource>
+				<directory>src-test</directory>
+			</testResource>
+		</testResources>
+	</build>
+
+	<profiles>
+		<profile>
+			<id>se</id>
+			<activation>
+				<activeByDefault>true</activeByDefault>
+			</activation>
+			<build>
+				<plugins>
+					<plugin>
+						<groupId>org.apache.maven.plugins
+						</groupId>
+						<artifactId>maven-jar-plugin</artifactId>
+						<configuration>
+							<excludes>
+								<exclude>${gt2-jarIncludes}</exclude>
+								<exclude>${jts-jarIncludes}</exclude>
+								<exclude>${jsi-jarIncludes}</exclude>
+								<exclude>${sptidx-jarIncludes}</exclude>
+							</excludes>
+						</configuration>
+						<executions>
+							<!--
+								Generates a jar file only with the GT2 based spatial index
+								classes
+							-->
+							<execution>
+								<id>gt2</id>
+								<phase>package</phase>
+								<goals>
+									<goal>jar</goal>
+								</goals>
+								<configuration>
+									<classifier>gt2</classifier>
+									<includes>
+										<include>${gt2-jarIncludes}</include>
+									</includes>
+									<excludes>
+										<exclude>${gt2-jarExcludes}</exclude>
+									</excludes>
+								</configuration>
+							</execution>
+							<!--
+								Generates a jar file only with the JTS based spatial index
+								classes
+							-->
+							<execution>
+								<id>jts</id>
+								<phase>package</phase>
+								<goals>
+									<goal>jar</goal>
+								</goals>
+								<configuration>
+									<classifier>jts</classifier>
+									<includes>
+										<include>${jts-jarIncludes}</include>
+									</includes>
+									<excludes>
+										<exclude>${jts-jarExcludes}</exclude>
+									</excludes>
+								</configuration>
+							</execution>
+							<!--
+								Generates a jar file only with the JSI based spatial index
+								classes
+							-->
+							<execution>
+								<id>jsi</id>
+								<phase>package</phase>
+								<goals>
+									<goal>jar</goal>
+								</goals>
+								<configuration>
+									<classifier>jsi</classifier>
+									<includes>
+										<include>${jsi-jarIncludes}</include>
+									</includes>
+									<excludes>
+										<exclude>${jsi-jarExcludes}</exclude>
+									</excludes>
+								</configuration>
+							</execution>
+							<!--
+								Generates a jar file only with the spatialindex based spatial
+								index classes
+							-->
+							<execution>
+								<id>spatialindex</id>
+								<phase>package</phase>
+								<goals>
+									<goal>jar</goal>
+								</goals>
+								<configuration>
+									<classifier>spatialindex</classifier>
+									<includes>
+										<include>${sptidx-jarIncludes}</include>
+									</includes>
+									<excludes>
+										<exclude>${sptidx-jarExcludes}</exclude>
+									</excludes>
+								</configuration>
+							</execution>
+						</executions>
+					</plugin>
+					<plugin>
+						<artifactId>maven-antrun-plugin</artifactId>
+						<executions>
+							<execution>
+								<id>services</id>
+								<phase>package</phase>
+								<goals>
+									<goal>run</goal>
+								</goals>
+								<configuration>
+									<tasks>
+										<jar
+											destfile="${project.build.directory}/${project.build.finalName}-gt2.jar"
+											update="true">
+											<fileset dir="${basedir}/resources/gt2" />
+										</jar>
+										<jar
+											destfile="${project.build.directory}/${project.build.finalName}-jsi.jar"
+											update="true">
+											<fileset dir="${basedir}/resources/jsi" />
+										</jar>
+										<jar
+											destfile="${project.build.directory}/${project.build.finalName}-jts.jar"
+											update="true">
+											<fileset dir="${basedir}/resources/jts" />
+										</jar>
+										<jar
+											destfile="${project.build.directory}/${project.build.finalName}-spatialindex.jar"
+											update="true">
+											<fileset dir="${basedir}/resources/spatialindex" />
+										</jar>
+									</tasks>
+								</configuration>
+							</execution>
+						</executions>
+					</plugin>
+					<plugin>
+						<groupId>org.apache.maven.plugins
+						</groupId>
+						<artifactId>maven-surefire-plugin
+						</artifactId>
+						<configuration>
+							<additionalClasspathElements>
+								<additionalClasspathElement>${basedir}/resources/gt2
+								</additionalClasspathElement>
+								<additionalClasspathElement>${basedir}/resources/jsi
+								</additionalClasspathElement>
+								<additionalClasspathElement>${basedir}/resources/jts
+								</additionalClasspathElement>
+								<additionalClasspathElement>${basedir}/resources/spatialindex
+								</additionalClasspathElement>
+							</additionalClasspathElements>
+						</configuration>
+					</plugin>
+
+				</plugins>
+			</build>
+		</profile>
+		<profile>
+			<id>cdc</id>
+			<activation>
+				<activeByDefault>false</activeByDefault>
+			</activation>
+			<build>
+
+				<plugins>
+					<plugin>
+						<groupId>org.apache.maven.plugins
+						</groupId>
+						<artifactId>maven-compiler-plugin
+						</artifactId>
+						<configuration>
+							<source>1.4</source>
+							<target>1.4</target>
+							<!-- put your configurations here -->
+							<encoding>ISO-8859-1</encoding>
+							<excludes>
+								<exclude>${jts-jarExcludes}</exclude>
+								<exclude>**/gt2/**</exclude>
+								<exclude>**/jsi/**</exclude>
+								<exclude>**/spatialindex/**</exclude>
+							</excludes>
+						</configuration>
+					</plugin>
+					<plugin>
+						<groupId>org.apache.maven.plugins
+						</groupId>
+						<artifactId>maven-jar-plugin</artifactId>
+						<configuration>
+							<excludes>
+								<exclude>${jts-jarIncludes}</exclude>
+							</excludes>
+						</configuration>
+						<executions>
+
+							<!--
+								Generates a jar file only with the JTS based spatial index
+								classes
+							-->
+							<execution>
+								<id>jts</id>
+								<phase>package</phase>
+								<goals>
+									<goal>jar</goal>
+								</goals>
+								<configuration>
+									<classifier>jts</classifier>
+									<includes>
+										<include>${jts-jarIncludes}</include>
+									</includes>
+									<excludes>
+										<exclude>${jts-jarExcludes}</exclude>
+										<exclude>**/gt2/**</exclude>
+										<exclude>**/jsi/**</exclude>
+										<exclude>**/spatialindex/**</exclude>
+									</excludes>
+								</configuration>
+							</execution>
+						</executions>
+					</plugin>
+				</plugins>
+			</build>
+		</profile>
+		<profile>
+			<id>eclipse-project</id>
+			<build>
+				<defaultGoal>antrun:run</defaultGoal>
+				<plugins>
+					<plugin>
+						<artifactId>maven-antrun-plugin</artifactId>
+						<configuration>
+							<tasks>
+								<ant antfile="${build-dir}/ant-tasks/eclipse-tasks.xml"
+									target="eclipse.all"/>
+							</tasks>
+						</configuration>
+					</plugin>
+				</plugins>
+			</build>				
+		</profile>		
+	</profiles>
+
+
+</project>
\ No newline at end of file
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/resources/jsi/META-INF/services/org.gvsig.tools.library.Library
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/resources/jsi/META-INF/services/org.gvsig.tools.library.Library	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/resources/jsi/META-INF/services/org.gvsig.tools.library.Library	(revision 38486)
@@ -0,0 +1 @@
+org.gvsig.fmap.dal.index.spatial.jsi.JSIIndexLibrary
\ No newline at end of file
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/resources/spatialindex/META-INF/services/org.gvsig.tools.library.Library
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/resources/spatialindex/META-INF/services/org.gvsig.tools.library.Library	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/resources/spatialindex/META-INF/services/org.gvsig.tools.library.Library	(revision 38486)
@@ -0,0 +1 @@
+org.gvsig.fmap.dal.index.spatial.spatialindex.SPTLIBIndexLibrary
\ No newline at end of file
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/resources/gt2/META-INF/services/org.gvsig.tools.library.Library
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/resources/gt2/META-INF/services/org.gvsig.tools.library.Library	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/resources/gt2/META-INF/services/org.gvsig.tools.library.Library	(revision 38486)
@@ -0,0 +1 @@
+org.gvsig.fmap.dal.index.spatial.gt2.Gt2IndexLibrary
\ No newline at end of file
Index: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/resources/jts/META-INF/services/org.gvsig.tools.library.Library
===================================================================
--- tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/resources/jts/META-INF/services/org.gvsig.tools.library.Library	(revision 0)
+++ tags/v2_0_0_Build_2049/libraries/libFMap_dalindex/resources/jts/META-INF/services/org.gvsig.tools.library.Library	(revision 38486)
@@ -0,0 +1 @@
+org.gvsig.fmap.dal.index.spatial.jts.JTSIndexLibrary
\ No newline at end of file

Property changes on: tags/v2_0_0_Build_2049/libraries/libFMap_dalindex
___________________________________________________________________
Added: svn:ignore
   + .classpath 
.project 
.settings 
maven-eclipse.xml
target
bin
hs_err_pid*
.externalToolBuilders
.settings
.classpath
.project


