summaryrefslogtreecommitdiffstats
path: root/petascope/src/petascope/wcst/transaction/tools/RasdamanUtils.java
blob: 18369877bbe4102d505731ecc4ecac5dc4776e2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/*
 * This file is part of rasdaman community.
 *
 * Rasdaman community 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 3 of the License, or
 * (at your option) any later version.
 *
 * Rasdaman community 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 rasdaman community.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2009 Peter Baumann /
 rasdaman GmbH.
 *
 * For more information please see <http://www.rasdaman.org>
 * or contact Peter Baumann via <baumann@rasdaman.com>.
 */
package petascope.wcst.transaction.tools;

//~--- non-JDK imports --------------------------------------------------------
import org.odmg.DBag;
import org.odmg.Database;
import org.odmg.Implementation;
import org.odmg.ODMGException;
import org.odmg.OQLQuery;
import org.odmg.Transaction;

import rasj.RasGMArray;
import rasj.RasImplementation;
import rasj.RasMInterval;
import rasj.RasResultIsNoIntervalException;

import petascope.wcs.server.exceptions.WCSException;

//~--- JDK imports ------------------------------------------------------------

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;

import java.io.ByteArrayInputStream;

import java.util.Iterator;
import org.odmg.QueryException;
import petascope.wcs.server.exceptions.InternalComponentException;

/**
 * Utility class for doing various tasks that involve the Rasdaman server.
 *
 * @author Andrei Aiordachioaie
 */
public class RasdamanUtils {

    Implementation myApp = null;
    Database myDb = null;
    Transaction myTa = null;
    private String base;
    private String server;

    /**
     * Simple constructor
     *
     * @param s server string
     * @param b database name
     */
    public RasdamanUtils(String s, String b) {
        this.server = s;
        this.base = b;
    }

    public void log(String msg) {
        System.err.flush();
        System.out.println("Rasdaman Utils: " + msg);
        System.out.flush();
    }

    /**
     * Opens a new connection to the Rasdaman server, and starts a new transaction.
     * @throws WCSException on connection error
     */
    public void init() throws WCSException {
        try {
            if (myApp == null) {
                myApp = new RasImplementation(server);
            }
            if (myDb == null) {
                myDb = myApp.newDatabase();
                log("Opening database...");
                myDb.open(base, Database.OPEN_READ_WRITE);
            }
            if (myTa == null) {
                log("Beginning new transaction ...");
                myTa = myApp.newTransaction();
                myTa.begin();
            }
        } catch (ODMGException e) {
            throw new InternalComponentException("Could not connect to the Rasdaman server !", e);
        }
    }

    public void commitAndClose() throws ODMGException {
        if (myTa != null) {
            log("Commiting transaction ...");
            myTa.commit();
            myTa = null;
        }
        if (myDb != null) {
            log("Closing database...");
            myDb.close();
            myDb = null;
        }
        log("Finished !");
    }

    public void abortAndClose() throws ODMGException {
        if (myTa != null) {
            log("Aborting transaction...");
            myTa.abort();
            myTa = null;
        }
        if (myDb != null) {
            log("Closing database...");
            myDb.close();
            myDb = null;
        }
        log("Finished !");
    }

    public BufferedImage loadCoverage(String name) throws Exception {
        init();

        log("Running Load Coverage " + name + " query!");
        OQLQuery myQu = myApp.newOQLQuery();

        myQu.create("select jpeg(" + name + ") from " + name);
        DBag resultSet = (DBag) myQu.execute();

        if (resultSet != null) {
            log("Query successful !");
            Iterator iter = resultSet.iterator();

            if (iter.hasNext()) {
                RasGMArray result = (RasGMArray) iter.next();
                byte[] ba = result.getArray();
                ByteArrayInputStream bas = new ByteArrayInputStream(ba);
                com.sun.image.codec.jpeg.JPEGImageDecoder decoder = com.sun.image.codec.jpeg.JPEGCodec.createJPEGDecoder(bas);
                BufferedImage bufImg = null;

                try {
                    bufImg = decoder.decodeAsBufferedImage();
                } catch (Exception e) {
                    System.err.println("Error decoding the image !!!");
                }

                commitAndClose();

                return bufImg;
            }
        }

        abortAndClose();

        return null;
    }

    public RasGMArray createMDD() throws RasResultIsNoIntervalException {
        // create 2-D MDD with cell length 1, i.e., type “byte”:
        RasGMArray myMDD = new RasGMArray(new RasMInterval("[1:400,1:400]"), 1);
        // byte container for array data, matching in size:
        byte[] mydata = new byte[160000];

        // initialize array as grid of gray and black stripes:
        for (int y = 0; y < 400; y++) {
            for (int x = 0; x < 400; x++) {
                mydata[y * 399 + x] = (byte) ((y % 4) > 1
                        ? 80
                        : 0);
            }
        }
        // now insert byte array into MDD object
        // (sets only the pointer, no copying takes place!):
        myMDD.setArray(mydata);

        return myMDD;
    }

    public void insertGrayImageAsArray(String name) throws ODMGException {
        try {
            init();

            log("Creating grey image ...");
            RasGMArray myMDD = createMDD();
            // set up query object for collection creation:
            OQLQuery myQu = myApp.newOQLQuery();

            myQu.create("create collection " + name + " GreySet");
            // set the object type name (used for server type checking):
            myMDD.setObjectTypeName("GreyImage");
            // finally, execute “create collection” statement:
            log("Creating collection '" + name + "'");
            myQu.execute();
            // now create the insert statement:
            myQu.create("insert into " + name + " values $1");
            // let the server generate a new OID for the object to be
            // inserted, and remember this OID locally:
            String myNewOID = myApp.getObjectId(myMDD);

            // bind the MDD value which substitutes formal parameter $1:
            myQu.bind(myMDD);
            // …and ship the complete statement to the server:
            log("Inserting data into the collection");
            myQu.execute();
            log("Done !");

            commitAndClose();
        } catch (Exception e) {
            e.printStackTrace();
            abortAndClose();
        }
    }

    public void updateGrayImageWithArray(String name, BufferedImage img, int x1, int y1, int x2,
            int y2) {
        try {
            log("Building query for updating gray image ...");
            RasGMArray myMDD = createMddFromImage(img);

            myMDD.setObjectTypeName("GreyImage");
            // set up query object for collection creation:
            OQLQuery myQu = myApp.newOQLQuery();
            // Where to insert new image
            String interval = String.valueOf(x1) + ":" + String.valueOf(x2) + ","
                    + String.valueOf(y1) + ":" + String.valueOf(y2);
            // Size of new image
            String interval2 = String.valueOf(0) + ":" + String.valueOf(x2 - x1) + ","
                    + String.valueOf(0) + ":" + String.valueOf(y2 - y1);

            myQu.create("update " + name + " AS c SET c[" + interval + "] "
                    + "assign maaray x in [" + interval2 + "] values $1");
            // let the server generate a new OID for the object to be
            // inserted, and remember this OID locally:
            String myNewOID = myApp.getObjectId(myMDD);

            // bind the MDD value which substitutes formal parameter $1:
            myQu.bind(myMDD);
            // …and ship the complete statement to the server:
            log("Updating image ...");
            myQu.execute();
            log("Done !");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void insertGrayImageAsArray(String name, BufferedImage img) throws ODMGException, InternalComponentException {
        log("Creating grey image ...");
        RasGMArray myMDD = createMddFromImage(img);
        // set up query object for collection creation:
        OQLQuery myQu = myApp.newOQLQuery();

        myQu.create("create collection " + name + " GreySet");
        // set the object type name (used for server type checking):
        myMDD.setObjectTypeName("GreyImage");
        // finally, execute “create collection” statement:
        log("Creating collection '" + name + "'");
        myQu.execute();
        // now create the insert statement:
        myQu.create("insert into " + name + " values $1");
        // let the server generate a new OID for the object to be
        // inserted, and remember this OID locally:
        String myNewOID = myApp.getObjectId(myMDD);

        // bind the MDD value which substitutes formal parameter $1:
        myQu.bind(myMDD);
        // …and ship the complete statement to the server:
        log("Inserting data into the collection");
        myQu.execute();
        log("Done !");
    }

    public void insertColorImageAsArray(String name, BufferedImage img) throws ODMGException {
        try {
            log("Creating grey image ...");
            RasGMArray myMDD = createMddFromImage(img);
            // set up query object for collection creation:
            OQLQuery myQu = myApp.newOQLQuery();

            myQu.create("create collection " + name + " RGBSet");
            // set the object type name (used for server type checking):
            myMDD.setObjectTypeName("RGBImage");
            // finally, execute “create collection” statement:
            log("Creating collection '" + name + "'");
            myQu.execute();
            // now create the insert statement:
            myQu.create("insert into " + name + " values $1");
            // let the server generate a new OID for the object to be
            // inserted, and remember this OID locally:
            String myNewOID = myApp.getObjectId(myMDD);

            // bind the MDD value which substitutes formal parameter $1:
            myQu.bind(myMDD);
            // …and ship the complete statement to the server:
            log("Inserting data into the collection");
            myQu.execute();
            log("Done !");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void insertImageAsJpeg(String name, byte[] img, int maxX, int maxY) throws ODMGException {
        try {
            init();

            log("Creating image from bytes ...");
            RasGMArray myMDD = createRasArrayFromBytes(img, maxX, maxY);
            // set up query object for collection creation:
            OQLQuery myQu = myApp.newOQLQuery();

            myQu.create("create collection " + name + " GreySet");
            // set the object type name (used for server type checking):
            myMDD.setObjectTypeName("GreyImage");
            // finally, execute “create collection” statement:
            log("Creating collection '" + name + "'");
            myQu.execute();
            // now create the insert statement:
            myQu.create("insert into " + name + " values inv_jpeg($1)");
            // let the server generate a new OID for the object to be
            // inserted, and remember this OID locally:
            String myNewOID = myApp.getObjectId(myMDD);

            // bind the MDD value which substitutes formal parameter $1:
            myQu.bind(myMDD);
            // …and ship the complete statement to the server:
            log("Inserting data into the collection");
            myQu.execute();
            log("Done !");

            commitAndClose();
        } catch (Exception e) {
            System.out.flush();
            e.printStackTrace();
            System.err.flush();
            abortAndClose();
        }
    }

    private RasGMArray createRasArrayFromBytes(byte[] bytes, int maxX, int maxY)
            throws RasResultIsNoIntervalException {
        // create 2-D MDD with cell length 1, i.e., type “byte”:
        String strX = String.valueOf(maxX), strY = String.valueOf(maxY);
        String interval = "[1:" + strX + "],1:" + strY + "]";
        // FIXME: maybe change cell type?
        int cellType = 1;

        // create the RasGMArray object
        RasGMArray myMDD = new RasGMArray(new RasMInterval(interval), cellType);

        myMDD.setArray(bytes);

        return myMDD;
    }

    public void deleteCollection(String name)
            throws ODMGException, ODMGException, ODMGException, Exception {
        try {
//          init();

            log("Creating query...");
            // set up query object for collection creation:
            OQLQuery myQu = myApp.newOQLQuery();

            myQu.create("drop collection " + name);
            // finally, execute “create collection” statement:
            log("Executing deletion query...");
            myQu.execute();
            // now create the insert statement:
            log("Query finished !");

//          commitAndClose();
        } catch (Exception e) {
            e.printStackTrace();

            throw e;
//          abortAndClose();
        }
    }

    public void printAllCollections() throws ODMGException {
        String query = "select r from RAS_COLLECTIONNAMES as r";

//      init();

        log("Querying for all available collections ...");
        OQLQuery myQu = myApp.newOQLQuery();

        myQu.create(query);

        DBag resultSet = (DBag) myQu.execute();

        if (resultSet != null) {
            Iterator iter = resultSet.iterator();

            while (iter.hasNext()) {
                RasGMArray result = (RasGMArray) iter.next();
                byte[] ba = result.getArray();
                String name = new String(ba);

                if (name.endsWith("\u0000")) {
                    name = name.substring(0, name.length() - (new String("\u0000")).length());
                }

                System.out.println("* " + name);
            }
        }

//      commitAndClose();
    }

    public RasGMArray createMddFromImage(BufferedImage img) throws InternalComponentException {
        String interval = null;
        try {
            int cols = img.getWidth();
            int rows = img.getHeight();
            // create 2-D MDD with cell length 1, i.e., type “byte”:
            interval = "[1:" + cols + ",1:" + rows + "]";
            int cellType = 1;

            // create the RasGMArray object
            RasGMArray myMDD = new RasGMArray(new RasMInterval(interval), cellType);
            DataBuffer db = img.getData().getDataBuffer();
            byte[] bytes = new byte[cols * rows];


            System.out.println("Processing image with size: " + interval);
            System.out.println("Created vector with size: " + cols * rows);
            System.out.println("Processing data with size: " + db.getSize());
            int i = 0;

            /*
             *  Java image data-types store an image as a 1-D array, reading the
             * image row-wise. Rasdaman stores the image column-wise. So we need to
             * convert between the two representations.
             */
            for (int c = 0; c < cols; c++) {
                for (int r = 0; r < rows; r++) {
                    bytes[i++] = (byte) db.getElem(r * cols + c);
                }
            }
            myMDD.setArray(bytes);

            return myMDD;
        } catch (RasResultIsNoIntervalException e) {
            throw new InternalComponentException("Illegal Interval String: " + interval, e);
        }
    }

    public BufferedImage convertImageToGray(BufferedImage img) {
        BufferedImage image = new BufferedImage(img.getWidth(), img.getHeight(),
                BufferedImage.TYPE_BYTE_GRAY);
        Graphics g = image.getGraphics();

        g.drawImage(img, 0, 0, null);
        g.dispose();

        return image;
    }
}