Statistics
| Revision:

gvsig-raster / org.gvsig.raster.cache / trunk / org.gvsig.raster.cache / org.gvsig.raster.cache.lib.impl / deprecated / buffer / impl / stripecache / horizontal / CacheHorzImpl.java @ 1939

History | View | Annotate | Download (24.5 KB)

1
package org.gvsig.raster.cache.buffer.impl.stripecache.horizontal;
2

    
3
import java.io.IOException;
4

    
5
import org.gvsig.raster.cache.buffer.Band;
6
import org.gvsig.raster.cache.buffer.exception.WrongParameterException;
7
import org.gvsig.raster.cache.buffer.impl.stripecache.Cache;
8
import org.gvsig.raster.cache.buffer.impl.stripecache.CacheStruct;
9
import org.gvsig.raster.cache.buffer.impl.stripecache.HDDPageList;
10
import org.gvsig.raster.cache.buffer.impl.stripecache.PageBuffer;
11
import org.gvsig.raster.cache.buffer.impl.stripecache.PageCacheList;
12

    
13
/**
14
 * <P>
15
 * Esta clase representa a la cache raster. Consta de una ser?e de p?ginas (CachePages)
16
 * que son buffers con los bloques de datos cacheados en un instante dado. Esta cache tiene 
17
 * una estructura en forma de array donde cada elemento es una p?gina de cach?. Las p?ginas 
18
 * se agrupan en bloques de N p?ginas denominados grupos. La variable nelemsGroup contiene 
19
 * el n?mero de p?ginas de cada grupo.
20
 * </P>
21
 * <P>
22
 * La politica de reemplazo es que una p?gina siempre va a un conjunto determinado por el calculo
23
 * cto = pag % nelemsGroup. Si hay hueco vac?o en el grupo se a?adir? en el siguiente hueco pero
24
 * si hay que reeplazar se reeplazar? la p?gina que m?s tiempo haga su ?ltimo acceso. 
25
 * </P>
26
 * <P>
27
 * Esta cach? lleva el control de que p?ginas est?n cargadas a trav?s de un array de de booleanos
28
 * donde cada elemento representa a una p?gina de datos del raster. Si el elemento en la posici?n
29
 * N de dicho array es true significa que la p?gina est? cacheada. Si es false no lo estar?. 
30
 * </P>
31
 * <P>
32
 * La p?gina de datos actualmente accedida debe estar cacheada por lo que est? clase debe llevar
33
 * el control de que p?gina se est? accediendo o a sido accedida por ?ltima vez. La variable que
34
 * nos dice que p?gina est? siendo accedida es loadPage y pageBuffer ser? la variable que apunta
35
 * al buffer de esta p?gina. Cuando se cambia de p?gina en un acceso estas dos variables deben
36
 * cambiar a sus nuevos valores.
37
 * </P>
38
 * <P>
39
 * Otro par?metro que controla esta clase es que p?gina de cada grupo ha sido accedido con mayor 
40
 * frecuencia. Esto es ?til porque siempre se reemplaza la p?gina de un grupo que haga m?s tiempo
41
 * que haya sido accedida bajo la premisa de que "las p?ginas con accesos recientes tienen mayor 
42
 * probabilidad de volver a ser usadas". Esto es controlado por la variable lastAccess que es
43
 * usada para implementar el algoritmo LRU. Cada vez que una p?gina de un grupo es accedida su 
44
 * contador de lastAccess se pone a 0. El resto de contadores de las p?ginas del grupo se incrementa
45
 * en uno. Siempre se sustituye la p?gina del grupo con valor m?s grande en el contador.
46
 * </P>
47
 * 
48
 * @author Nacho Brodin (nachobrodin@gmail.com)
49
 *
50
 */
51
public class CacheHorzImpl implements Cache {
52
        /**
53
         * List of pages in disk. This array represents all pages
54
         */
55
        protected HDDPageList     hddPageList            = null;
56
        /**
57
         * List of pages in memory. This array represents cached pages
58
         */
59
        protected PageCacheList   pageCacheList          = null;
60
        /**
61
         * Cada elemento es una p?gina del raster y dice si est? cacheada o no.
62
         */
63
        protected boolean[]       cacheada               = null;
64
        /**
65
         * N?mero de p?gina cargada en accessPage.
66
         */
67
        protected int             numberInAccessPage     = -1;
68
        /**
69
         * Buffer de datos de la p?gina actualmente accedida.
70
         */
71
        protected PageBuffer      accessPage             = null;
72
        /**
73
         * Cada elemento del array es una p?gina de cach? y contiene el n?mero de p?gina cargada en 
74
         * esa posici?n.
75
         */
76
        protected int[]                  pageNumberInCache      = null;
77
        /**  
78
         * P?ginas de la cach?.
79
         */
80
        protected CacheStruct     cacheStruct            = null;
81
        /**
82
         * ?ltimo acceso a las p?ginas de cada grupo. Valores de la antig?edad del acceso dentro del
83
         * grupo. La primera dimensi?n del array corresponde al n?mero de grupo y la segunda
84
         * a los elementos del grupo. El elemento del grupo con un acceso m?s reciente tendr? 
85
         * un n?mero menor y el de mayor valor ser? el candidato para la sustituci?n en el pr?ximo
86
         * remplazamiento
87
         */
88
        protected int[][]         lastAccess             = null;
89
        /**
90
         * Cada elemento representa una p?gina de cach? y dice si esta ha sido modificada desde que
91
         * fu? cargada en cach? o no.
92
         */
93
        protected boolean[]        modified              = null;
94
        
95
        protected int              dataSourceWidth       = 0;
96
        protected int              dataSourceHeight      = 0;
97
                
98
        /**
99
         * Inicializamos la variables. Para ello creamos el objeto Cache que contendr? todos los 
100
         * par?metros necesarios para crear el array que controla los accesos m?s recientes y el
101
         * array que dice si una p?gina est? en memoria o no.
102
         * @param nBands N?mero de bandas
103
         * @param dataType Tipo de dato de la p?gina
104
         * @param dataSourceWidth ancho de la fuente de datos
105
         */
106
        public CacheHorzImpl(int nBands, int dataType, int dataSourceWidth, int dataSourceHeight) {
107
                this.dataSourceHeight = dataSourceHeight;
108
                this.dataSourceWidth = dataSourceWidth;
109
                init(nBands, dataType, dataSourceWidth, dataSourceHeight);
110
        }
111
        
112
        /**
113
         * Contructor
114
         * @param cacheStruct
115
         */
116
        public CacheHorzImpl(CacheStruct cacheStruct) {
117
                this.cacheStruct = cacheStruct;
118
                
119
                //Inicializamos la antig?edad de acceso  
120
                lastAccess = new int[cacheStruct.getNGroups()][cacheStruct.getPagsPerGroup()];
121
                
122
                //Creamos el buffer de la cach?
123
                //page = new PageBuffer[cacheStruct.getNPags()];
124
                pageNumberInCache = new int[cacheStruct.getNPags()];
125
                modified = new boolean[cacheStruct.getNPags()];
126
                cacheada = new boolean[cacheStruct.getNTotalPags()];
127
                
128
                initStructs();
129
                initPointers();
130
                
131
                createPages(getNBands());
132
        }
133
        
134
        /**
135
         * Initialize arrays and data structures
136
         * @param nBands
137
         * @param dataType
138
         * @param dataSourceWidth
139
         * @param dataSourceHeight
140
         */
141
        protected void init(int nBands, int dataType, int dataSourceWidth, int dataSourceHeight) {
142
                //Creamos la estructura de la cach?
143
                cacheStruct = new CacheStruct(nBands, dataType, dataSourceWidth, dataSourceHeight);
144
                
145
                //Inicializamos la antig?edad de acceso  
146
                lastAccess = new int[cacheStruct.getNGroups()][cacheStruct.getPagsPerGroup()];
147
                
148
                //Creamos el buffer de la cach?
149
                pageNumberInCache = new int[cacheStruct.getNPags()];
150
                modified = new boolean[cacheStruct.getNPags()];
151
                cacheada = new boolean[cacheStruct.getNTotalPags()];
152
                                
153
                initStructs();
154
                initPointers();
155
                
156
                createPages(getNBands());
157
        }
158
                
159
        /**
160
         * Inicializa las estructuras de mantenimiento de cach?. Estas son array de paginas
161
         * accedidas por ?ltima vez, numeros de p?gina cargadas en cada posici?n de cach?, 
162
         * array con la informaci?n de p?gina modificada y array que dice si una p?gina de disco
163
         * est? cacheada o no.
164
         */
165
        protected void initStructs() {
166
                for(int i = 0; i < cacheStruct.getNGroups(); i ++)
167
                        for(int j = 0; j < cacheStruct.getPagsPerGroup(); j ++)
168
                                lastAccess[i][j] = -1;
169
                
170
                for(int i = 0; i < cacheada.length; i++)
171
                        cacheada[i] = false;
172
                
173
                
174
                for(int i = 0; i < cacheStruct.getNPags(); i++) {
175
                        //pageNumberInCache[i] = -1;
176
                        modified[i] = false;
177
                }                
178
        }
179
        
180
        protected void initPointers() {
181
                int cont = 0;
182
                for(int iGroup = 0; iGroup < cacheStruct.getNGroups(); iGroup ++) {
183
                        for(int iPagPerGroup = 0; iPagPerGroup < cacheStruct.getPagsPerGroup(); iPagPerGroup ++) {
184
                                int pag = iGroup + (cacheStruct.getNGroups() * iPagPerGroup);
185
                                pageNumberInCache[cont] = pag;
186
                                if(pag < cacheada.length - 1)
187
                                        cacheada[pag] = true;
188
                                cont ++;
189
                        }
190
                }        
191
        }
192
        
193
        /**
194
         * Create new and empty pages with the structure information of
195
         * this cache
196
         */
197
        public void createPages(int bands) {
198
                hddPageList = new HDDPageList(cacheStruct.getNTotalPags(), bands);
199
                pageCacheList = new PageCacheList(cacheStruct.getNPags(),
200
                                                                                bands,
201
                                                                                cacheStruct.getHPag(),
202
                                                                                cacheStruct.getDataType(),
203
                                                                                dataSourceWidth);
204
                pageCacheList.setHddPages(hddPageList);
205
        }
206
        
207
        /**
208
         * Load the cache status selected in the parameter. The array has one position for each
209
         * page of cache. In each position has the page number loaded in that memory place.
210
         *  
211
         * @param pageNumberInCache Array of positions
212
         * @throws InterruptedException 
213
         */
214
        public void loadCacheStatus(int[] pageNumberInCache) throws InterruptedException {
215
                if(pageNumberInCache.length != pageCacheList.size())
216
                        return;
217
                for (int iPage = 0; iPage < pageNumberInCache.length; iPage++) 
218
                        pageCacheList.get(iPage).loadPage(pageNumberInCache[iPage]);
219
        }
220
        
221
        /**
222
         * Limpia los trozos de cach? en disco. Despu?s del llamar a este 
223
         * m?todo no puede volver a usarse esta cach?.
224
         * @throws IOException 
225
         */
226
        public void clearCache() throws IOException {
227
                pageCacheList.clearPageList();
228
                hddPageList.clearPageList();
229
        }
230
        
231
        /*
232
         * (non-Javadoc)
233
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#getBitsPag()
234
         */
235
        public int getBitsPag() {
236
                return cacheStruct.getBitsPag();
237
        }
238

    
239
        /**
240
         * Obtiene la altura de la p?gina de cache en l?neas. 
241
         * @return N?mero de l?neas de altura de p?gina.
242
         */
243
        public int getHPag() {
244
                return cacheStruct.getHPag();
245
        }
246
        
247
        /*
248
         * (non-Javadoc)
249
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#isInCache(int)
250
         */
251
        public boolean isInCache(int nPag) {
252
                /*if(nPag < 0 || nPag >= cacheada.length)
253
                        return false;*/
254
                return cacheada[nPag];
255
        }
256
        
257
        /*
258
         * (non-Javadoc)
259
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#setPageAsLoadInCache(int)
260
         */
261
        public void setPageAsLoadInCache(int nPag) {
262
                if(nPag < 0 || nPag >= cacheada.length)
263
                        return;
264
                cacheada[nPag] = true;
265
        }
266
        
267
        /*
268
         * (non-Javadoc)
269
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#setPageAsNotLoadInCache(int)
270
         */
271
        public void setPageAsNotLoadInCache(int nPag) {
272
                if(nPag < 0 || nPag >= cacheada.length)
273
                        return;
274
                cacheada[nPag] = false;
275
        }
276
        
277
        /*
278
         * (non-Javadoc)
279
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#getRasterPageNumberInPosition(int)
280
         */
281
        public int getRasterPageNumberInPosition(int nCachePage) {
282
                return pageNumberInCache[nCachePage];
283
        }
284
        
285
        /*
286
         * (non-Javadoc)
287
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#getRasterPageNumberInPosition(int, int)
288
         */
289
        public int getRasterPageNumberInPosition(int group, int posInGroup) {
290
                return pageNumberInCache[group * getPagsPerGroup() + posInGroup];
291
        }
292
        
293
        /*
294
         * (non-Javadoc)
295
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#setRasterPageNumberInPosition(int, int)
296
         */
297
        public void setRasterPageNumberInPosition(int nCachePage, int nRasterPage) {
298
                pageNumberInCache[nCachePage] = nRasterPage;
299
        }
300
        
301
        /*
302
         * (non-Javadoc)
303
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#setRasterPageNumberInPosition(int, int, int)
304
         */
305
        public void setRasterPageNumberInPosition(int group, int posInGroup, int nRasterPage) {
306
                pageNumberInCache[group * getPagsPerGroup() + posInGroup] = nRasterPage;
307
        }
308
        
309
        /**
310
         * Obtiene el n?mero de p?gina de cach? donde est? cargada la p?gina del raster
311
         * que se ha pasado por par?metro.
312
         * @param pag P?gina del raster
313
         * @return N?mero de p?gina del raster
314
         */
315
        public int getNumberCachePageFromNumberRasterPage(int pag) {
316
                int group = pag % getNGroups(); 
317
                for(int i = 0; i < getPagsPerGroup(); i++)
318
                        if(pageNumberInCache[group + i] == pag)
319
                                return (group * getPagsPerGroup() + i);
320
                return -1;
321
        }
322
        
323
        /*
324
         * (non-Javadoc)
325
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#getNumberGroupFromNumberRasterPage(int)
326
         */
327
        public int[] getNumberGroupFromNumberRasterPage(int pag) {
328
                int group = pag % getNGroups();
329
                for(int i = 0; i < getPagsPerGroup(); i++)
330
                        if(pageNumberInCache[(group * getPagsPerGroup()) + i] == pag)
331
                                return new int[]{group, i};
332
                return null;
333
        }
334
        
335
        /*
336
         * (non-Javadoc)
337
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#getLastAccess()
338
         */
339
        public int[][] getLastAccess() {
340
                return lastAccess;
341
        }
342

    
343
        /*
344
         * (non-Javadoc)
345
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#setZeroInLastAccess(int, int)
346
         */
347
        public void setZeroInLastAccess(int group, int posInGroup) {
348
                lastAccess[group][posInGroup] = 0;
349
        }
350
        
351
        /*
352
         * (non-Javadoc)
353
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#getNumberInAccessPage()
354
         */
355
        public int getNumberInAccessPage() {
356
                return numberInAccessPage;
357
        }
358

    
359
        /*
360
         * (non-Javadoc)
361
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#getPagsPerGroup()
362
         */
363
        public int getPagsPerGroup() {
364
                return cacheStruct.getPagsPerGroup();
365
        }
366

    
367
        /**
368
         * Obtiene la p?gina de datos de la posici?n pag
369
         * @param pag N?mero de p?gina de cach? a recuperar
370
         * @return PageBuffer correspondiente a la p?gina recuperada
371
         */
372
        public PageBuffer getPageBufferFromNumberCachePage(int pag) {
373
                return pageCacheList.get(pag);
374
        }
375
        
376
        /**
377
         * Obtiene la p?gina de datos a partir del n?mero de p?gina de raster
378
         * @param pag N?mero de p?gina raster a recuperar
379
         * @return PageBuffer correspondiente a la p?gina recuperada o null si no est? en cach?
380
         */
381
        public PageBuffer getPageBufferFromNumberRasterPage(int pag) {
382
                int group = pag % getNGroups();
383
                for(int i = 0; i < getPagsPerGroup(); i++)
384
                        if(pageNumberInCache[group * getPagsPerGroup() + i] == pag)
385
                                return pageCacheList.get(group * getPagsPerGroup() + i);
386
                return null;
387
        }
388
        
389
        /*
390
         * (non-Javadoc)
391
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#getPageBuffer(int, int)
392
         */
393
        public PageBuffer getPageBuffer(int group, int posInGroup) {
394
                return pageCacheList.get(group * getPagsPerGroup() + posInGroup);
395
        }
396
        
397
        /*
398
         * (non-Javadoc)
399
         * @see org.cachete.buffer.stripecache.ICache#getAccessPage()
400
         */
401
        public PageBuffer getAccessPage() {
402
                return accessPage;
403
        }
404
        
405
        /*
406
         * (non-Javadoc)
407
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#setAccessPage(org.gvsig.raster.cache.buffer.impl.stripecache.horizontal.PageBuffer, int)
408
         */
409
        public void setAccessPage(PageBuffer pb, int pagNumber) {
410
                accessPage = pb;
411
                numberInAccessPage = pagNumber;
412
        }
413
        
414
        /*
415
         * (non-Javadoc)
416
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#isModified(int)
417
         */
418
        public boolean isModified(int nCachePag) {
419
                return modified[nCachePag];
420
        }
421

    
422
        /*
423
         * (non-Javadoc)
424
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#isModified(int, int)
425
         */
426
        public boolean isModified(int group, int posInGroup) {
427
                return modified[group * getPagsPerGroup() + posInGroup];
428
        }
429

    
430
        /*
431
         * (non-Javadoc)
432
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#setModify(int)
433
         */
434
        public void setModify(int nCachePag) {
435
                modified[nCachePag] = true;        
436
        }
437
        
438
        /**
439
         * Pone como modificada una p?gina de cach?
440
         * @param group Grupo en el que se encuentra la p?gina
441
         * @param posInGroup Posici?n dentro del grupo en el que est? la p?gina
442
         */
443
        public void setModify(int group, int posInGroup) {
444
                modified[group * getPagsPerGroup() + posInGroup] = true;        
445
        }
446
        
447
        /*
448
         * (non-Javadoc)
449
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#unsetModify(int)
450
         */
451
        public void unsetModify(int nCachePag) {
452
                modified[nCachePag] = false;        
453
        }
454
        
455
        /*
456
         * (non-Javadoc)
457
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#unsetModify(int, int)
458
         */
459
        public void unsetModify(int group, int posInGroup) {
460
                modified[group * getPagsPerGroup() + posInGroup] = false;        
461
        }
462
        
463
        /**
464
         * Obtiene el n?mero de p?ginas de la cach?
465
         * @return N?mero total de p?ginas de la cach?
466
         */
467
        public int getNPags() {
468
                return cacheStruct.getNPags();
469
        }
470
        
471
        /**
472
         * Obtiene el n?mero de bandas
473
         * @return N?mero de bandas
474
         */
475
        public int getNBands() {
476
                return cacheStruct.getNBands();
477
        }
478
        
479
        /**
480
         * Obtiene la estructura de ca cach?
481
         * @return CacheStruct
482
         */
483
        public CacheStruct getCacheStruct() {
484
                return cacheStruct;
485
        }
486
        
487
        /**
488
         * Asigna la estructura de ca cach?
489
         * @param CacheStruct
490
         */
491
        public void setCacheStruct(CacheStruct cacheStruct) {
492
                this.cacheStruct = cacheStruct;
493
        }
494
        
495
        /*
496
         * (non-Javadoc)
497
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#getNGroups()
498
         */
499
        public int getNGroups() {
500
                return cacheStruct.getNGroups();
501
        }
502
        
503
        /*
504
         * (non-Javadoc)
505
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#getNTotalPags()
506
         */
507
        public int getNTotalPags() {
508
                return cacheStruct.getNTotalPags();
509
        }
510
        
511
        /**
512
         * Obtiene el array con los n?meros de p?gina que hay cargados
513
         * en cada bloque de cache
514
         * @return array con los n?mero de p?gina
515
         */
516
        public int[] getPageNumberInCache() {
517
                return this.pageNumberInCache;
518
        }
519
        
520
        /**
521
         * Para extraer el desplazamiento de una direcci?n (l?nea de raster) hay que hacer una operaci?n And con 
522
         * con la altura de la p?gina -1. Por ejemplo, una p?gina de 16 l?neas de altura el desplazamiento ser?
523
         * 16 - 1 = 15 porque 15 en binario es 1111.
524
         * 
525
         * Si queremos acceder a la linea del raster n?mero 83 (1010011) realizando la operaci?n And con el valor del
526
         * desplazamiento obtenemos (0001111 & 1010011 = 0000011), es decir el valor 3 en decimal. Esto quiere decir
527
         * que la l?nea 83 del raster es la 3 de su p?gina. 
528
         * @return valor del desplazamiento
529
         */
530
        public int getOffset() {
531
                return cacheStruct.getOffset();
532
        }
533
        
534
        /**
535
         * Convierte una p?gina dentro de un grupo de la cach? en un n?mero de 
536
         * p?gina de cach?. Por ejemplo, en una cach? de 10 grupos y 5 p?ginas por grupo
537
         * la p?gina 2 del grupo 4 devolver? el 23 (5 * 4 + 3 = 23) teniendo en cuenta que
538
         * la p?gina y el grupo cero tambi?n cuentan.  
539
         * @param group
540
         * @param pageInGroup
541
         * @return
542
         */
543
        public int convertPageInGroupToPageInCache(int group, int pageInGroup) {
544
                return (group * cacheStruct.getPagsPerGroup() + pageInGroup);
545
        }
546

    
547
        /*
548
         * (non-Javadoc)
549
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#updateLastAccess(int)
550
         */
551
        public int updateLastAccess(int group) {
552
                int max = Integer.MIN_VALUE;
553
                int posMax = 0;
554
                for(int i = 0; i < getPagsPerGroup(); i++) {
555
                        if(getLastAccess()[group][i] >= 0)
556
                                getLastAccess()[group][i] ++;
557
                        
558
                        if(getLastAccess()[group][i] > max) {
559
                                max = getLastAccess()[group][i];
560
                                posMax = i;
561
                        }
562
                }
563
                return posMax;
564
        }
565
        
566
        /**
567
         * Obtiene la posici?n del grupo de la p?gina a reemplazar, es decir la de m?ximo valor
568
         * en el vector lastAccess.
569
         * @param group N?mero de grupo a obtener la p?gina de reemplazo
570
         * @return La posici?n del elemento del grupo con valor m?ximo. Este elemento 
571
         * es el candidato para el reemplazo.
572
         */
573
        public int posInGroupPagToReplace(int group) {
574
                int max = Integer.MIN_VALUE;
575
                int posMax = 0;
576
                for(int i = 0; i < getPagsPerGroup(); i++) {
577
                        if(getLastAccess()[group][i] > max) {
578
                                max = getLastAccess()[group][i];
579
                                posMax = i;
580
                        }
581
                }
582
                return posMax;
583
        } 
584
        
585
        /*
586
         * (non-Javadoc)
587
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#loadPage(int, int, int)
588
         */
589
        public void loadPage(int group, int posInGroupPageToReplace, int nPag) throws InterruptedException {
590
                pageCacheList.get(group * getPagsPerGroup() + posInGroupPageToReplace).loadPage(nPag);
591
        }
592
        
593
        /*
594
         * (non-Javadoc)
595
         * @see org.gvsig.raster.cache.buffer.impl.stripecache.ICache#savePage(int, int, int)
596
         */
597
        public void savePage(int group, int posInGroupPageToReplace, int nPag) throws IOException {
598
                pageCacheList.get(group * getPagsPerGroup() + posInGroupPageToReplace).savePage(nPag);
599
        }
600

    
601
        /**
602
         * Salva a disco todas las p?ginas en memoria cach? e inicializa estructuras de datos.
603
         * 
604
         * @throws IOException
605
         */
606
        public void resetCache() throws IOException {
607
                for (int iCachePage = 0; iCachePage < pageCacheList.size(); iCachePage++) { 
608
                        if(modified[iCachePage])
609
                                pageCacheList.get(iCachePage).savePage(this.getRasterPageNumberInPosition(iCachePage));
610
                }
611
                initStructs();
612
        }
613
        
614
        /**
615
         * Remove the selected cache band from disk and memory
616
         * @param iBand Band number to remove
617
         * @throws IOException 
618
         */
619
        public void removeBand(int pos) throws IOException {
620
                pageCacheList.removeBand(pos);
621
                hddPageList.removeBand(pos);
622
        }
623
        
624
        /**
625
         * Add an empty band in the cache
626
         * @param iBand Band number to add
627
         * @throws IOException 
628
         */
629
        public void addBand(int pos) throws IOException {
630
                resetCache();
631
                pageCacheList.addBand(pos);
632
                PageBuffer buf = new PageBuffer(cacheStruct.getDataType(), dataSourceWidth, cacheStruct.getHPag(), 1, true);
633
                hddPageList.addBand(pos, buf);
634
        }
635
        
636
        /**
637
         * Add a band in the cache
638
         * @param iBand Band number to add
639
         * @param Band Band to add
640
         * @throws IOException 
641
         */
642
        public void addBand(int pos, Band band) throws IOException {
643
                resetCache();
644
                pageCacheList.addBand(pos);
645
                PageBuffer buf = new PageBuffer(cacheStruct.getDataType(), dataSourceWidth, band.getBlockSize(), 1, true);
646
                hddPageList.addBand(pos, band, buf);
647
        }
648
        
649
        /**
650
         * Swap bands accordint to positions selected in bandPosition parameter.
651
         * 
652
         * @param  bandPosition
653
         *         New order for the bands in the array. Each position in the array represent the old band
654
         *         .The number that it contains represent the new position of that band. For instance, an
655
         *         array with values {1, 0, 2, 3} means that it has four bands and the band number one is swaped
656
         *         with the band number zero. The bands two and three don't change its position in this example.                           
657
         * @throws WrongParameterException
658
         * @throws IOException 
659
         */
660
         public void swapBands(int[] bandPosition) throws WrongParameterException, IOException {
661
                resetCache();
662
                pageCacheList.swapBands(bandPosition);
663
                hddPageList.swapBands(bandPosition);
664
         }
665
                        
666
        /**
667
         * Consulta si alguna p?gina de memoria tiene modificaciones para volcar a disco
668
         * @return true si hay alguna p?gina con modificaciones y false si no la hay
669
         */
670
        public boolean anyPageModified() {
671
                for (int iPage = 0; iPage < modified.length; iPage++) {
672
                        if(modified[iPage])
673
                                return true;
674
                }
675
                return false;
676
        }
677
        
678
        /**
679
         * Get the width of the data source
680
         * @return int
681
         */
682
        public int getDataSourceWidth() {
683
                return dataSourceWidth;
684
        }
685

    
686
        /**
687
         * Get the height of the data source
688
         * @return int
689
         */
690
        public int getDataSourceHeight() {
691
                return dataSourceHeight;
692
        }
693
        
694
        /*
695
         * (non-Javadoc)
696
         * @see java.lang.Object#clone()
697
         */
698
        public Object clone() {
699
                CacheHorzImpl clon = cloneStructure();
700
                clon.hddPageList = (HDDPageList)hddPageList.clone();
701
                clon.pageCacheList = (PageCacheList)pageCacheList.clone();
702
                clon.pageCacheList.setHddPages(clon.hddPageList);
703
                return clon;
704
        }
705
        
706
        /**
707
         * Clone the cache structure without clone data pages neither disk pages 
708
         * @return Cache
709
         */
710
        public CacheHorzImpl cloneStructure() {
711
                CacheHorzImpl clon = new CacheHorzImpl(cacheStruct.getNBands(), cacheStruct.getDataType(), dataSourceWidth, dataSourceHeight);
712
                for (int i = 0; i < cacheada.length; i++) 
713
                        clon.cacheada[i] = cacheada[i];
714
                clon.numberInAccessPage = numberInAccessPage;
715
                for (int i = 0; i < pageNumberInCache.length; i++) 
716
                        clon.pageNumberInCache[i] = pageNumberInCache[i];
717
                for (int i = 0; i < lastAccess.length; i++) {
718
                        for (int j = 0; j < lastAccess[i].length; j++) {
719
                                clon.lastAccess[i][j] = lastAccess[i][j];
720
                        }
721
                }
722
                for (int i = 0; i < modified.length; i++)
723
                        clon.modified[i] = modified[i];
724
                clon.cacheStruct = (CacheStruct)cacheStruct.clone();
725
                return clon;
726
        }
727

    
728
        /**
729
         * Imprime la informaci?n de estructura de cach?
730
         */
731
        public void show() {
732
                ((org.gvsig.raster.cache.buffer.impl.stripecache.CacheStruct)cacheStruct).show();
733
                System.out.println("Cacheada:");
734
                for(int i = 0; i < cacheada.length; i++)
735
                        System.out.print(i + "=" + cacheada[i]+" ");
736
                System.out.println();
737
                System.out.println("LastAccess:");
738
                for(int i = 0; i < cacheStruct.getNGroups(); i++) {
739
                        System.out.println("Grupo " + i +":");
740
                        for(int j = 0; j < cacheStruct.getPagsPerGroup(); j++)
741
                                System.out.println("elem " + j + " : " + "Page " + pageNumberInCache[i * cacheStruct.getPagsPerGroup() + j] + " : " + lastAccess[i][j]);
742
                
743
                }
744
        }
745
        
746
        /**
747
         * Imprime la informaci?n de estructura de cach?
748
         * @throws IOException 
749
         */
750
//        public void log(String txt) {
751
//                try {
752
//                        FileServices.getDesc().write(txt);
753
//                        FileServices.getDesc().newLine();
754
//                        FileServices.getDesc().write("**** Pag(i) = ?Cacheada?: ****");
755
//                        FileServices.getDesc().newLine();
756
//                        /*for(int i = 0; i < cacheada.length; i++) {
757
//                                TxtIO.getDesc().write(i + "=" + cacheada[i] + " ");
758
//                                TxtIO.getDesc().newLine();
759
//                        }*/
760
//
761
//                        FileServices.getDesc().write("Numero pag en accessPage: " + numberInAccessPage);
762
//                        FileServices.getDesc().newLine();
763
//                        FileServices.getDesc().write("Accesos:");
764
//                        FileServices.getDesc().newLine();
765
//                        int count = 0;
766
//                        for(int i = 0; i < cacheStruct.getNGroups(); i++) {
767
//                                FileServices.getDesc().write("--->Grupo " + i +":");
768
//                                FileServices.getDesc().newLine();
769
//                                for(int j = 0; j < cacheStruct.getPagsPerGroup(); j++) {
770
//                                        FileServices.getDesc().write("Pos:" + count + ", Pos grupo:" + j + " : " + ", Pag en esta pos: " + pageNumberInCache[i * cacheStruct.getPagsPerGroup() + j] + " Access:" + lastAccess[i][j]);
771
//                                        FileServices.getDesc().newLine();
772
//                                        count ++;
773
//                                }                
774
//                        }
775
//                } catch (IOException e) {
776
//                        e.printStackTrace();
777
//                }
778
//        }
779
        
780
}