KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > db > impl > PSet_ReifStore_RDB


1 /*
2   (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
3   [See end of file]
4 */

5
6 package com.hp.hpl.jena.db.impl;
7
8 import java.sql.PreparedStatement JavaDoc;
9 import java.sql.SQLException JavaDoc;
10 import java.util.List JavaDoc;
11
12 import com.hp.hpl.jena.graph.*;
13 import com.hp.hpl.jena.shared.*;
14 import com.hp.hpl.jena.graph.impl.LiteralLabel;
15 import com.hp.hpl.jena.util.iterator.ExtendedIterator;
16 import com.hp.hpl.jena.util.iterator.Map1;
17 import com.hp.hpl.jena.db.RDFRDBException;
18 import com.hp.hpl.jena.db.impl.SpecializedGraphReifier_RDB.StmtMask;
19
20 import com.hp.hpl.jena.vocabulary.RDF;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24
25 //=======================================================================
26
/**
27 * Handles Physical storage for implementing SpecializedGraphs.
28 * Different PSet classes are needed for different databases and different
29 * layout schemes.
30 * <p>
31 * This class is a base implemention from which database-specific
32 * drivers can inherit. It is not generic in the sense that it will work
33 * on any minimal SQL store and so should be treated as if it were
34 * an abstract class.
35 * <p>The SQL statements which implement each of the functions are
36 * loaded in a separate file etc/[layout]_[database].sql from the classpath.
37 * See {@link SQLCache SQLCache documentation} for more information on the
38 * format of this file.
39 *
40 * Based on Driver* classes by Dave Reynolds.
41 *
42 * @author <a HREF="mailto:harumi.kuno@hp.com">Harumi Kuno</a>
43 * @version $Revision: 1.23 $ on $Date: 2005/02/21 12:03:06 $
44 */

45
46 public class PSet_ReifStore_RDB extends PSet_TripleStore_RDB {
47
48     //=======================================================================
49
// Internal variables
50

51     protected static Log logger = LogFactory.getLog( PSet_ReifStore_RDB.class );
52     
53     //=======================================================================
54
// Constructors and accessors
55

56     /**
57      * Constructor.
58      */

59     public PSet_ReifStore_RDB() {
60     }
61
62     //=======================================================================
63

64     
65     // Database operations
66

67     public void storeReifStmt(Node n, Triple t, IDBID my_GID) {
68         storeTripleAR(t, my_GID, n, true, false, null);
69     }
70
71     public void deleteReifStmt(Node n, Triple t, IDBID my_GID) {
72         deleteTripleAR(t, my_GID, n, false, null);
73     }
74
75     /* (non-Javadoc)
76      * @see com.hp.hpl.jena.db.impl.IPSet#find(com.hp.hpl.jena.graph.TripleMatch, com.hp.hpl.jena.db.impl.IDBID)
77      */

78     public ResultSetReifIterator findReifStmt(
79         Node stmtURI,
80         boolean hasType,
81         IDBID graphID, boolean getTriples) {
82         String JavaDoc astName = getTblName();
83         String JavaDoc gid = graphID.getID().toString();
84         ResultSetReifIterator result = new ResultSetReifIterator(this, getTriples, graphID);
85
86         PreparedStatement JavaDoc ps = null;
87
88         boolean objIsBlankOrURI = false;
89         int args = 1;
90         String JavaDoc stmtStr;
91         boolean findAll = (stmtURI == null) || stmtURI.equals(Node.ANY);
92         boolean notFound = false;
93
94         if ( findAll )
95             stmtStr = hasType ? "selectReifiedT" : "selectReified";
96         else
97             stmtStr = hasType ? "selectReifiedNT" : "selectReifiedN";
98         try {
99             ps = m_sql.getPreparedSQLStatement(stmtStr, getTblName());
100
101             if (!findAll) {
102                 String JavaDoc stmt_uri = m_driver.nodeToRDBString(stmtURI, false);
103                 if ( stmt_uri == null ) notFound = true;
104                 else ps.setString(args++, stmt_uri);
105             }
106             if (hasType)
107                 ps.setString(args++, "T");
108
109             ps.setString(args++, gid);
110
111         } catch (Exception JavaDoc e) {
112             notFound = true;
113             logger.warn( "Getting prepared statement for " + stmtStr + " Caught exception ", e);
114             throw new JenaException("Exception during database access", e); // Rethrow in case there is a recovery option
115
}
116
117         if ( notFound )
118             result.close();
119         else {
120             try {
121             m_sql.executeSQL(ps, stmtStr, result);
122             } catch (Exception JavaDoc e) {
123                 logger.debug( "find encountered exception ", e);
124                                 throw new JenaException("Exception during database access", e); // Rethrow in case there is a recovery option
125
}
126         }
127         return result;
128     }
129     
130     public ResultSetReifIterator findReifTripleMatch(
131         TripleMatch t,
132         IDBID graphID) {
133         String JavaDoc astName = getTblName();
134         String JavaDoc gid = graphID.getID().toString();
135         ResultSetReifIterator result = new ResultSetReifIterator(this, true, graphID);
136
137         PreparedStatement JavaDoc ps = null;
138
139         String JavaDoc stmtStr = "*findReif ";
140         boolean gotStmt = false;
141         boolean gotPred = false;
142         boolean gotObj = false;
143         boolean objIsStmt = false;
144         char reifProp = ' ';
145         boolean done = false;
146         int argc = 1;
147         
148         Node stmtURI = t.getMatchSubject();
149         Node obj = t.getMatchObject();
150         Node pred = t.getMatchPredicate();
151         
152         if ( (stmtURI != null) && !stmtURI.equals(Node.ANY) ) {
153             gotStmt = true;
154             stmtStr += "N";
155         }
156         if ( (pred != null) && !pred.equals(Node.ANY) ) {
157             gotPred = true;
158             if ( pred.equals(RDF.Nodes.subject) ) reifProp = 'S';
159             else if ( pred.equals(RDF.Nodes.predicate) ) reifProp = 'P';
160             else if ( pred.equals(RDF.Nodes.object) ) reifProp = 'O';
161             else if ( pred.equals(RDF.Nodes.type) ) reifProp = 'T';
162             else done = true;
163             stmtStr += ("P" + reifProp);
164         }
165         if ( (obj != null) && !obj.equals(Node.ANY) ) {
166             gotObj = true;
167             stmtStr += "O";
168             if ( obj.equals(RDF.Nodes.Statement) ) {
169                 objIsStmt = true;
170                 stmtStr += "C";
171             } else if ( reifProp == 'T' )
172                 // reifier only stores patterns like (-, rdf:type, rdf:Statement)
173
done = true;
174         }
175
176         if ( done == false ) try {
177             ps = m_sql.getPreparedSQLStatement(stmtStr, getTblName());
178             ps.setString(argc++, gid);
179             if ( gotStmt ) {
180                 String JavaDoc stmtNode = m_driver.nodeToRDBString(stmtURI, false);
181                 if ( stmtNode == null ) done = true;
182                 else ps.setString(argc++, stmtNode);
183             }
184             if ( gotObj ) {
185                 // no arguments in case match is <-,rdf:type,rdf:Statement>
186
if ( !(gotPred && objIsStmt) ) {
187                     String JavaDoc objNode = m_driver.nodeToRDBString(obj, false);
188                     ps.setString(argc++,objNode);
189                     if ( gotPred == false ) {
190                         // if no predicate, object value could be in subj, pred or obj column
191
ps.setString(argc++,objNode);
192                         ps.setString(argc++,objNode);
193                     }
194                 }
195             }
196
197         } catch (Exception JavaDoc e) {
198             done = true;
199             logger.warn( "Getting prepared statement for " + stmtStr + " Caught exception ", e);
200                         throw new JenaException("Exception during database access", e); // Rethrow in case there is a recovery option
201
}
202
203         if ( done )
204             result.close();
205         else {
206             try {
207             m_sql.executeSQL(ps, stmtStr, result);
208             } catch (Exception JavaDoc e) {
209                 logger.debug( "find encountered exception ", e);
210                                 throw new JenaException("Exception during database access", e); // Rethrow in case there is a recovery option
211
}
212         }
213         return result;
214     }
215
216
217     
218     /*
219      * (non-Javadoc)
220      * return all nodes which reify the triple as a statement. no
221      * need to do distinct here since we only return nodes for reified statments.
222      */

223     
224     public ExtendedIterator findReifStmtURIByTriple(Triple t, IDBID my_GID) {
225         String JavaDoc stmtStr = null;
226         int argc = 1;
227         PreparedStatement JavaDoc ps = null;
228         ResultSetIterator result = new ResultSetIterator();
229         boolean notFound = false;
230
231         stmtStr = "selectReifNode";
232         stmtStr += (t == null) ? "T" : "SPOT";
233
234         try {
235             ps = m_sql.getPreparedSQLStatement(stmtStr, getTblName());
236             ps.clearParameters();
237
238             if (t != null) {
239                 String JavaDoc argStr;
240                 argStr = m_driver.nodeToRDBString(t.getSubject(),false);
241                 if ( argStr == null ) notFound = true;
242                 else ps.setString(argc++, argStr);
243                 argStr = m_driver.nodeToRDBString(t.getPredicate(),false);
244                 if ( argStr == null ) notFound = true;
245                 else ps.setString(argc++, argStr);
246                 argStr = m_driver.nodeToRDBString(t.getObject(),false);
247                 if ( argStr == null ) notFound = true;
248                 else ps.setString(argc++, argStr);
249             }
250
251                 ps.setString(argc, my_GID.getID().toString());
252         } catch (Exception JavaDoc e) {
253             notFound = true;
254             logger.warn( "Getting prepared statement for " + stmtStr + " Caught exception ", e);
255                         throw new JenaException("Exception during database access", e); // Rethrow in case there is a recovery option
256
}
257
258         // find on object field
259
if ( notFound )
260             result.close();
261         else {
262         try {
263             m_sql.executeSQL(ps, stmtStr, result);
264         } catch (Exception JavaDoc e) {
265             logger.debug("find encountered exception ", e);
266             throw new JenaException("Exception during database access", e); // Rethrow in case there is a recovery option
267
}
268         }
269         return result.mapWith(new MapResultSetToNode());
270     }
271     
272     private class MapResultSetToNode implements Map1 {
273
274         /* (non-Javadoc)
275          * @see com.hp.hpl.jena.util.iterator.Map1#map1(java.lang.Object)
276          */

277         public Object JavaDoc map1(Object JavaDoc o) {
278             // TODO Auto-generated method stub
279
List JavaDoc l = (List JavaDoc) o;
280             // TODO we have a BUG here somewhere, hence the message.
281
if (l.get(0) instanceof String JavaDoc) {} else
282                 throw new JenaException( "String required: " + l.get(0).getClass() + " " + l.get(0) );
283             Node n = m_driver.RDBStringToNode((String JavaDoc) l.get(0));
284             return n;
285         }
286         
287     }
288
289     /* (non-Javadoc)
290         * return (distinct) nodes which reify something (have any fragment)
291         */

292
293     public ExtendedIterator findReifNodes(Node stmtURI, IDBID graphID) {
294         String JavaDoc astName = getTblName();
295         String JavaDoc gid = graphID.getID().toString();
296         ResultSetIterator result = new ResultSetIterator();
297         int argc = 1;
298         PreparedStatement JavaDoc ps = null;
299         boolean notFound = false;
300
301         String JavaDoc stmtStr =
302             stmtURI == null ? "selectReifNode" : "selectReifNodeN";
303         try {
304             ps = m_sql.getPreparedSQLStatement(stmtStr, getTblName());
305
306             if (stmtURI != null) {
307                 String JavaDoc stmt_uri = m_driver.nodeToRDBString(stmtURI,false);
308                 if ( stmtURI == null ) notFound = true;
309                 else ps.setString(argc++, stmt_uri);
310             }
311
312             ps.setString(argc, gid);
313
314         } catch (Exception JavaDoc e) {
315             notFound = true;
316             logger.warn( "Getting prepared statement for " + stmtStr + " Caught exception ", e);
317             throw new JenaException("Exception during database access", e); // Rethrow in case there is a recovery option
318
}
319
320         if ( notFound )
321             result.close();
322         else try {
323             result = m_sql.executeSQL(ps, stmtStr, result);
324         } catch (Exception JavaDoc e) {
325             logger.debug("find encountered exception ", e);
326             throw new JenaException("Exception during database access", e); // Rethrow in case there is a recovery option
327
}
328         return result;
329     }
330
331     public void storeFrag(
332         Node stmtURI,
333         Triple frag,
334         StmtMask fragMask,
335         IDBID my_GID) {
336         Node subj = fragMask.hasSubj() ? frag.getObject() : Node.NULL;
337         Node prop = fragMask.hasPred() ? frag.getObject() : Node.NULL;
338         Node obj = fragMask.hasObj() ? frag.getObject() : Node.NULL;
339         Triple t = Triple.create(subj, prop, obj);
340         storeTripleAR(t, my_GID, stmtURI, fragMask.hasType(), false, null);
341     }
342
343     public void updateOneFrag(
344         Node stmtURI,
345         Triple frag,
346         StmtMask fragMask,
347         boolean nullify,
348         IDBID my_GID) {
349             
350             String JavaDoc stmtStr = null;
351             Node val = null;
352             int argc = 1;
353             String JavaDoc argStr;
354             
355             if ( !fragMask.hasOneBit() )
356                 throw new JenaException("Reification can only update one column");
357             PreparedStatement JavaDoc ps = null;
358
359             if ( fragMask.hasSubj() ) {
360                 stmtStr = "updateReifiedS";
361                 if ( !nullify ) val = frag.getObject();
362             } else if ( fragMask.hasPred() ) {
363                 stmtStr = "updateReifiedP";
364                 if ( !nullify ) val = frag.getObject();
365             } else if ( fragMask.hasObj() ) {
366                 stmtStr = "updateReifiedO";
367                 if ( !nullify ) val = frag.getObject();
368             } else if ( fragMask.hasType() ) {
369                 stmtStr = "updateReifiedT";
370             }
371                 
372             try {
373                 ps = m_sql.getPreparedSQLStatement(stmtStr, getTblName());
374                 ps.clearParameters();
375                 if ( fragMask.hasSubj() || fragMask.hasPred() || fragMask.hasObj() ) {
376                     if (nullify)
377                         ps.setNull(argc++,java.sql.Types.VARCHAR);
378                     else {
379                         argStr = m_driver.nodeToRDBString(val,true);
380                         if ( argStr == null )
381                             throw new RDFRDBException("Invalid update argument: " + val.toString());
382                         ps.setString(argc++,argStr);
383                     }
384                 } else {
385                     // update hasType field
386
if ( nullify )
387                         ps.setString(argc++," "); // not nullable
388
else
389                         ps.setString(argc++,"T");
390                 }
391                 argStr = m_driver.nodeToRDBString(stmtURI,true);
392                 if ( argStr == null )
393                     throw new RDFRDBException("Invalid update statement URI: " + stmtURI.toString());
394                 ps.setString(argc++,argStr);
395
396                 ps.setString(argc++,my_GID.getID().toString());
397             } catch (Exception JavaDoc e) {
398                 logger.warn( "Getting prepared statement for " + stmtStr + " Caught exception ", e);
399                 throw new JenaException("Exception during database access", e); // Rethrow in case there is a recovery option
400
}
401             try {
402                 ps.executeUpdate();
403              } catch (SQLException JavaDoc e1) {
404                  logger.error("SQLException caught during reification update" + e1.getErrorCode(), e1);
405                 throw new JenaException("Exception during database access", e1); // Rethrow in case there is a recovery option
406
}
407         }
408
409     public void nullifyFrag(Node stmtURI, StmtMask fragMask, IDBID my_GID) {
410         updateOneFrag(stmtURI,null,fragMask,true,my_GID);
411     }
412     
413     public void updateFrag(
414         Node stmtURI,
415         Triple frag,
416         StmtMask fragMask,
417         IDBID my_GID) {
418             updateOneFrag(stmtURI,frag,fragMask,false,my_GID);
419         }
420
421     public ResultSetReifIterator findFrag(
422         Node stmtURI,
423         Triple frag,
424         StmtMask fragMask,
425         IDBID my_GID) {
426             
427             String JavaDoc stmtStr = null;
428             Node val = null;
429             int argc = 1;
430             ResultSetReifIterator result =
431                 new ResultSetReifIterator(this, true, my_GID);
432             boolean notFound = false;
433             String JavaDoc argStr;
434             
435             Node_Literal litNode = null;
436             LiteralLabel ll = null;
437             String JavaDoc lval = null;
438             boolean litIsPlain = false;
439             boolean objIsURI = false;
440
441         
442             if ( !fragMask.hasOneBit() )
443                 throw new JenaException("Reification can only find one column");
444             PreparedStatement JavaDoc ps = null;
445
446             val = frag.getObject();
447             if ( fragMask.hasSubj() ) {
448                 stmtStr = "selectReifiedNS";
449             } else if ( fragMask.hasPred() ) {
450                 stmtStr = "selectReifiedNP";
451             } else if ( fragMask.hasObj() ) {
452                 stmtStr = "selectReifiedNO";
453             } else if ( fragMask.hasType() ) {
454                 stmtStr = "selectReifiedNT";
455             }
456                 
457             try {
458                 ps = m_sql.getPreparedSQLStatement(stmtStr, getTblName());
459                 ps.clearParameters();
460                 argStr = m_driver.nodeToRDBString(stmtURI,false);
461                 if ( argStr == null ) notFound = true;
462                 else ps.setString(argc++,argStr);
463                 if ( fragMask.hasSubj() || fragMask.hasPred() || fragMask.hasObj()) {
464                     argStr = m_driver.nodeToRDBString(val,false);
465                     if ( argStr == null ) notFound = true;
466                     else ps.setString(argc++,argStr);
467                 } else {
468                     // find on hasType field
469
ps.setString(argc++,"T");
470                 }
471                 ps.setString(argc,my_GID.getID().toString());
472                 
473             } catch (Exception JavaDoc e) {
474                 logger.warn( "Getting prepared statement for " + stmtStr + " Caught exception ", e);
475             }
476
477             if ( notFound )
478                 result.close();
479             else
480             try {
481                 m_sql.executeSQL(ps, stmtStr, result);
482             } catch (Exception JavaDoc e) {
483                 logger.debug("find encountered exception ", e);
484             }
485         return result;
486     }
487     
488     public void deleteFrag(
489         Triple frag,
490         StmtMask fragMask,
491         IDBID my_GID) {
492             
493             if ( !fragMask.hasOneBit() )
494                 throw new JenaException("Can only delete one fragment");
495             int argc = 1;
496         
497             PreparedStatement JavaDoc ps = null;
498             String JavaDoc stmtStr = "deleteReified";
499             if ( fragMask.hasSubj() )
500                 stmtStr += "S";
501             else if ( fragMask.hasPred() )
502                 stmtStr += "P";
503             else if ( fragMask.hasObj() )
504                 stmtStr += "O";
505             else if ( fragMask.hasType() )
506                 stmtStr += "T";
507             else
508                 throw new JenaException("Unspecified reification fragment in deleteFrag");
509
510             Node val = frag.getObject();
511             String JavaDoc argStr = m_driver.nodeToRDBString(val,false);
512             Node stmtURI = frag.getSubject();
513             String JavaDoc uriStr = m_driver.nodeToRDBString(stmtURI,false);
514                             
515             try {
516                 ps = m_sql.getPreparedSQLStatement(stmtStr, getTblName());
517                 ps.clearParameters();
518                 
519                 if ( fragMask.hasSubj() )
520                     ps.setString(argc++,argStr);
521                 else if ( fragMask.hasPred() )
522                     ps.setString(argc++,argStr);
523                 else if ( fragMask.hasObj() )
524                     ps.setString(argc++,argStr);
525                 ps.setString(argc++,my_GID.getID().toString());
526                 ps.setString(argc,uriStr);
527                 
528             } catch (Exception JavaDoc e) {
529                 logger.warn( "Getting prepared statement for " + stmtStr + " Caught exception ", e);
530             }
531             try {
532                 ps.executeUpdate();
533             } catch (Exception JavaDoc e) {
534                 logger.debug("deleteFrag encountered exception ", e);
535             }
536         return;
537     }
538 }
539     /*
540      * (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
541      * All rights reserved.
542      *
543      * Redistribution and use in source and binary forms, with or without
544      * modification, are permitted provided that the following conditions
545      * are met:
546      * 1. Redistributions of source code must retain the above copyright
547      * notice, this list of conditions and the following disclaimer.
548      * 2. Redistributions in binary form must reproduce the above copyright
549      * notice, this list of conditions and the following disclaimer in the
550      * documentation and/or other materials provided with the distribution.
551      * 3. The name of the author may not be used to endorse or promote products
552      * derived from this software without specific prior written permission.
553     
554      * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
555      * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
556      * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
557      * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
558      * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
559      * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
560      * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
561      * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
562      * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
563      * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
564      */

565  
566
Popular Tags