Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: This class is in order to fix a problem. It doesn't 
4
 *             has functionality for Metacat.
5
 *             In Currently, some document in xml_document table 
6
 *             doesn't have entries in xml_access table. This is 
7
 *             okay during the old access policy.
8
 *             But we changed the access policy and if there is no 
9
 *             entry in xml_access table, except owner, other person 
10
 *             can not access it. So we need to associate with access 
11
 *             policy in xml_access table for these doc ids.
12
 *             The same access policy of these doc' dataset will associate
13
 *             to them. 
14
 *  Copyright: 2000 Regents of the University of California and the
15
 *             National Center for Ecological Analysis and Synthesis
16
 *    Authors: Jing Tao
17
 *
18
 *   '$Author: leinfelder $'
19
 *     '$Date: 2011-12-07 12:18:24 -0800 (Wed, 07 Dec 2011) $'
20
 * '$Revision: 6744 $'
21
 *
22
 * This program is free software; you can redistribute it and/or modify
23
 * it under the terms of the GNU General Public License as published by
24
 * the Free Software Foundation; either version 2 of the License, or
25
 * (at your option) any later version.
26
 *
27
 * This program is distributed in the hope that it will be useful,
28
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
30
 * GNU General Public License for more details.
31
 *
32
 * You should have received a copy of the GNU General Public License
33
 * along with this program; if not, write to the Free Software
34
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
35
 */
36

    
37
package edu.ucsb.nceas.metacat;
38

    
39

    
40
import java.io.*;
41
import java.util.Vector;
42
import java.net.URL;
43
import java.net.MalformedURLException;
44
import java.sql.*;
45
import java.util.Stack;
46
import java.util.Hashtable;
47
import java.util.Enumeration;
48
import java.io.BufferedWriter;
49

    
50
import org.apache.log4j.Logger;
51

    
52
import edu.ucsb.nceas.metacat.database.DBConnection;
53
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
54

    
55

    
56
/**This class is in order to fix a problem. It doesn't has functionality for 
57
 *Metacat. 
58
 *In Currently, some document in xml_document table doesn't have entries in 
59
 *xml_access table. This is okay during the old access policy.
60
 *But we changed the access policy and if there is no entry in xml_access table,
61
 * except owner, other person can not access it. So we need to associate with 
62
 *access policy in xml_access table for these doc ids. The same access policy 
63
 *of these docoments' data set will associate to them. 
64
 */
65
public class AssociateAccessPolicy {
66

    
67
 
68
 
69
  private DBConnection  conn = null;
70
  private Vector docIdInAccessTable=null;
71
  private Vector docIdWithoutAccessEntry=null;
72
  private Vector notFoundDataSetId=null;
73
  private Vector itsDataSetIdWithouAccessEntry=null;
74
  private Hashtable docIdMapDataSetId=null; 
75
  private Logger logMetacat = Logger.getLogger(AssociateAccessPolicy.class);
76
  
77
  /**
78
   * the main routine used to associate access policy
79
   */
80
  static public void main(String[] args) 
81
  {
82
     DBConnection localConn=null;
83
     int serialNumber = -1;
84
     AssociateAccessPolicy policy=null;
85
     try
86
     {
87
      localConn=DBConnectionPool.getDBConnection("AssociateAccessPolict.main");
88
      serialNumber=localConn.getCheckOutSerialNumber();
89
      policy = new AssociateAccessPolicy(localConn);
90
      policy.associateAccess();
91
      //localConn.close();   
92
     }//try
93
     catch (Exception e) 
94
     {
95
        System.err.println("Error in AssociateAccessPolicy.main");
96
        System.err.println(e.getMessage());
97
        e.printStackTrace(System.err);
98
     }
99
     finally
100
     {
101
       DBConnectionPool.returnDBConnection(localConn, serialNumber);
102
     }//finally
103
     
104
     if (!(policy.getNotFoundDataSetId()).isEmpty())
105
     {
106
         
107
         System.out.println("Following docid which could not find a mapped" 
108
                  +" dataset was associated with defualt policy:");
109
         for (int i=0; i<(policy.getNotFoundDataSetId()).size(); i++)
110
        {
111
           String str=(String)(policy.getNotFoundDataSetId()).elementAt(i);
112
           System.out.println(str);
113
        }//for
114
     }//if
115
     if (!(policy.geItsDataSetIdWithouAccessEntry()).isEmpty())
116
     {
117
         
118
         System.out.println("Following docid which's mapped dataset doesn't has"
119
                  +" an access entry was associated with defualt policy:");
120
         for (int i=0; i<(policy.geItsDataSetIdWithouAccessEntry()).size(); i++)
121
        {
122
           String str=(String)
123
                        (policy.geItsDataSetIdWithouAccessEntry()).elementAt(i);
124
           System.out.println(str);
125
        }//for
126
     }//if
127
  }
128
  
129
  /**
130
   * construct an instance of the DBQuery class 
131
   *
132
   * <p>Generally, one would call the findDocuments() routine after creating 
133
   * an instance to specify the search query</p>
134
   *
135
   * @param conn the JDBC connection that we use for the query
136
   * @param parserName the fully qualified name of a Java class implementing
137
   *                   the org.xml.sax.XMLReader interface
138
   */
139
  public AssociateAccessPolicy( DBConnection conn) 
140
                  throws IOException, 
141
                         SQLException, Exception
142
  {   
143
    this.conn = conn;
144
    this.docIdInAccessTable=new Vector();
145
    this.docIdWithoutAccessEntry=new Vector();
146
    this.notFoundDataSetId=new Vector();
147
    this.itsDataSetIdWithouAccessEntry=new Vector();
148
    this.docIdMapDataSetId=new Hashtable();
149
    getDocIdInAccessTable();
150
    getDocIdWithoutAccessEntry();
151
    getDocIdMapDataSetId();
152
   }
153
  
154
  /**
155
   * Get the docid which didn't found a dataset id to map it
156
   */
157
  public Vector getNotFoundDataSetId()
158
  {
159
    return notFoundDataSetId;
160
  }
161
  /**
162
   * Get the docid which it's mapped dataset doesn't has access entry
163
   */
164
  public Vector geItsDataSetIdWithouAccessEntry()
165
  {
166
    return itsDataSetIdWithouAccessEntry;
167
  }
168
 
169
  /**
170
   * Get all docIds list in xml_access table
171
   */
172
  private void getDocIdInAccessTable()
173
                      throws SQLException, McdbException,Exception
174
  {
175
    PreparedStatement pStmt;
176
    String docId;
177
    ResultSet rs=null;
178
    
179
    //the query stirng
180
    String query="SELECT id.docid from xml_access xa, identifier id where xa.guid = id.guid";
181
    try
182
    {
183
      pStmt=conn.prepareStatement(query);
184
      //excute the query
185
      pStmt.execute();
186
      //get the result set
187
      rs=pStmt.getResultSet();
188
      //process the result
189
      while (rs.next())
190
      {
191
        
192
        docId=rs.getString(1);//the result docId 
193
        //put the result into docIdInAccessTable vetor
194
        if (!docIdInAccessTable.contains(docId))// delete duplicate docid
195
        {
196
          docIdInAccessTable.add(docId);
197
        }
198
      }//while
199
      //close the pStmt
200
      pStmt.close();
201
    }//try
202
    catch (SQLException e)
203
    {
204
    	logMetacat.error("Error in getDocidListForDataPackage: "
205
                            +e.getMessage());
206
    }//catch
207
    //System.out.println("docid in access table");
208
    /*for (int i=0; i<docIdInAccessTable.size(); i++)
209
    {
210
         String str=(String)docIdInAccessTable.elementAt(i);
211
         System.out.println(str);
212
    }*/
213
    //for
214
  }// getDocIdInAccessTable()
215
  
216
  /**
217
   * associateDefaultValue to docid
218
   * This docid either couldn't find a mapped dataset or it self is a dataset
219
   * @param docId, the docid which will be associate default access value
220
   */
221
  private void associateDefaultValue(String docId)
222
                      throws SQLException, McdbException,Exception
223
  {
224
    PreparedStatement pStmt;
225
    
226
    String query=null;
227
  
228
    //the query stirng
229
    //we let accessfileid blank becuause we couldn't know access file
230
    query="INSERT INTO xml_access " + 
231
            "(docid, principal_name, permission, perm_type, perm_order)" +
232
             "VALUES (?,'public','4','allow','allowFirst')";
233
    
234
    try
235
    {
236
      pStmt=conn.prepareStatement(query);
237
      //bind value
238
      pStmt.setString(1, docId);
239
      //excute the query
240
      logMetacat.debug("running sql: " + pStmt.toString());
241
      pStmt.execute();
242
      pStmt.close();
243
    }//try
244
    catch (SQLException e)
245
    {
246
      System.out.println("Error in associateDefaultValue: "
247
                            +e.getMessage());
248
    }//catch
249
    
250
  }// associateDefaultValue
251
  /**
252
   * Get all docIds which don't have an entry in xml_access table
253
   */
254
  private void getDocIdWithoutAccessEntry()
255
                                 throws SQLException, McdbException,Exception
256
  {
257
    PreparedStatement pStmt=null;
258
    String docId;
259
    ResultSet rs=null;
260

    
261
   
262
    //the query stirng
263
    String query="SELECT docid from xml_documents";
264
    try
265
    {
266
      pStmt=conn.prepareStatement(query);
267
      //excute the query
268
      pStmt.execute();
269
      //get the result set
270
      rs=pStmt.getResultSet();
271
      //process the result
272
      while (rs.next())
273
      {
274
       
275
        docId=rs.getString(1);//the result docId 
276
        //System.out.println("docid in document talbe "+docId);
277
        //If this docId is not in the docIdInAccessTable list,
278
        //put the result into docIdInAccessTable vetor
279
        if (!docIdInAccessTable.contains(docId))
280
        {
281
           docIdWithoutAccessEntry.add(docId);
282
        }
283
     
284
      }//while
285
      //close the pStmt
286
      pStmt.close();
287
    }//try
288
    catch (SQLException e)
289
    {
290
      pStmt.close();
291
      logMetacat.error("Error in getDocidListForDataPackage: "
292
                            +e.getMessage());
293
    }//catch
294
    //System.out.println("docid without access entry:");
295
    /*for (int i=0; i<docIdWithoutAccessEntry.size(); i++)
296
    {
297
         String str=(String)docIdWithoutAccessEntry.elementAt(i);
298
         System.out.println(str);
299
    }*/
300
    //for
301
  }//getDocIdWithoutAccessEntry()  
302
  
303
  /**
304
   * Find dataset docid for these id which doesn't have an entry in access table
305
   * The access policy of dataset docid will apply the id which doesn't have an
306
   * an entry in access table.
307
   * docid and datasetid which will be stored in a hashtable.
308
   * docid as a key, datasetid as value
309
   */
310
  private void getDocIdMapDataSetId()
311
                              throws SQLException, McdbException,Exception
312
  {
313
    
314
    PreparedStatement pStmt=null;
315
    ResultSet rs=null;
316
    String docId=null;
317
    String dataSetId=null;
318
    //make sure there is some documents ids which doesn't has an access entry
319
    if ( docIdWithoutAccessEntry.isEmpty())
320
    {
321
      throw new 
322
          Exception("Every docid in xml_documents table has access policy");
323
    }
324
    String query="SELECT docid from xml_relation where subject= ? or object= ?";
325
    try
326
    {
327
      //find a dataset id for those id which doesn't have access entry
328
      for (int i=0;i<docIdWithoutAccessEntry.size();i++)
329
      {
330
        docId=(String)docIdWithoutAccessEntry.elementAt(i);
331
        pStmt=conn.prepareStatement(query);
332
        //bind the value to query
333
        pStmt.setString(1, docId);
334
        pStmt.setString(2, docId);
335
        //execute the query
336
        pStmt.execute();
337
        rs=pStmt.getResultSet();
338
        //process the result
339
        if (rs.next()) //There are some records for the id in docId fields
340
        {
341
          dataSetId=rs.getString(1);
342
          //System.out.println("dataset id: "+dataSetId);
343
          //put docid and dataset id into hashtable
344
          docIdMapDataSetId.put(docId, dataSetId);
345
        }
346
        else
347
        {
348
         //if not found a dataset id, associateput it into notFoundDataSetId
349
         //and associate with default value
350
          //System.out.println("the id couldn't find data set id: "+docId);
351
          associateDefaultValue(docId);
352
          notFoundDataSetId.add(docId);
353
        }
354
        pStmt.close();
355
      }//for
356
    }//try
357
    catch (SQLException e)
358
    {
359
      pStmt.close();
360
      System.out.println("Error ingetDocIdMapDataSetId: "
361
                            +e.getMessage());
362
    }
363
   
364
  }//getDocIdMapDataSetId()
365
  
366
  /**
367
   * Associate the access policy of dataset to the docid which the data set id
368
   * mapped
369
   */ 
370
   public void associateAccess()
371
                           throws SQLException, McdbException,Exception
372
   {
373
      String docId=null;
374
      String dataSetId=null;
375
      String accessFileId=null;
376
      String principal=null;
377
      int    permission=0;
378
      String permType=null;
379
      String permOrder=null;
380
      String beginTime=null;
381
      String endTime=null;
382
      int    ticketCount=-1;
383
      PreparedStatement pStmt=null;
384
      PreparedStatement insertStatement=null;
385
      ResultSet rs=null;
386
      String query=null;
387
      boolean hasRecord=false;
388
   
389
      //make sure there is some documents ids which doesn't has access entry
390
      if ( docIdWithoutAccessEntry.isEmpty())
391
      {
392
          throw new 
393
            Exception("Every docid in xml_documents table has access policy");
394
      }
395
      //every docid without access policy couldn't find a dataset to map
396
      //assign them default access policy value this aleady done in
397
      //getDocidMapDataSetId
398
      else if (docIdMapDataSetId.isEmpty())
399
      {
400
        
401
      }
402
      else
403
      {
404
        try
405
        {
406
          Enumeration docList = docIdMapDataSetId.keys();
407
          while (docList.hasMoreElements())
408
          {
409
            docId=(String)docList.nextElement();
410
            dataSetId=(String)docIdMapDataSetId.get(docId);
411
            query="select accessfileid, principal_name,permission,perm_type,"
412
                +"perm_order,begin_time,end_time,ticket_count from xml_access xa, identifier id "
413
                +"where id.docid = ? and id.guid = xa.guid";
414
            pStmt=conn.prepareStatement(query);
415
            //bind the value to query
416
            pStmt.setString(1, dataSetId);
417
            //excute the query
418
            pStmt.execute();
419
            rs=pStmt.getResultSet();
420
            //every entry for data set id 
421
            hasRecord=rs.next();
422
            //couldn't find access entry for dataset the docid mapped
423
            //assing defualt value to this docid
424
            if (!hasRecord)
425
            {
426
              
427
              itsDataSetIdWithouAccessEntry.add(docId);
428
              associateDefaultValue(docId);
429
            }
430
            //find the dataset access entry, apply this entry to docid
431
            else
432
            {
433
              
434
              while (hasRecord)
435
              {
436
                //get datasetid's access policy and store them into variables
437
                accessFileId=rs.getString(1);
438
                //System.out.println("accessfileid: "+accessFileId);
439
                principal=rs.getString(2);
440
                //System.out.println("principal: "+principal);
441
                permission=rs.getInt(3);
442
                //System.out.println("permission: "+permission);
443
                permType=rs.getString(4);
444
                //System.out.println("permType: "+permType);
445
                permOrder=rs.getString(5);
446
                //System.out.println("permOrder: "+permOrder);
447
                beginTime=rs.getString(6);
448
                //System.out.println("beginTime: "+beginTime);
449
                endTime=rs.getString(7);
450
                //System.out.println("endTime: "+endTime);
451
                ticketCount=rs.getInt(8);
452
                //System.out.println("ticketCount: "+ticketCount);
453
            
454
                insertStatement = conn.prepareStatement(
455
                  "INSERT INTO xml_access " + 
456
                  "(docid, principal_name, permission, perm_type, perm_order,"+
457
                  "ticket_count, accessfileid) VALUES "+
458
                  "(?,?,?,?,?,?,?)");
459
                // Bind the values to the query
460
                insertStatement.setString(1, docId);
461
                insertStatement.setString(2, principal);
462
                insertStatement.setInt(3, permission);
463
                insertStatement.setString(4, permType);
464
                insertStatement.setString(5, permOrder);
465
                insertStatement.setString(7, accessFileId);
466
                if ( ticketCount > 0 ) 
467
                { 
468
                  insertStatement.setString(6, "" + ticketCount);
469
                } 
470
                else 
471
                {
472
                  insertStatement.setString(6, null);
473
                }
474
                logMetacat.debug("running sql: " + insertStatement.toString());
475
                insertStatement.execute();
476
                hasRecord=rs.next();
477
              }//while
478
              insertStatement.close();
479
            }//else
480
            
481
          }//while
482
          pStmt.close();
483
        }//try
484
        catch (SQLException e)
485
        {
486
          pStmt.close();
487
          insertStatement.close();
488
          logMetacat.error("Error in getDocidListForDataPackadge: "
489
                            +e.getMessage());
490
        }//catch
491
        
492
      }//else
493
      
494
  }//AccociateAccess
495
 
496
}//class
(4-4/64)