Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that handles the SAX XML events as they
4
 *             are generated from XML documents
5
 *  Copyright: 2000 Regents of the University of California and the
6
 *             National Center for Ecological Analysis and Synthesis
7
 *    Authors: Matt Jones, Jivka Bojilova
8
 *
9
 *   '$Author: leinfelder $'
10
 *     '$Date: 2011-11-04 14:45:59 -0700 (Fri, 04 Nov 2011) $'
11
 * '$Revision: 6606 $'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

    
30
import java.io.File;
31
import java.io.FileOutputStream;
32
import java.io.IOException;
33
import java.io.OutputStreamWriter;
34
import java.io.Writer;
35
import java.sql.PreparedStatement;
36
import java.sql.ResultSet;
37
import java.sql.SQLException;
38
import java.util.Date;
39
import java.util.EmptyStackException;
40
import java.util.Enumeration;
41
import java.util.Hashtable;
42
import java.util.Stack;
43
import java.util.Vector;
44

    
45
import org.apache.log4j.Logger;
46
import org.xml.sax.Attributes;
47
import org.xml.sax.SAXException;
48

    
49
import edu.ucsb.nceas.metacat.accesscontrol.AccessControlInterface;
50
import edu.ucsb.nceas.metacat.accesscontrol.AccessRule;
51
import edu.ucsb.nceas.metacat.accesscontrol.AccessSection;
52
import edu.ucsb.nceas.metacat.database.DBConnection;
53
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
54
import edu.ucsb.nceas.metacat.properties.PropertyService;
55
import edu.ucsb.nceas.metacat.util.DocumentUtil;
56
import edu.ucsb.nceas.metacat.util.MetacatUtil;
57
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
58

    
59
/**
60
 * A database aware Class implementing callback methods for the SAX parser to
61
 * call when processing the XML stream and generating events
62
 */
63
public class Eml210SAXHandler extends DBSAXHandler implements AccessControlInterface {
64

    
65
	private boolean processingTopLevelAccess = false;
66

    
67
	private boolean processingAdditionalAccess = false;
68

    
69
	private boolean processingOtherAccess = false;
70

    
71
	private AccessSection accessObject = null;
72

    
73
	private AccessRule accessRule = null;
74

    
75
	// all access rules
76
	private Vector<AccessSection> accessObjectList = new Vector<AccessSection>(); 
77

    
78
	private Hashtable<String, AccessSection> topLevelAccessControlMap = new Hashtable<String, AccessSection>();
79

    
80
	// subtree access for additionalmetadata
81
	private Hashtable<String, AccessSection> additionalAccessControlMap = new Hashtable<String, AccessSection>();
82
	
83
	
84
	private Vector<Hashtable<String, AccessSection>> additionalAccessMapList = new Vector<Hashtable<String, AccessSection>>();
85
	
86
	// ids from additionalmetadata/describes
87
	private Vector<String> describesId = new Vector<String>(); 
88
	
89
	private Stack<SubTree> subTreeInfoStack = new Stack<SubTree>();
90

    
91
	private Vector<SubTree> subTreeList = new Vector<SubTree>();
92
	
93
	private boolean needToCheckAccessModule = false;
94

    
95
	private Vector<AccessSection> unChangeableAccessSubTreeVector = new Vector<AccessSection>();
96

    
97
	private Stack<NodeRecord> currentUnchangeableAccessModuleNodeStack = new Stack<NodeRecord>();
98

    
99
	private AccessSection topAccessSection;
100

    
101
	// we need an another stack to store the access node which we pull out just
102
	// from xml. If a reference happened, we can use the stack the compare nodes
103
	private Stack<NodeRecord> storedAccessNodeStack = new Stack<NodeRecord>();
104

    
105
	// vector stored the data file id which will be write into relation table
106
	private Vector<String> onlineDataFileIdInRelationVector = new Vector<String>();
107

    
108
	// vector stored the data file id which will be write top access rules to
109
	// access table
110
	private Vector<String> onlineDataFileIdInTopAccessVector = new Vector<String>();
111

    
112
	// Indicator of inline data
113
	private boolean handleInlineData = false;
114

    
115
	private Hashtable<String, String> inlineDataNameSpace = null;
116

    
117
	private Writer inlineDataFileWriter = null;
118

    
119
	private String inlineDataFileName = null;
120

    
121
	DistributionSection currentDistributionSection = null;
122

    
123
	Vector<DistributionSection> allDistributionSections = new Vector<DistributionSection>();
124

    
125
	// This variable keeps a counter of each distribution element. This index
126
	// will be used to name the inline data file that gets written to disk, and to
127
	// strip inline data from the metadata document on file if the user does not have
128
	// read access.
129
	private int distributionIndex = 0;
130

    
131
	// private String distributionOnlineFileName = null;
132

    
133
	// This is used to delete inline files if the xml does not parse correctly.
134
	private Vector<String> inlineFileIdList = new Vector<String>();
135

    
136
	// Constant
137
	private static final String EML = "eml";
138

    
139
	private static final String DISTRIBUTION = "distribution";
140

    
141
	private static final String ORDER = "order";
142

    
143
	private static final String ID = "id";
144

    
145
	private static final String REFERENCES = "references";
146

    
147
	public static final String INLINE = "inline";
148

    
149
	private static final String ONLINE = "online";
150

    
151
	private static final String URL = "url";
152

    
153
	// private static final String PERMISSIONERROR = "User tried to update a
154
	// subtree "
155
	// + "when they don't have write permission!";
156

    
157
	private static final String UPDATEACCESSERROR = "User tried to update an "
158
			+ "access module when they don't have \"ALL\" permission!";
159

    
160
	private static final String TOPLEVEL = "top";
161

    
162
	private static final String SUBTREELEVEL = "subtree";
163

    
164
	private static final String RELATION = "Provides info for";
165

    
166
	private Logger logMetacat = Logger.getLogger(Eml210SAXHandler.class);
167

    
168
	/**
169
	 * Construct an instance of the handler class In this constructor, user can
170
	 * specify the version need to update
171
	 * 
172
	 * @param conn
173
	 *            the JDBC connection to which information is written
174
	 * @param action -
175
	 *            "INSERT" or "UPDATE"
176
	 * @param docid
177
	 *            to be inserted or updated into JDBC connection
178
	 * @param revision,
179
	 *            the user specified the revision need to be update
180
	 * @param user
181
	 *            the user connected to MetaCat servlet and owns the document
182
	 * @param groups
183
	 *            the groups to which user belongs
184
	 * @param pub
185
	 *            flag for public "read" access on document
186
	 * @param serverCode
187
	 *            the serverid from xml_replication on which this document
188
	 *            resides.
189
	 * 
190
	 */
191
	public Eml210SAXHandler(DBConnection conn, String action, String docid,
192
			String revision, String user, String[] groups, String pub, int serverCode,
193
			Date createDate, Date updateDate) throws SAXException {
194
		super(conn, action, docid, revision, user, groups, pub, serverCode, createDate,
195
				updateDate);
196
		// Get the unchangeable subtrees (user doesn't have write permission)
197
		try {
198
			PermissionController control = new PermissionController(docid
199
					+ PropertyService.getProperty("document.accNumSeparator") + revision);
200

    
201
			// If the action is update and user doesn't have "ALL" permission
202
			// we need to check if user can update access subtree			
203
			if (!control.hasPermission(user, groups, AccessControlInterface.ALLSTRING)
204
					&& action != null && action.equals("UPDATE")) {
205
				needToCheckAccessModule = true;
206
				unChangeableAccessSubTreeVector = getAccessSubTreeListFromDB();
207
			}
208

    
209
		} catch (Exception e) {
210
			throw new SAXException(e.getMessage());
211
		}
212
	}
213

    
214
	/*
215
	 * Get the subtree node info from xml_accesssubtree table
216
	 */
217
	private Vector<AccessSection> getAccessSubTreeListFromDB() throws Exception {
218
		Vector<AccessSection> result = new Vector<AccessSection>();
219
		PreparedStatement pstmt = null;
220
		ResultSet rs = null;
221
		String sql = "SELECT controllevel, subtreeid, startnodeid, endnodeid "
222
				+ "FROM xml_accesssubtree WHERE docid like ? "
223
				+ "ORDER BY startnodeid ASC";
224

    
225
		try {
226

    
227
			pstmt = connection.prepareStatement(sql);
228
			// Increase DBConnection usage count
229
			connection.increaseUsageCount(1);
230
			// Bind the values to the query
231
			pstmt.setString(1, docid);
232
			pstmt.execute();
233

    
234
			// Get result set
235
			rs = pstmt.getResultSet();
236
			while (rs.next()) {
237
				String level = rs.getString(1);
238
				String sectionId = rs.getString(2);
239
				long startNodeId = rs.getLong(3);
240
				long endNodeId = rs.getLong(4);
241
				// create a new access section
242
				AccessSection accessObj = new AccessSection();
243
				accessObj.setControlLevel(level);
244
				accessObj.setDocId(docid);
245
				accessObj.setSubTreeId(sectionId);
246
				accessObj.setStartNodeId(startNodeId);
247
				accessObj.setEndNodeId(endNodeId);
248
				Stack<NodeRecord> nodeStack = accessObj.getSubTreeNodeStack();
249
				accessObj.setSubTreeNodeStack(nodeStack);
250
				// add this access obj into vector
251
				result.add(accessObj);
252
				// Get the top level access subtree control
253
				if (level != null && level.equals(TOPLEVEL)) {
254
					topAccessSection = accessObj;
255
				}
256
			}
257
			pstmt.close();
258
		}// try
259
		catch (SQLException e) {
260
			throw new SAXException("EMLSAXHandler.getAccessSubTreeListFromDB(): "
261
					+ e.getMessage());
262
		}// catch
263
		finally {
264
			try {
265
				pstmt.close();
266
			} catch (SQLException ee) {
267
				throw new SAXException("EMLSAXHandler.getAccessSubTreeListFromDB(): "
268
						+ ee.getMessage());
269
			}
270
		}// finally
271
		return result;
272
	}
273

    
274
	/** SAX Handler that is called at the start of each XML element */
275
	public void startElement(String uri, String localName, String qName, Attributes atts)
276
			throws SAXException {
277
		// for element <eml:eml...> qname is "eml:eml", local name is "eml"
278
		// for element <acl....> both qname and local name is "eml"
279
		// uri is namesapce
280
		logMetacat.debug("Start ELEMENT(qName) " + qName);
281
		logMetacat.debug("Start ELEMENT(localName) " + localName);
282
		logMetacat.debug("Start ELEMENT(uri) " + uri);
283

    
284
		DBSAXNode parentNode = null;
285
		DBSAXNode currentNode = null;
286

    
287
		if (!handleInlineData) {
288
			// Get a reference to the parent node for the id
289
			try {
290
				parentNode = (DBSAXNode) nodeStack.peek();
291
			} catch (EmptyStackException e) {
292
				parentNode = null;
293
			}
294

    
295
			// start handle inline data
296
			if (localName.equals(INLINE)) {
297
				handleInlineData = true;
298
				// initialize namespace hash for in line data
299
				inlineDataNameSpace = new Hashtable<String, String>();
300
				// initialize file writer
301
				String docidWithoutRev = DocumentUtil.getDocIdFromString(docid);
302
				String seperator = ".";
303
				try {
304
					seperator = PropertyService.getProperty("document.accNumSeparator");
305
				} catch (PropertyNotFoundException pnfe) {
306
					logMetacat.error("Could not fing property 'accNumSeparator'. "
307
							+ "Setting separator to '.': " + pnfe.getMessage());
308
				}
309
				// the new file name will look like docid.rev.2
310
				inlineDataFileName = docidWithoutRev + seperator + revision + seperator
311
						+ distributionIndex;
312
				inlineDataFileWriter = createInlineDataFileWriter(inlineDataFileName, encoding);
313
				// put the inline file id into a vector. If upload failed,
314
				// metacat will delete the inline data file
315
				inlineFileIdList.add(inlineDataFileName);
316
				
317
				currentDistributionSection.setDistributionType(DistributionSection.INLINE_DATA_DISTRIBUTION);
318
				currentDistributionSection.setDataFileName(inlineDataFileName);
319

    
320
			}
321

    
322
			// If hit a text node, we need write this text for current's parent
323
			// node This will happen if the element is mixed
324
			if (hitTextNode && parentNode != null) {
325

    
326
				// compare top level access module
327
				if (processingTopLevelAccess && needToCheckAccessModule) {
328
					compareAccessTextNode(currentUnchangeableAccessModuleNodeStack, textBuffer);
329
				}
330

    
331
				if (needToCheckAccessModule
332
						&& (processingAdditionalAccess || processingOtherAccess || processingTopLevelAccess)) {
333
					// stored the pull out nodes into storedNode stack
334
					NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT", null,
335
							null, MetacatUtil.normalize(textBuffer.toString()));
336
					storedAccessNodeStack.push(nodeElement);
337

    
338
				}
339

    
340
				// write the textbuffer into db for parent node.
341
				endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer, parentNode);
342
				// rest hitTextNode
343
				hitTextNode = false;
344
				// reset textbuffer
345
				textBuffer = null;
346
				textBuffer = new StringBuffer();
347

    
348
			}
349

    
350
			// Document representation that points to the root document node
351
			if (atFirstElement) {
352
				atFirstElement = false;
353
				// If no DOCTYPE declaration: docname = root element
354
				// doctype = root element name or name space
355
				if (docname == null) {
356
					docname = localName;
357
					// if uri isn't null doctype = uri(namespace)
358
					// othewise root element
359
					if (uri != null && !(uri.trim()).equals("")) {
360
						doctype = uri;
361
					} else {
362
						doctype = docname;
363
					}
364
					logMetacat.debug("DOCNAME-a: " + docname);
365
					logMetacat.debug("DOCTYPE-a: " + doctype);
366
				} else if (doctype == null) {
367
					// because docname is not null and it is declared in dtd
368
					// so could not be in schema, no namespace
369
					doctype = docname;
370
					logMetacat.debug("DOCTYPE-b: " + doctype);
371
				}
372
				rootNode.writeNodename(docname);
373
				try {
374
					// for validated XML Documents store a reference to XML DB
375
					// Catalog. Because this is select statement and it needn't
376
					// roll back if insert document action failed. In order to
377
					// decrease DBConnection usage count, we get a new
378
					// dbconnection from pool String catalogid = null;
379
					DBConnection dbConn = null;
380
					int serialNumber = -1;
381

    
382
					try {
383
						// Get dbconnection
384
						dbConn = DBConnectionPool
385
								.getDBConnection("DBSAXHandler.startElement");
386
						serialNumber = dbConn.getCheckOutSerialNumber();
387
						
388
						String sql = "SELECT catalog_id FROM xml_catalog "
389
							+ "WHERE entry_type = 'Schema' "
390
							+ "AND public_id = ?";
391
						PreparedStatement pstmt = dbConn.prepareStatement(sql);
392
						pstmt.setString(1, doctype);
393
						ResultSet rs = pstmt.executeQuery();
394
						boolean hasRow = rs.next();
395
						if (hasRow) {
396
							catalogid = rs.getString(1);
397
						}
398
						pstmt.close();
399
					}// try
400
					finally {
401
						// Return dbconnection
402
						DBConnectionPool.returnDBConnection(dbConn, serialNumber);
403
					}// finally
404

    
405
					// create documentImpl object by the constructor which can
406
					// specify the revision
407
					if (!super.getIsRevisionDoc()) {
408
						currentDocument = new DocumentImpl(connection, rootNode
409
								.getNodeID(), docname, doctype, docid, revision, action,
410
								user, this.pub, catalogid, this.serverCode, createDate,
411
								updateDate);
412
					}
413

    
414
				} catch (McdbDocNotFoundException mdnfe) {
415
					Vector<Integer> revList = null;
416
					
417
					try {
418
						revList = DBUtil.getRevListFromRevisionTable(docid);
419
					} catch (SQLException sqle) {
420
						logMetacat.error("SQL error when trying to get rev list for doc " + docid + " : " + sqle.getMessage());
421
						throw (new SAXException("Doc ID " + docid + " was not found and cannot be updated.")); 
422
					}
423
					
424
					if (revList.size() > 0) {
425
						throw (new SAXException("EML210SaxHandler.startElement - Doc ID " + docid + " was deleted and cannot be updated."));
426
					} else {
427
						throw (new SAXException("EML210SaxHandler.startElement - Doc ID " + docid + " was not found and cannot be updated.")); 
428
					}
429
				} catch (Exception e) {
430
                    throw (new SAXException("EML210SaxHandler.startElement - error with action " + 
431
                    		action + " : " + e.getMessage()));
432
				}
433
			}
434

    
435
			// Create the current node representation
436
			currentNode = new DBSAXNode(connection, qName, localName, parentNode,
437
					rootNode.getNodeID(), docid, doctype);
438
			// Use a local variable to store the element node id
439
			// If this element is a start point of subtree(section), it will be
440
			// stored otherwise, it will be discarded
441
			long startNodeId = currentNode.getNodeID();
442
			// Add all of the namespaces
443
			String prefix = null;
444
			String nsuri = null;
445
			Enumeration<String> prefixes = namespaces.keys();
446
			while (prefixes.hasMoreElements()) {
447
				prefix = prefixes.nextElement();
448
				nsuri = namespaces.get(prefix);
449
				endNodeId = currentNode.setNamespace(prefix, nsuri, docid);
450
			}
451

    
452
			// Add all of the attributes
453
			for (int i = 0; i < atts.getLength(); i++) {
454
				String attributeName = atts.getQName(i);
455
				String attributeValue = atts.getValue(i);
456
				endNodeId = currentNode
457
						.setAttribute(attributeName, attributeValue, docid);
458

    
459
				// To handle name space and schema location if the attribute
460
				// name is xsi:schemaLocation. If the name space is in not
461
				// in catalog table it will be registered.
462
				if (attributeName != null
463
						&& attributeName.indexOf(MetaCatServlet.SCHEMALOCATIONKEYWORD) != -1) {
464
					SchemaLocationResolver resolver = new SchemaLocationResolver(
465
							attributeValue);
466
					resolver.resolveNameSpace();
467

    
468
				} else if (attributeName != null && attributeName.equals(ID)) {
469

    
470
				}
471
			}// for
472

    
473
			// handle access stuff
474
			if (localName.equals(ACCESS)) {
475
				if (parentNode.getTagName().equals(EML)) {
476
					processingTopLevelAccess = true;
477
				} else if (parentNode.getTagName() == DISTRIBUTION) {
478
					processingAdditionalAccess = true;
479
				} else {
480
					// process other access embedded into resource level
481
					// module
482
					processingOtherAccess = true;
483
				}
484
				// create access object
485
				accessObject = new AccessSection();
486
				// set permission order
487
				String permOrder = currentNode.getAttribute(ORDER);
488
				accessObject.setPermissionOrder(permOrder);
489
				// set access id
490
				String accessId = currentNode.getAttribute(ID);
491
				accessObject.setSubTreeId(accessId);
492
				accessObject.setStartNodeId(startNodeId);
493
				accessObject.setDocId(docid);
494
				if (processingAdditionalAccess) {
495
					accessObject.setDataFileName(inlineDataFileName);
496
				}
497

    
498
				// load top level node stack to
499
				// currentUnchangableAccessModuleNodeStack
500
				if (processingTopLevelAccess && needToCheckAccessModule) {
501
					// get the node stack for
502
					currentUnchangeableAccessModuleNodeStack = topAccessSection
503
							.getSubTreeNodeStack();
504
				}
505
			} else if (localName.equals(DISTRIBUTION)) {
506
				distributionIndex++;
507
				currentDistributionSection = new DistributionSection(distributionIndex);
508

    
509
				// handle subtree info
510
				SubTree subTree = new SubTree();
511
				// set sub tree id
512
				subTree.setSubTreeId(String.valueOf(distributionIndex));
513
				// set sub tree start element name
514
				subTree.setStartElementName(currentNode.getTagName());
515
				// set start node number
516
				subTree.setStartNodeId(startNodeId);
517
				// add to stack, but it didn't get end node id yet
518
				subTreeInfoStack.push(subTree);
519
			}
520
			// Set up a access rule for allow
521
			else if (parentNode.getTagName() != null
522
					&& (parentNode.getTagName()).equals(ACCESS)
523
					&& localName.equals(ALLOW)) {
524

    
525
				accessRule = new AccessRule();
526

    
527
				// set permission type "allow"
528
				accessRule.setPermissionType(ALLOW);
529

    
530
			}
531
			// set up an access rule for deny
532
			else if (parentNode.getTagName() != null
533
					&& (parentNode.getTagName()).equals(ACCESS) && localName.equals(DENY)) {
534
				accessRule = new AccessRule();
535
				// set permission type "allow"
536
				accessRule.setPermissionType(DENY);
537
			}
538

    
539
			// Add the node to the stack, so that any text data can be
540
			// added as it is encountered
541
			nodeStack.push(currentNode);
542
			// Add the node to the vector used by thread for writing XML Index
543
			nodeIndex.addElement(currentNode);
544

    
545
			// compare top access level module
546
			if (processingTopLevelAccess && needToCheckAccessModule) {
547
				compareElementNameSpaceAttributes(
548
						currentUnchangeableAccessModuleNodeStack, namespaces, atts,
549
						localName, UPDATEACCESSERROR);
550

    
551
			}
552

    
553
			// store access module element and attributes into stored stack
554
			if (needToCheckAccessModule
555
					&& (processingAdditionalAccess || processingOtherAccess || processingTopLevelAccess)) {
556
				// stored the pull out nodes into storedNode stack
557
				NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "ELEMENT", localName,
558
						prefix, MetacatUtil.normalize(null));
559
				storedAccessNodeStack.push(nodeElement);
560
				for (int i = 0; i < atts.getLength(); i++) {
561
					String attributeName = atts.getQName(i);
562
					String attributeValue = atts.getValue(i);
563
					NodeRecord nodeAttribute = new NodeRecord(-2, -2, -2, "ATTRIBUTE",
564
							attributeName, null, MetacatUtil.normalize(attributeValue));
565
					storedAccessNodeStack.push(nodeAttribute);
566
				}
567

    
568
			}
569

    
570
			// reset name space
571
			namespaces = null;
572
			namespaces = new Hashtable<String, String>();
573
		}// not inline data
574
		else {
575
			// we don't buffer the inline data in characters() method
576
			// so start character don't need to hand text node.
577

    
578
			// inline data may be the xml format.
579
			StringBuffer inlineElements = new StringBuffer();
580
			inlineElements.append("<").append(qName);
581
			// append attributes
582
			for (int i = 0; i < atts.getLength(); i++) {
583
				String attributeName = atts.getQName(i);
584
				String attributeValue = atts.getValue(i);
585
				inlineElements.append(" ");
586
				inlineElements.append(attributeName);
587
				inlineElements.append("=\"");
588
				inlineElements.append(attributeValue);
589
				inlineElements.append("\"");
590
			}
591
			// append namespace
592
			String prefix = null;
593
			String nsuri = null;
594
			Enumeration<String> prefixes = inlineDataNameSpace.keys();
595
			while (prefixes.hasMoreElements()) {
596
				prefix = prefixes.nextElement();
597
				nsuri = namespaces.get(prefix);
598
				inlineElements.append(" ");
599
				inlineElements.append("xmlns:");
600
				inlineElements.append(prefix);
601
				inlineElements.append("=\"");
602
				inlineElements.append(nsuri);
603
				inlineElements.append("\"");
604
			}
605
			inlineElements.append(">");
606
			// reset inline data name space
607
			inlineDataNameSpace = null;
608
			inlineDataNameSpace = new Hashtable<String, String>();
609
			// write inline data into file
610
			logMetacat.debug("the inline element data is: " + inlineElements.toString());
611
			writeInlineDataIntoFile(inlineDataFileWriter, inlineElements);
612
		}// else
613

    
614
	}
615

    
616
	private void compareElementNameSpaceAttributes(
617
			Stack<NodeRecord> unchangeableNodeStack,
618
			Hashtable<String, String> nameSpaces, Attributes attributes,
619
			String localName, String error) throws SAXException {
620
		// Get element subtree node stack (element node)
621
		NodeRecord elementNode = null;
622
		try {
623
			elementNode = unchangeableNodeStack.pop();
624
		} catch (EmptyStackException ee) {
625
			logMetacat.error("Node stack is empty for element data");
626
			throw new SAXException(error);
627
		}
628
		logMetacat.debug("current node type from xml is ELEMENT");
629
		logMetacat.debug("node type from stack: " + elementNode.getNodeType());
630
		logMetacat.debug("node name from xml document: " + localName);
631
		logMetacat.debug("node name from stack: " + elementNode.getNodeName());
632
		logMetacat.debug("node data from stack: " + elementNode.getNodeData());
633
		logMetacat.debug("node id is: " + elementNode.getNodeId());
634
		// if this node is not element or local name not equal or name space
635
		// not equals, throw an exception
636
		if (!elementNode.getNodeType().equals("ELEMENT")
637
				|| !localName.equals(elementNode.getNodeName()))
638
		// (uri != null && !uri.equals(elementNode.getNodePrefix())))
639
		{
640
			logMetacat.error("Inconsistence happened: ");
641
			logMetacat.error("current node type from xml is ELEMENT");
642
			logMetacat.error("node type from stack: " + elementNode.getNodeType());
643
			logMetacat.error("node name from xml document: " + localName);
644
			logMetacat.error("node name from stack: " + elementNode.getNodeName());
645
			logMetacat.error("node data from stack: " + elementNode.getNodeData());
646
			logMetacat.error("node id is: " + elementNode.getNodeId());
647
			throw new SAXException(error);
648
		}
649

    
650
		// compare namespace
651
		Enumeration<String> nameEn = nameSpaces.keys();
652
		while (nameEn.hasMoreElements()) {
653
			// Get namespacke node stack (element node)
654
			NodeRecord nameNode = null;
655
			try {
656
				nameNode = unchangeableNodeStack.pop();
657
			} catch (EmptyStackException ee) {
658
				logMetacat.error("Node stack is empty for namespace data");
659
				throw new SAXException(error);
660
			}
661

    
662
			String prefixName = nameEn.nextElement();
663
			String nameSpaceUri = nameSpaces.get(prefixName);
664
			if (!nameNode.getNodeType().equals("NAMESPACE")
665
					|| !prefixName.equals(nameNode.getNodeName())
666
					|| !nameSpaceUri.equals(nameNode.getNodeData())) {
667
				logMetacat.error("Inconsistence happened: ");
668
				logMetacat.error("current node type from xml is NAMESPACE");
669
				logMetacat.error("node type from stack: " + nameNode.getNodeType());
670
				logMetacat.error("current node name from xml is: " + prefixName);
671
				logMetacat.error("node name from stack: " + nameNode.getNodeName());
672
				logMetacat.error("current node data from xml is: " + nameSpaceUri);
673
				logMetacat.error("node data from stack: " + nameNode.getNodeData());
674
				logMetacat.error("node id is: " + nameNode.getNodeId());
675
				throw new SAXException(error);
676
			}
677

    
678
		}// while
679

    
680
		// compare attributes
681
		for (int i = 0; i < attributes.getLength(); i++) {
682
			NodeRecord attriNode = null;
683
			try {
684
				attriNode = unchangeableNodeStack.pop();
685

    
686
			} catch (EmptyStackException ee) {
687
				logMetacat.error("Node stack is empty for attribute data");
688
				throw new SAXException(error);
689
			}
690
			String attributeName = attributes.getQName(i);
691
			String attributeValue = attributes.getValue(i);
692
			logMetacat.debug("current node type from xml is ATTRIBUTE ");
693
			logMetacat.debug("node type from stack: " + attriNode.getNodeType());
694
			logMetacat.debug("current node name from xml is: " + attributeName);
695
			logMetacat.debug("node name from stack: " + attriNode.getNodeName());
696
			logMetacat.debug("current node data from xml is: " + attributeValue);
697
			logMetacat.debug("node data from stack: " + attriNode.getNodeData());
698
			logMetacat.debug("node id  is: " + attriNode.getNodeId());
699

    
700
			if (!attriNode.getNodeType().equals("ATTRIBUTE")
701
					|| !attributeName.equals(attriNode.getNodeName())
702
					|| !attributeValue.equals(attriNode.getNodeData())) {
703
				logMetacat.error("Inconsistence happened: ");
704
				logMetacat.error("current node type from xml is ATTRIBUTE ");
705
				logMetacat.error("node type from stack: " + attriNode.getNodeType());
706
				logMetacat.error("current node name from xml is: " + attributeName);
707
				logMetacat.error("node name from stack: " + attriNode.getNodeName());
708
				logMetacat.error("current node data from xml is: " + attributeValue);
709
				logMetacat.error("node data from stack: " + attriNode.getNodeData());
710
				logMetacat.error("node is: " + attriNode.getNodeId());
711
				throw new SAXException(error);
712
			}
713
		}// for
714

    
715
	}
716

    
717
	/* method to compare current text node and node in db */
718
	private void compareAccessTextNode(Stack<NodeRecord> nodeStack, StringBuffer text) throws SAXException {
719
		NodeRecord node = null;
720
		// get node from current stack
721
		try {
722
			node = nodeStack.pop();
723
		} catch (EmptyStackException ee) {
724
			logMetacat.error("Node stack is empty for text data in startElement for doc id " + docid);
725
			throw new SAXException("Access rules could not be found in database.");
726
		}
727

    
728
		String dbAccessData = node.getNodeData();
729
		String docAccessData = text.toString().trim();
730
		
731
		logMetacat.debug("Eml210SAXHandler.compareAccessTextNode - \n" +
732
					"\t access node type from db:       " + node.getNodeType() + "\n" +
733
					"\t access node data from db:       " + node.getNodeData() + "\n" +
734
					"\t access node data from document: " + text.toString());
735
		
736
		if (!node.getNodeType().equals("TEXT")
737
				|| !docAccessData.equals(dbAccessData)) {
738
			logMetacat.warn("Eml210SAXHandler.compareAccessTextNode - Access record mismatch: \n" +
739
					"\t access node type from db:       " + node.getNodeType() + "\n" +
740
					"\t access node data from db:       " + dbAccessData + "\n" +
741
					"\t access node data from document: " + docAccessData);
742
			
743
			throw new SAXException(UPDATEACCESSERROR + " [Eml210SAXHandler.compareAccessTextNode]");
744
		}// if
745
	}
746

    
747
	/** SAX Handler that is called for each XML text node */
748
	public void characters(char[] cbuf, int start, int len) throws SAXException {
749
		logMetacat.debug("CHARACTERS");
750
		if (!handleInlineData) {
751
			// buffer all text nodes for same element. This is for if text was
752
			// split into different nodes
753
			textBuffer.append(new String(cbuf, start, len));
754
			// set hittextnode true
755
			hitTextNode = true;
756
			// if text buffer .size is greater than max, write it to db.
757
			// so we can save memory
758
			if (textBuffer.length() > MAXDATACHARS) {
759
				logMetacat.debug("Write text into DB in charaters"
760
						+ " when text buffer size is greater than maxmum number");
761
				DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
762
				endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer, currentNode);
763
				textBuffer = null;
764
				textBuffer = new StringBuffer();
765
			}
766
		} else {
767
			// this is inline data and write file system directly
768
			// we don't need to buffer it.
769
			StringBuffer inlineText = new StringBuffer();
770
			inlineText.append(new String(cbuf, start, len));
771
			logMetacat.debug("The inline text data write into file system: "
772
					+ inlineText.toString());
773
			writeInlineDataIntoFile(inlineDataFileWriter, inlineText);
774
		}
775
	}
776

    
777
	/** SAX Handler that is called at the end of each XML element */
778
	public void endElement(String uri, String localName, String qName)
779
			throws SAXException {
780
		logMetacat.debug("End ELEMENT " + qName);
781

    
782
		if (localName.equals(INLINE) && handleInlineData) {
783
			// Get the node from the stack
784
			DBSAXNode currentNode = (DBSAXNode) nodeStack.pop();
785
			logMetacat.debug("End of inline data");
786
			// close file writer
787
			try {
788
				inlineDataFileWriter.close();
789
				handleInlineData = false;
790
			} catch (IOException ioe) {
791
				throw new SAXException(ioe.getMessage());
792
			}
793

    
794
			// write put inline data file name into text buffer (without path)
795
			textBuffer = new StringBuffer(inlineDataFileName);
796
			// write file name into db
797
			endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer, currentNode);
798
			// reset textbuff
799
			textBuffer = null;
800
			textBuffer = new StringBuffer();
801
			return;
802
		}
803

    
804
		if (!handleInlineData) {
805
			// Get the node from the stack
806
			DBSAXNode currentNode = (DBSAXNode) nodeStack.pop();
807
			String currentTag = currentNode.getTagName();
808

    
809
			// If before the end element, the parser hit text nodes and store
810
			// them into the buffer, write the buffer to data base. The reason
811
			// we put write database here is for xerces some time split text
812
			// node
813
			if (hitTextNode) {
814
				// get access value
815
				String data = null;
816
				// add principal
817
				if (currentTag.equals(PRINCIPAL) && accessRule != null) {
818
					data = (textBuffer.toString()).trim();
819
					accessRule.addPrincipal(data);
820

    
821
				} else if (currentTag.equals(PERMISSION) && accessRule != null) {
822
					data = (textBuffer.toString()).trim();
823
					// we combine different a permission into one value
824
					int permission = accessRule.getPermission();
825
					// add permission
826
					if (data.toUpperCase().equals(READSTRING)) {
827
						permission = permission | READ;
828
					} else if (data.toUpperCase().equals(WRITESTRING)) {
829
						permission = permission | WRITE;
830
					} else if (data.toUpperCase().equals(CHMODSTRING)) {
831
						permission = permission | CHMOD;
832
					} else if (data.toUpperCase().equals(ALLSTRING)) {
833
						permission = permission | ALL;
834
					}
835
					accessRule.setPermission(permission);
836
				} else if (currentTag.equals(REFERENCES)
837
						&& (processingTopLevelAccess || processingAdditionalAccess || processingOtherAccess)) {
838
					// get reference
839
					data = (textBuffer.toString()).trim();
840
					// put reference id into accessSection
841
					accessObject.setReferences(data);
842

    
843
				} else if (currentTag.equals(URL)) {
844
					// handle online data, make sure its'parent is online
845
					DBSAXNode parentNode = (DBSAXNode) nodeStack.peek();
846
					if (parentNode != null && parentNode.getTagName() != null
847
							&& parentNode.getTagName().equals(ONLINE)) {
848
						// if online data is in local metacat, add it to the
849
						// vector
850
						data = (textBuffer.toString()).trim();
851
						handleOnlineUrlDataFile(data);
852

    
853
					}// if
854
				}// else if
855
				
856
				// write text to db if it is not inline data
857
				logMetacat.debug("Write text into DB in End Element");
858

    
859
				// compare top level access module
860
				if (processingTopLevelAccess && needToCheckAccessModule) {
861
					compareAccessTextNode(currentUnchangeableAccessModuleNodeStack,
862
							textBuffer);
863
				}
864
				// write text node into db
865
				endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer, currentNode);
866
			}
867
			
868
			if (needToCheckAccessModule
869
					&& (processingAdditionalAccess || processingOtherAccess || processingTopLevelAccess)) {
870
				// stored the pull out nodes into storedNode stack
871
				NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT", null,
872
						null, MetacatUtil.normalize(textBuffer.toString()));
873
				storedAccessNodeStack.push(nodeElement);
874

    
875
			}
876

    
877
			// set hitText false
878
			hitTextNode = false;
879
			// reset textbuff
880
			textBuffer = null;
881
			textBuffer = new StringBuffer();
882

    
883
			// hand sub stree stuff
884
			if (!subTreeInfoStack.empty()) {
885
				SubTree tree = subTreeInfoStack.peek();// get last
886
				// subtree
887
				if (tree != null && tree.getStartElementName() != null
888
						&& (tree.getStartElementName()).equals(currentTag)) {
889
					// find the end of sub tree and set the end node id
890
					tree.setEndNodeId(endNodeId);
891
					// add the subtree into the final store palace
892
					subTreeList.add(tree);
893
					// get rid of it from stack
894
					subTreeInfoStack.pop();
895
				}// if
896
			}// if
897

    
898
			// access stuff
899
			if (currentTag.equals(ALLOW) || currentTag.equals(DENY)) {
900
				// finish parser access rule and assign it to new one
901
				AccessRule newRule = accessRule;
902
				// add the new rule to access section object
903
				accessObject.addAccessRule(newRule);
904
				// reset access rule
905
				accessRule = null;
906
			} else if (currentTag.equals(ACCESS)) {
907
				// finish parsing an access section and assign it to new one
908
				DBSAXNode parentNode = (DBSAXNode) nodeStack.peek();
909

    
910
				accessObject.setEndNodeId(endNodeId);
911

    
912
				if (parentNode != null && parentNode.getTagName() != null
913
						&& parentNode.getTagName().equals(DISTRIBUTION)) {
914
					describesId.add(String.valueOf(distributionIndex));
915
					currentDistributionSection.setAccessSection(accessObject);
916
				}
917

    
918
				AccessSection newAccessObject = accessObject;
919

    
920
				if (newAccessObject != null) {
921

    
922
					// add the accessSection into a vector to store it
923
					// if it is not a reference, need to store it
924
					if (newAccessObject.getReferences() == null) {
925

    
926
						newAccessObject.setStoredTmpNodeStack(storedAccessNodeStack);
927
						accessObjectList.add(newAccessObject);
928
					}
929
					if (processingTopLevelAccess) {
930

    
931
						// top level access control will handle whole document
932
						// -docid
933
						topLevelAccessControlMap.put(docid, newAccessObject);
934
						// reset processtopleveraccess tag
935

    
936
					}// if
937
					else if (processingAdditionalAccess) {
938
						// for additional control put everything in describes
939
						// value
940
						// and access object into hash
941
						for (int i = 0; i < describesId.size(); i++) {
942

    
943
							String subId = describesId.elementAt(i);
944
							if (subId != null) {
945
								additionalAccessControlMap.put(subId, newAccessObject);
946
							}// if
947
						}// for
948
						// add this hashtable in to vector
949

    
950
						additionalAccessMapList.add(additionalAccessControlMap);
951
						// reset this hashtable in order to store another
952
						// additional
953
						// accesscontrol
954
						additionalAccessControlMap = null;
955
						additionalAccessControlMap = new Hashtable<String, AccessSection>();
956
					}// if
957

    
958
				}// if
959
				// check if access node stack is empty after parsing top access
960
				// module
961

    
962
				if (needToCheckAccessModule && processingTopLevelAccess
963
						&& !currentUnchangeableAccessModuleNodeStack.isEmpty()) {
964

    
965
					logMetacat.error("Access node stack is not empty after "
966
							+ "parsing access subtree");
967
					throw new SAXException(UPDATEACCESSERROR);
968

    
969
				}
970
				// reset access section object
971

    
972
				accessObject = null;
973

    
974
				// reset tmp stored node stack
975
				storedAccessNodeStack = null;
976
				storedAccessNodeStack = new Stack<NodeRecord>();
977

    
978
				// reset flag
979
				processingAdditionalAccess = false;
980
				processingTopLevelAccess = false;
981
				processingOtherAccess = false;
982

    
983
			} else if (currentTag.equals(DISTRIBUTION)) {
984
				// If the current Distribution is inline or data and it doesn't have an access section
985
				// we use the top level access section (if it exists)
986
				if ((currentDistributionSection.getDistributionType() == DistributionSection.DATA_DISTRIBUTION 
987
						|| currentDistributionSection.getDistributionType() == DistributionSection.INLINE_DATA_DISTRIBUTION)
988
						&& currentDistributionSection.getAccessSection() == null
989
						&& topLevelAccessControlMap.size() > 0) {
990
					
991
					AccessSection accessSection = new AccessSection();
992
					accessSection.setDocId(docid);	
993
					AccessSection topLevelAccess = topLevelAccessControlMap.get(docid);
994
					accessSection.setPermissionOrder(topLevelAccess.getPermissionOrder());
995
					Vector<AccessRule> accessRuleList = topLevelAccess.getAccessRules();
996
					for (AccessRule accessRule : accessRuleList) {
997
						accessSection.addAccessRule(accessRule);
998
					}
999
					currentDistributionSection.setAccessSection(accessSection);
1000
				} 
1001
				if (currentDistributionSection.getAccessSection() != null) {
1002
					currentDistributionSection.getAccessSection().setDataFileName(currentDistributionSection.getDataFileName());
1003
				}
1004
				allDistributionSections.add(currentDistributionSection);
1005
				currentDistributionSection = null;
1006
				describesId = null;
1007
				describesId = new Vector<String>();
1008
			}
1009
		} else {
1010
			// this is in inline part
1011
			StringBuffer endElement = new StringBuffer();
1012
			endElement.append("</");
1013
			endElement.append(qName);
1014
			endElement.append(">");
1015
			logMetacat.debug("inline endElement: " + endElement.toString());
1016
			writeInlineDataIntoFile(inlineDataFileWriter, endElement);
1017
		}
1018
	}
1019

    
1020
	/**
1021
	 * SAX Handler that receives notification of comments in the DTD
1022
	 */
1023
	public void comment(char[] ch, int start, int length) throws SAXException {
1024
		logMetacat.debug("COMMENT");
1025
		if (!handleInlineData) {
1026
			if (!processingDTD) {
1027
				DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1028
				String str = new String(ch, start, length);
1029

    
1030
				// compare top level access module
1031
				if (processingTopLevelAccess && needToCheckAccessModule) {
1032
					compareCommentNode(currentUnchangeableAccessModuleNodeStack, str,
1033
							UPDATEACCESSERROR);
1034
				}
1035
				endNodeId = currentNode.writeChildNodeToDB("COMMENT", null, str, docid);
1036
				if (needToCheckAccessModule
1037
						&& (processingAdditionalAccess || processingOtherAccess || processingTopLevelAccess)) {
1038
					// stored the pull out nodes into storedNode stack
1039
					NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "COMMENT", null,
1040
							null, MetacatUtil.normalize(str));
1041
					storedAccessNodeStack.push(nodeElement);
1042

    
1043
				}
1044
			}
1045
		} else {
1046
			// inline data comment
1047
			StringBuffer inlineComment = new StringBuffer();
1048
			inlineComment.append("<!--");
1049
			inlineComment.append(new String(ch, start, length));
1050
			inlineComment.append("-->");
1051
			logMetacat.debug("inline data comment: " + inlineComment.toString());
1052
			writeInlineDataIntoFile(inlineDataFileWriter, inlineComment);
1053
		}
1054
	}
1055

    
1056
	/* Compare comment from xml and db */
1057
	private void compareCommentNode(Stack<NodeRecord> nodeStack, String string,
1058
			String error) throws SAXException {
1059
		NodeRecord node = null;
1060
		try {
1061
			node = nodeStack.pop();
1062
		} catch (EmptyStackException ee) {
1063
			logMetacat.error("the stack is empty for comment data");
1064
			throw new SAXException(error);
1065
		}
1066
		logMetacat.debug("current node type from xml is COMMENT");
1067
		logMetacat.debug("node type from stack: " + node.getNodeType());
1068
		logMetacat.debug("current node data from xml is: " + string);
1069
		logMetacat.debug("node data from stack: " + node.getNodeData());
1070
		logMetacat.debug("node is from stack: " + node.getNodeId());
1071
		// if not consistent terminate program and throw a exception
1072
		if (!node.getNodeType().equals("COMMENT") || !string.equals(node.getNodeData())) {
1073
			logMetacat.error("Inconsistence happened: ");
1074
			logMetacat.error("current node type from xml is COMMENT");
1075
			logMetacat.error("node type from stack: " + node.getNodeType());
1076
			logMetacat.error("current node data from xml is: " + string);
1077
			logMetacat.error("node data from stack: " + node.getNodeData());
1078
			logMetacat.error("node is from stack: " + node.getNodeId());
1079
			throw new SAXException(error);
1080
		}// if
1081
	}
1082

    
1083
	/**
1084
	 * SAX Handler called once for each processing instruction found: node that
1085
	 * PI may occur before or after the root element.
1086
	 */
1087
	public void processingInstruction(String target, String data) throws SAXException {
1088
		logMetacat.debug("PI");
1089
		if (!handleInlineData) {
1090
			DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1091
			endNodeId = currentNode.writeChildNodeToDB("PI", target, data, docid);
1092
		} else {
1093
			StringBuffer inlinePI = new StringBuffer();
1094
			inlinePI.append("<?");
1095
			inlinePI.append(target);
1096
			inlinePI.append(" ");
1097
			inlinePI.append(data);
1098
			inlinePI.append("?>");
1099
			logMetacat.debug("inline data pi is: " + inlinePI.toString());
1100
			writeInlineDataIntoFile(inlineDataFileWriter, inlinePI);
1101
		}
1102
	}
1103

    
1104
	/** SAX Handler that is called at the start of Namespace */
1105
	public void startPrefixMapping(String prefix, String uri) throws SAXException {
1106
		logMetacat.debug("NAMESPACE");
1107
		if (!handleInlineData) {
1108
			namespaces.put(prefix, uri);
1109
		} else {
1110
			inlineDataNameSpace.put(prefix, uri);
1111
		}
1112
	}
1113

    
1114
	/**
1115
	 * SAX Handler that is called for each XML text node that is Ignorable white
1116
	 * space
1117
	 */
1118
	public void ignorableWhitespace(char[] cbuf, int start, int len) throws SAXException {
1119
		// When validation is turned "on", white spaces are reported here
1120
		// When validation is turned "off" white spaces are not reported here,
1121
		// but through characters() callback
1122
		logMetacat.debug("IGNORABLEWHITESPACE");
1123
		if (!handleInlineData) {
1124
			DBSAXNode currentNode = (DBSAXNode) nodeStack.peek();
1125
				String data = new String(cbuf, start, len);
1126
				// compare whitespace in access top module
1127
				if (processingTopLevelAccess && needToCheckAccessModule) {
1128
					compareWhiteSpace(currentUnchangeableAccessModuleNodeStack, data,
1129
							UPDATEACCESSERROR);
1130
				}
1131
				// Write the content of the node to the database
1132
				if (needToCheckAccessModule
1133
						&& (processingAdditionalAccess || processingOtherAccess || processingTopLevelAccess)) {
1134
					// stored the pull out nodes into storedNode stack
1135
					NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT", null,
1136
							null, MetacatUtil.normalize(data));
1137
					storedAccessNodeStack.push(nodeElement);
1138

    
1139
				}
1140
				endNodeId = currentNode.writeChildNodeToDB("TEXT", null, data, docid);
1141
		} else {
1142
			// This is inline data write to file directly
1143
			StringBuffer inlineWhiteSpace = new StringBuffer(new String(cbuf, start, len));
1144
			writeInlineDataIntoFile(inlineDataFileWriter, inlineWhiteSpace);
1145
		}
1146

    
1147
	}
1148

    
1149
	/* Compare whitespace from xml and db */
1150
	private void compareWhiteSpace(Stack<NodeRecord> nodeStack, String string,
1151
			String error) throws SAXException {
1152
		NodeRecord node = null;
1153
		try {
1154
			node = nodeStack.pop();
1155
		} catch (EmptyStackException ee) {
1156
			logMetacat.error("the stack is empty for whitespace data");
1157
			throw new SAXException(error);
1158
		}
1159
		if (!node.getNodeType().equals("TEXT") || !string.equals(node.getNodeData())) {
1160
			logMetacat.error("Inconsistence happened: ");
1161
			logMetacat.error("current node type from xml is WHITESPACE TEXT");
1162
			logMetacat.error("node type from stack: " + node.getNodeType());
1163
			logMetacat.error("current node data from xml is: " + string);
1164
			logMetacat.error("node data from stack: " + node.getNodeData());
1165
			logMetacat.error("node is from stack: " + node.getNodeId());
1166
			throw new SAXException(error);
1167
		}// if
1168
	}
1169

    
1170
	/** SAX Handler that receives notification of end of the document */
1171
	public void endDocument() throws SAXException {
1172
		logMetacat.debug("end Document");
1173
		// There are some unchangable subtree didn't be compare
1174
		// This maybe cause user change the subtree id
1175
		if (!super.getIsRevisionDoc()) {
1176
			// write access rule to db
1177
			writeAccessRuleToDB();
1178
			// delete relation table
1179
			deleteRelations();
1180
			// write relations
1181
			for (int i = 0; i < onlineDataFileIdInRelationVector.size(); i++) {
1182
				String id = onlineDataFileIdInRelationVector.elementAt(i);
1183
				writeOnlineDataFileIdIntoRelationTable(id);
1184
			}
1185
		}
1186
	}
1187

    
1188
	/* The method to write all access rule into db */
1189
	private void writeAccessRuleToDB() throws SAXException {
1190
		// Delete old permssion
1191
		deletePermissionsInAccessTable(docid);
1192
		// write top leve access rule
1193
		writeTopLevelAccessRuleToDB();
1194
		// write additional access rule
1195
		// writeAdditionalAccessRuleToDB();
1196
		writeAdditionalAccessRulesToDB();
1197
	}// writeAccessRuleToDB
1198

    
1199
	/* The method to write top level access rule into db. */
1200
	private void writeTopLevelAccessRuleToDB() throws SAXException {
1201
		// for top document level
1202
		AccessSection accessSection = topLevelAccessControlMap.get(docid);
1203
		boolean top = true;
1204
		String subSectionId = null;
1205
		if (accessSection != null) {
1206
			AccessSection accessSectionObj = accessSection;
1207

    
1208
			// if accessSection is not null and is not reference
1209
			if (accessSectionObj.getReferences() == null) {
1210
				// write the top level access module into xml_accesssubtree to
1211
				// store info and then when update to check if the user can
1212
				// update it or not
1213
				deleteAccessSubTreeRecord(docid);
1214
				writeAccessSubTreeIntoDB(accessSectionObj, TOPLEVEL);
1215

    
1216
				// write access section into xml_access table
1217
				writeGivenAccessRuleIntoDB(accessSectionObj, top, subSectionId);
1218
				// write online data file into xml_access too.
1219
				// for (int i= 0; i <onlineDataFileIdInTopAccessVector.size();
1220
				// i++)
1221
				// {
1222
				// String id = onlineDataFileIdInTopAccessVector.elementAt(i);
1223
				// writeAccessRuleForRelatedDataFileIntoDB(accessSectionObj,
1224
				// id);
1225
				// }
1226

    
1227
			} else {
1228

    
1229
				// this is a reference and go trough the vector which contains
1230
				// all access object
1231
				String referenceId = accessSectionObj.getReferences();
1232
				boolean findAccessObject = false;
1233
				logMetacat.debug("referered id for top access: " + referenceId);
1234
				for (int i = 0; i < accessObjectList.size(); i++) {
1235
					AccessSection accessObj = accessObjectList.elementAt(i);
1236
					String accessObjId = accessObj.getSubTreeId();
1237
					if (referenceId != null && accessObj != null
1238
							&& referenceId.equals(accessObjId)) {
1239
						// make sure the user didn't change any thing in this
1240
						// access moduel
1241
						// too if user doesn't have all permission
1242
						if (needToCheckAccessModule) {
1243

    
1244
							Stack<NodeRecord> newStack = accessObj
1245
									.getStoredTmpNodeStack();
1246
							// revise order
1247
							newStack = DocumentUtil.reviseStack(newStack);
1248
							// go throught the vector of
1249
							// unChangeableAccessSubtreevector
1250
							// and find the one whose id is as same as
1251
							// referenceid
1252
							AccessSection oldAccessObj = getAccessSectionFromUnchangableAccessVector(referenceId);
1253
							// if oldAccessObj is null something is wrong
1254
							if (oldAccessObj == null) {
1255
								throw new SAXException(UPDATEACCESSERROR);
1256
							}// if
1257
							else {
1258
								// Get the node stack from old access obj
1259
								Stack<NodeRecord> oldStack = oldAccessObj
1260
										.getSubTreeNodeStack();
1261
								compareNodeStacks(newStack, oldStack);
1262
							}// else
1263
						}// if
1264
						// write accessobject into db
1265
						writeGivenAccessRuleIntoDB(accessObj, top, subSectionId);
1266
						// write online data file into xml_access too.
1267
						// for (int j= 0; j
1268
						// <onlineDataFileIdInTopAccessVector.size(); j++)
1269
						// {
1270
						// String id =
1271
						// onlineDataFileIdInTopAccessVector.elementAt(j);
1272
						// writeAccessRuleForRelatedDataFileIntoDB(accessSectionObj,
1273
						// id);
1274
						// }
1275

    
1276
						// write the reference access into xml_accesssubtree
1277
						// too write the top level access module into
1278
						// xml_accesssubtree to store info and then when update
1279
						// to check if the user can update it or not
1280
						deleteAccessSubTreeRecord(docid);
1281
						writeAccessSubTreeIntoDB(accessSectionObj, TOPLEVEL);
1282
						writeAccessSubTreeIntoDB(accessObj, SUBTREELEVEL);
1283
						findAccessObject = true;
1284
						break;
1285
					}
1286
				}// for
1287
				// if we couldn't find an access subtree id for this reference
1288
				// id
1289
				if (!findAccessObject) {
1290
					throw new SAXException("The referenceid: " + referenceId
1291
							+ " is not access subtree");
1292
				}// if
1293
			}// else
1294

    
1295
		}// if
1296
		else {
1297
			// couldn't find a access section object
1298
			logMetacat.warn("couldn't find access control for document: " + docid);
1299
		}
1300

    
1301
	}// writeTopLevelAccessRuletoDB
1302

    
1303
	/* Given a subtree id and find the responding access section */
1304
	private AccessSection getAccessSectionFromUnchangableAccessVector(String id) {
1305
		AccessSection result = null;
1306
		// Makse sure the id
1307
		if (id == null || id.equals("")) {
1308
			return result;
1309
		}
1310
		// go throught vector and find the list
1311
		for (int i = 0; i < unChangeableAccessSubTreeVector.size(); i++) {
1312
			AccessSection accessObj = unChangeableAccessSubTreeVector.elementAt(i);
1313
			if (accessObj.getSubTreeId() != null && (accessObj.getSubTreeId()).equals(id)) {
1314
				result = accessObj;
1315
			}// if
1316
		}// for
1317
		return result;
1318
	}// getAccessSectionFromUnchangableAccessVector
1319

    
1320
	/* Compare two node stacks to see if they are same */
1321
	private void compareNodeStacks(Stack<NodeRecord> stack1, Stack<NodeRecord> stack2)
1322
			throws SAXException {
1323
		// make sure stack1 and stack2 are not empty
1324
		if (stack1.isEmpty() || stack2.isEmpty()) {
1325
			logMetacat.error("Because stack is empty!");
1326
			throw new SAXException(UPDATEACCESSERROR);
1327
		}
1328
		// go throw two stacks and compare every element
1329
		while (!stack1.isEmpty()) {
1330
			// Pop an element from stack1
1331
			NodeRecord record1 = stack1.pop();
1332
			// Pop an element from stack2(stack 2 maybe empty)
1333
			NodeRecord record2 = null;
1334
			try {
1335
				record2 = stack2.pop();
1336
			} catch (EmptyStackException ee) {
1337
				logMetacat.error("Node stack2 is empty but stack1 isn't!");
1338
				throw new SAXException(UPDATEACCESSERROR);
1339
			}
1340
			// if two records are not same throw a exception
1341
			if (!record1.contentEquals(record2)) {
1342
				logMetacat.error("Two records from new and old stack are not " + "same!");
1343
				throw new SAXException(UPDATEACCESSERROR);
1344
			}// if
1345
		}// while
1346

    
1347
		// now stack1 is empty and we should make sure stack2 is empty too
1348
		if (!stack2.isEmpty()) {
1349
			logMetacat
1350
					.error("stack2 still has some elements while stack " + "is empty! ");
1351
			throw new SAXException(UPDATEACCESSERROR);
1352
		}// if
1353
	}// comparingNodeStacks
1354

    
1355
	/* The method to write additional access rule into db. */
1356
	private void writeAdditionalAccessRulesToDB() throws SAXException {
1357
		
1358
		// Iterate through every distribution and write access sections for data and inline
1359
		// types to the database
1360
		for (DistributionSection distributionSection : allDistributionSections) {			
1361
			// we're only interested in data and inline distributions
1362
			int distributionType = distributionSection.getDistributionType();
1363
			if (distributionType == DistributionSection.DATA_DISTRIBUTION
1364
					|| distributionType == DistributionSection.INLINE_DATA_DISTRIBUTION) {
1365
				AccessSection accessSection = distributionSection.getAccessSection();
1366
				
1367
				// If the distribution doesn't have an access section, we continue.
1368
				if (accessSection == null) {
1369
					continue;		
1370
				} 
1371
				
1372
				// We want to check file permissions for all online data updates and inserts, or for 
1373
				// inline updates.
1374
//				if (distributionType == DistributionSection.DATA_DISTRIBUTION
1375
//						|| (distributionType == DistributionSection.INLINE_DATA_DISTRIBUTION && action == "UPDATE")) {
1376

    
1377
				if (distributionType == DistributionSection.DATA_DISTRIBUTION) {
1378
					try {
1379
						PermissionController controller = new PermissionController(
1380
								distributionSection.getDataFileName(), false);
1381
						if (AccessionNumber.accNumberUsed(docid)
1382
								&& !controller.hasPermission(user, groups, "WRITE")) {
1383
							throw new SAXException(UPDATEACCESSERROR);
1384
						}
1385
					} catch (SQLException sqle) {
1386
						throw new SAXException(
1387
								"Database error checking user permissions: "
1388
										+ sqle.getMessage());
1389
					} catch (Exception e) {
1390
						throw new SAXException(
1391
								"General error checking user permissions: "
1392
										+ e.getMessage());
1393
					}
1394
				} else if (distributionType == DistributionSection.INLINE_DATA_DISTRIBUTION && action == "UPDATE") {
1395
					try {
1396
						PermissionController controller = new PermissionController(
1397
								docid, false);
1398

    
1399
						if (!controller.hasPermission(user, groups, "WRITE")) {
1400
							throw new SAXException(UPDATEACCESSERROR);
1401
						}
1402
					} catch (SQLException sqle) {
1403
						throw new SAXException(
1404
								"Database error checking user permissions: "
1405
										+ sqle.getMessage());
1406
					} catch (Exception e) {
1407
						throw new SAXException(
1408
								"General error checking user permissions: "
1409
										+ e.getMessage());
1410
					}
1411
				}
1412
				
1413
				String subSectionId = Integer.toString(distributionSection.getDistributionId());
1414
				writeGivenAccessRuleIntoDB(accessSection, false, subSectionId);
1415
			}
1416

    
1417
		}
1418
		
1419
		
1420
	}
1421

    
1422
	/* Write a given access rule into db */
1423
	private void writeGivenAccessRuleIntoDB(AccessSection accessSection,
1424
			boolean topLevel, String subSectionId) throws SAXException {
1425
		if (accessSection == null) {
1426
			throw new SAXException("The access object is null");
1427
		}
1428

    
1429
		String permOrder = accessSection.getPermissionOrder();
1430
		String sql = null;
1431
		PreparedStatement pstmt = null;
1432
		if (topLevel) {
1433
			sql = "INSERT INTO xml_access (docid, principal_name, permission, "
1434
					+ "perm_type, perm_order, accessfileid) VALUES "
1435
					+ " (?, ?, ?, ?, ?, ?)";
1436
		} else {
1437
			sql = "INSERT INTO xml_access (docid,principal_name, "
1438
					+ "permission, perm_type, perm_order, accessfileid, subtreeid"
1439
					+ ") VALUES" + " (?, ?, ?, ?, ?, ?, ?)";
1440
		}
1441
		try {
1442

    
1443
			pstmt = connection.prepareStatement(sql);
1444
			// Increase DBConnection usage count
1445
			connection.increaseUsageCount(1);
1446
			// Bind the values to the query
1447
			pstmt.setString(6, docid);
1448
			logMetacat.debug("Accessfileid in accesstable: " + docid);
1449
			pstmt.setString(5, permOrder);
1450
			logMetacat.debug("PermOder in accesstable: " + permOrder);
1451
			// if it is not top level, set subsection id
1452
			if (topLevel) {
1453
				pstmt.setString(1, docid);
1454
				logMetacat.debug("Docid in accesstable: " + docid);
1455
			}
1456
			if (!topLevel) {
1457
				pstmt.setString(1, accessSection.getDataFileName());
1458
				logMetacat.debug("Docid in accesstable: " + inlineDataFileName);
1459

    
1460
				// for subtree should specify the
1461
				if (subSectionId == null) {
1462
					throw new SAXException("The subsection is null");
1463
				}
1464

    
1465
				pstmt.setString(7, subSectionId);
1466
				logMetacat.debug("SubSectionId in accesstable: " + subSectionId);
1467
			}
1468

    
1469
			Vector<AccessRule> accessRules = accessSection.getAccessRules();
1470
			// go through every rule
1471
			for (int i = 0; i < accessRules.size(); i++) {
1472
				AccessRule rule = accessRules.elementAt(i);
1473
				String permType = rule.getPermissionType();
1474
				int permission = rule.getPermission();
1475
				pstmt.setInt(3, permission);
1476
				logMetacat.debug("permission in accesstable: " + permission);
1477
				pstmt.setString(4, permType);
1478
				logMetacat.debug("Permtype in accesstable: " + permType);
1479
				// go through every principle in rule
1480
				Vector<String> nameVector = rule.getPrincipal();
1481
				for (int j = 0; j < nameVector.size(); j++) {
1482
					String prName = nameVector.elementAt(j);
1483
					pstmt.setString(2, prName);
1484
					logMetacat.debug("Principal in accesstable: " + prName);
1485
					logMetacat.debug("running sql: " + pstmt.toString());
1486
					pstmt.execute();
1487
				}// for
1488
			}// for
1489
			pstmt.close();
1490
		}// try
1491
		catch (SQLException e) {
1492
			throw new SAXException("EMLSAXHandler.writeAccessRuletoDB(): "
1493
					+ e.getMessage());
1494
		}// catch
1495
		finally {
1496
			try {
1497
				pstmt.close();
1498
			} catch (SQLException ee) {
1499
				throw new SAXException("EMLSAXHandler.writeAccessRuletoDB(): "
1500
						+ ee.getMessage());
1501
			}
1502
		}// finally
1503

    
1504
	}// writeGivenAccessRuleIntoDB
1505

    
1506
	/* Write a gaven access rule into db */
1507
	private void writeAccessRuleForRelatedDataFileIntoDB(AccessSection accessSection,
1508
			String dataId) throws SAXException {
1509
		if (accessSection == null) {
1510
			throw new SAXException("The access object is null");
1511
		}
1512
		// get rid of rev from dataId
1513
		// dataId = MetacatUtil.getDocIdFromString(dataId);
1514
		String permOrder = accessSection.getPermissionOrder();
1515
		String sql = null;
1516
		PreparedStatement pstmt = null;
1517
		sql = "INSERT INTO xml_access (docid, principal_name, permission, "
1518
				+ "perm_type, perm_order, accessfileid) VALUES " + " (?, ?, ?, ?, ?, ?)";
1519

    
1520
		try {
1521

    
1522
			pstmt = connection.prepareStatement(sql);
1523
			// Increase DBConnection usage count
1524
			connection.increaseUsageCount(1);
1525
			// Bind the values to the query
1526
			pstmt.setString(1, dataId);
1527
			logMetacat.debug("Docid in accesstable: " + docid);
1528
			pstmt.setString(6, docid);
1529
			logMetacat.debug("Accessfileid in accesstable: " + docid);
1530
			pstmt.setString(5, permOrder);
1531
			logMetacat.debug("PermOder in accesstable: " + permOrder);
1532
			// if it is not top level, set subsection id
1533

    
1534
			Vector<AccessRule> accessRules = accessSection.getAccessRules();
1535
			// go through every rule
1536
			for (int i = 0; i < accessRules.size(); i++) {
1537
				AccessRule rule = accessRules.elementAt(i);
1538
				String permType = rule.getPermissionType();
1539
				int permission = rule.getPermission();
1540
				pstmt.setInt(3, permission);
1541
				logMetacat.debug("permission in accesstable: " + permission);
1542
				pstmt.setString(4, permType);
1543
				logMetacat.debug("Permtype in accesstable: " + permType);
1544
				// go through every principle in rule
1545
				Vector<String> nameVector = rule.getPrincipal();
1546
				for (int j = 0; j < nameVector.size(); j++) {
1547
					String prName = nameVector.elementAt(j);
1548
					pstmt.setString(2, prName);
1549
					logMetacat.debug("Principal in accesstable: " + prName);
1550
					logMetacat.debug("running sql: " + pstmt.toString());
1551
					pstmt.execute();
1552
				}// for
1553
			}// for
1554
			pstmt.close();
1555
		}// try
1556
		catch (SQLException e) {
1557
			throw new SAXException("EMLSAXHandler.writeAccessRuletoDB(): "
1558
					+ e.getMessage());
1559
		}// catch
1560
		finally {
1561
			try {
1562
				pstmt.close();
1563
			} catch (SQLException ee) {
1564
				throw new SAXException("EMLSAXHandler.writeAccessRuletoDB(): "
1565
						+ ee.getMessage());
1566
			}
1567
		}// finally
1568

    
1569
	}// writeAccessRuleForRalatedDataFileIntoDB
1570

    
1571
	/* Delete from db all permission for resources related to @aclid if any. */
1572
	private void deletePermissionsInAccessTable(String aclid) throws SAXException {
1573
		PreparedStatement pstmt = null;
1574
		try {
1575
			String sql = "DELETE FROM xml_access WHERE accessfileid = '" + aclid + "'";
1576
			// delete all acl records for resources related to @aclid if any
1577
			pstmt = connection.prepareStatement(sql);
1578
			pstmt.setString(1, aclid);
1579
			// Increase DBConnection usage count
1580
			connection.increaseUsageCount(1);
1581
			logMetacat.debug("running sql: " + sql);
1582
			pstmt.execute();
1583

    
1584
		} catch (SQLException e) {
1585
			throw new SAXException(e.getMessage());
1586
		} finally {
1587
			try {
1588
				pstmt.close();
1589
			} catch (SQLException ee) {
1590
				throw new SAXException(ee.getMessage());
1591
			}
1592
		}
1593
	}// deletePermissionsInAccessTable
1594

    
1595
	/*
1596
	 * In order to make sure only usr has "all" permission can update access
1597
	 * subtree in eml document we need to keep access subtree info in
1598
	 * xml_accesssubtree table, such as docid, version, startnodeid, endnodeid
1599
	 */
1600
	private void writeAccessSubTreeIntoDB(AccessSection accessSection, String level)
1601
			throws SAXException {
1602
		if (accessSection == null) {
1603
			throw new SAXException("The access object is null");
1604
		}
1605

    
1606
		String sql = null;
1607
		PreparedStatement pstmt = null;
1608
		sql = "INSERT INTO xml_accesssubtree (docid, rev, controllevel, "
1609
				+ "subtreeid, startnodeid, endnodeid) VALUES " + " (?, ?, ?, ?, ?, ?)";
1610
		try {
1611

    
1612
			pstmt = connection.prepareStatement(sql);
1613
			// Increase DBConnection usage count
1614
			connection.increaseUsageCount(1);
1615
			long startNodeId = accessSection.getStartNodeId();
1616
			long endNodeId = accessSection.getEndNodeId();
1617
			String sectionId = accessSection.getSubTreeId();
1618
			// Bind the values to the query
1619
			pstmt.setString(1, docid);
1620
			logMetacat.debug("Docid in access-subtreetable: " + docid);
1621
			pstmt.setLong(2, (new Long(revision)).longValue());
1622
			logMetacat.debug("rev in accesssubtreetable: " + revision);
1623
			pstmt.setString(3, level);
1624
			logMetacat.debug("contorl level in access-subtree table: " + level);
1625
			pstmt.setString(4, sectionId);
1626
			logMetacat.debug("Subtree id in access-subtree table: " + sectionId);
1627
			pstmt.setLong(5, startNodeId);
1628
			logMetacat.debug("Start node id is: " + startNodeId);
1629
			pstmt.setLong(6, endNodeId);
1630
			logMetacat.debug("End node id is: " + endNodeId);
1631
			logMetacat.debug("running sql: " + pstmt.toString());
1632
			pstmt.execute();
1633
			pstmt.close();
1634
		}// try
1635
		catch (SQLException e) {
1636
			throw new SAXException("EMLSAXHandler.writeAccessSubTreeIntoDB(): "
1637
					+ e.getMessage());
1638
		}// catch
1639
		finally {
1640
			try {
1641
				pstmt.close();
1642
			} catch (SQLException ee) {
1643
				throw new SAXException("EMLSAXHandler.writeAccessSubTreeIntoDB(): "
1644
						+ ee.getMessage());
1645
			}
1646
		}// finally
1647

    
1648
	}// writeAccessSubtreeIntoDB
1649

    
1650
	/* Delete every access subtree record from xml_accesssubtree. */
1651
	private void deleteAccessSubTreeRecord(String docId) throws SAXException {
1652
		PreparedStatement pstmt = null;
1653
		try {
1654
			String sql = "DELETE FROM xml_accesssubtree WHERE docid = ?";
1655
			// delete all acl records for resources related to @aclid if any
1656
			pstmt = connection.prepareStatement(sql);
1657
			pstmt.setString(1, docId);
1658
			// Increase DBConnection usage count
1659
			connection.increaseUsageCount(1);
1660
			logMetacat.debug("running sql: " + sql);
1661
			pstmt.execute();
1662

    
1663
		} catch (SQLException e) {
1664
			throw new SAXException(e.getMessage());
1665
		} finally {
1666
			try {
1667
				pstmt.close();
1668
			} catch (SQLException ee) {
1669
				throw new SAXException(ee.getMessage());
1670
			}
1671
		}
1672
	}// deleteAccessSubTreeRecord
1673

    
1674
	// open a file writer for writing inline data to file
1675
	private Writer createInlineDataFileWriter(String fileName, String encoding) throws SAXException {
1676
		Writer writer = null;
1677
		String path;
1678
		try {
1679
			path = PropertyService.getProperty("application.inlinedatafilepath");
1680
		} catch (PropertyNotFoundException pnfe) {
1681
			throw new SAXException(pnfe.getMessage());
1682
		}
1683
		/*
1684
		 * File inlineDataDirectory = new File(path);
1685
		 */
1686
		String newFile = path + "/" + fileName;
1687
		logMetacat.debug("inline file name: " + newFile);
1688
		try {
1689
			// true means append
1690
			writer = new OutputStreamWriter(new FileOutputStream(newFile, true), encoding);
1691
		} catch (IOException ioe) {
1692
			throw new SAXException(ioe.getMessage());
1693
		}
1694
		return writer;
1695
	}
1696

    
1697
	// write inline data into file system and return file name(without path)
1698
	private void writeInlineDataIntoFile(Writer writer, StringBuffer data)
1699
			throws SAXException {
1700
		try {
1701
			writer.write(data.toString());
1702
			writer.flush();
1703
		} catch (Exception e) {
1704
			throw new SAXException(e.getMessage());
1705
		}
1706
	}
1707

    
1708

    
1709

    
1710
	// if xml file failed to upload, we need to call this method to delete
1711
	// the inline data already in file system
1712
	public void deleteInlineFiles() throws SAXException {
1713
		if (!inlineFileIdList.isEmpty()) {
1714
			for (int i = 0; i < inlineFileIdList.size(); i++) {
1715
				String fileName = inlineFileIdList.elementAt(i);
1716
				deleteInlineDataFile(fileName);
1717
			}
1718
		}
1719
	}
1720

    
1721
	/* delete the inline data file */
1722
	private void deleteInlineDataFile(String fileName) throws SAXException {
1723
		String path;
1724
		try {
1725
			path = PropertyService.getProperty("application.inlinedatafilepath");
1726
		} catch (PropertyNotFoundException pnfe) {
1727
			throw new SAXException("Could not find inline data file path: "
1728
					+ pnfe.getMessage());
1729
		}
1730
		File inlineDataDirectory = new File(path);
1731
		File newFile = new File(inlineDataDirectory, fileName);
1732
		newFile.delete();
1733

    
1734
	}
1735

    
1736
	/* Delete relations */
1737
	private void deleteRelations() throws SAXException {
1738
		PreparedStatement pStmt = null;
1739
		String sql = "DELETE FROM xml_relation where docid =?";
1740
		try {
1741
			pStmt = connection.prepareStatement(sql);
1742
			// bind variable
1743
			pStmt.setString(1, docid);
1744
			// execute query
1745
			pStmt.execute();
1746
			pStmt.close();
1747
		}// try
1748
		catch (SQLException e) {
1749
			throw new SAXException("EMLSAXHandler.deleteRelations(): " + e.getMessage());
1750
		}// catch
1751
		finally {
1752
			try {
1753
				pStmt.close();
1754
			}// try
1755
			catch (SQLException ee) {
1756
				throw new SAXException("EMLSAXHandler.deleteRelations: "
1757
						+ ee.getMessage());
1758
			}// catch
1759
		}// finally
1760
	}
1761

    
1762
	/*
1763
	 * Write an online data file id into xml_relation table. The dataId
1764
	 * shouldnot have the revision
1765
	 */
1766
	private void writeOnlineDataFileIdIntoRelationTable(String dataId)
1767
			throws SAXException {
1768
		PreparedStatement pStmt = null;
1769
		String sql = "INSERT into xml_relation (docid, packagetype, subject, "
1770
				+ "relationship, object) values (?, ?, ?, ?, ?)";
1771
		try {
1772
			pStmt = connection.prepareStatement(sql);
1773
			// bind variable
1774
			pStmt.setString(1, docid);
1775
			pStmt.setString(2, doctype); //DocumentImpl.EML2_1_0NAMESPACE);
1776
			pStmt.setString(3, docid);
1777
			pStmt.setString(4, RELATION);
1778
			pStmt.setString(5, dataId);
1779
			// execute query
1780
			pStmt.execute();
1781
			pStmt.close();
1782
		}// try
1783
		catch (SQLException e) {
1784
			throw new SAXException(
1785
					"EMLSAXHandler.writeOnlineDataFileIdIntoRelationTable(): "
1786
							+ e.getMessage());
1787
		}// catch
1788
		finally {
1789
			try {
1790
				pStmt.close();
1791
			}// try
1792
			catch (SQLException ee) {
1793
				throw new SAXException(
1794
						"EMLSAXHandler.writeOnlineDataFileIdIntoRelationTable(): "
1795
								+ ee.getMessage());
1796
			}// catch
1797
		}// finally
1798

    
1799
	}// writeOnlineDataFileIdIntoRelationTable
1800

    
1801
	/*
1802
	 * This method will handle data file in online url. If the data file is in
1803
	 * ecogrid protocol, then the datafile identifier(without rev)should be put
1804
	 * into onlineDataFileRelationVector. The docid in this vector will be
1805
	 * insert into xml_relation table in endDocument(). If the data file doesn't
1806
	 * exsit in xml_documents or xml_revision table, or the user has all
1807
	 * permission to the data file if the docid already existed, the data file
1808
	 * id (without rev)will be put into onlineDataFileTopAccessVector. The top
1809
	 * access rules specified in this eml document will apply to the data file.
1810
	 * NEED to do: We should also need to implement http and ftp. Those external
1811
	 * files should be download and assign a data file id to it.
1812
	 */
1813
	private void handleOnlineUrlDataFile(String url) throws SAXException {
1814
		logMetacat.warn("The url is " + url);
1815

    
1816
		if (currentDistributionSection == null) {
1817
			throw new SAXException("Trying to set the online file name for a null"
1818
					+ " distribution section");
1819
		}
1820

    
1821
		// if the url is not in ecogrid protocol, null will be returned
1822
		String accessionNumber = DocumentUtil.getAccessionNumberFromEcogridIdentifier(url);
1823
		if (accessionNumber == null) {
1824
			// the accession number is null if the url does not references a
1825
			// local data file (url would start with "ecogrid://"
1826
			currentDistributionSection
1827
					.setDistributionType(DistributionSection.ONLINE_DATA_DISTRIBUTION);
1828
		} else {
1829
			// handle ecogrid protocol
1830
			// get rid of revision number to get the docid.
1831
			String docid = DocumentUtil.getDocIdFromAccessionNumber(accessionNumber);
1832

    
1833
			currentDistributionSection
1834
					.setDistributionType(DistributionSection.DATA_DISTRIBUTION);
1835
			currentDistributionSection.setDataFileName(docid);
1836

    
1837
			// distributionOnlineFileName = docid;
1838
			onlineDataFileIdInRelationVector.add(docid);
1839
			try {				
1840
				if (!AccessionNumber.accNumberUsed(docid)) {
1841
					onlineDataFileIdInTopAccessVector.add(docid);
1842
				} else {
1843
					PermissionController controller = new PermissionController(accessionNumber);				
1844
					if (controller.hasPermission(user, groups,AccessControlInterface.ALLSTRING)) {
1845
						onlineDataFileIdInTopAccessVector.add(docid);
1846
					} else {
1847
						throw new SAXException(UPDATEACCESSERROR);
1848
					}
1849
				} 
1850
			}// try
1851
			catch (Exception e) {
1852
				logMetacat.error("Eorr in "
1853
								+ "Eml210SAXHanlder.handleOnlineUrlDataFile is "
1854
								+ e.getMessage());
1855
				throw new SAXException(e.getMessage());
1856
			}
1857
		}
1858
	}
1859
}
(33-33/65)