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-12-16 12:21:20 -0800 (Fri, 16 Dec 2011) $'
11
 * '$Revision: 6802 $'
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.dataone.hazelcast.HazelcastService;
55
import edu.ucsb.nceas.metacat.properties.PropertyService;
56
import edu.ucsb.nceas.metacat.util.DocumentUtil;
57
import edu.ucsb.nceas.metacat.util.MetacatUtil;
58
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
59

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

    
66
	private boolean processingTopLevelAccess = false;
67

    
68
	private boolean processingAdditionalAccess = false;
69

    
70
	private boolean processingOtherAccess = false;
71

    
72
	private AccessSection accessObject = null;
73

    
74
	private AccessRule accessRule = null;
75

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

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

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

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

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

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

    
100
	private AccessSection topAccessSection;
101

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

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

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

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

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

    
118
	private Writer inlineDataFileWriter = null;
119

    
120
	private String inlineDataFileName = null;
121

    
122
	DistributionSection currentDistributionSection = null;
123

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

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

    
132
	// private String distributionOnlineFileName = null;
133

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
200
			if (action.equals("UPDATE")) {
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
				int latestRevision = DBUtil.getLatestRevisionInDocumentTable(docid);
204
				String previousDocid = 
205
					docid + PropertyService.getProperty("document.accNumSeparator") + latestRevision;
206
				
207
				PermissionController control = new PermissionController(previousDocid );
208
				if (!control.hasPermission(user, groups, AccessControlInterface.ALLSTRING)
209
						&& action != null) {
210
					needToCheckAccessModule = true;
211
					unChangeableAccessSubTreeVector = getAccessSubTreeListFromDB();
212
				}
213
			}
214

    
215
		} catch (Exception e) {
216
			throw new SAXException(e.getMessage());
217
		}
218
	}
219

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

    
231
		try {
232

    
233
			pstmt = connection.prepareStatement(sql);
234
			// Increase DBConnection usage count
235
			connection.increaseUsageCount(1);
236
			// Bind the values to the query
237
			pstmt.setString(1, docid);
238
			pstmt.execute();
239

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

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

    
290
		DBSAXNode parentNode = null;
291
		DBSAXNode currentNode = null;
292

    
293
		if (!handleInlineData) {
294
			// Get a reference to the parent node for the id
295
			try {
296
				parentNode = (DBSAXNode) nodeStack.peek();
297
			} catch (EmptyStackException e) {
298
				parentNode = null;
299
			}
300

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

    
326
			}
327

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

    
332
				// compare top level access module
333
				if (processingTopLevelAccess && needToCheckAccessModule) {
334
					compareAccessTextNode(currentUnchangeableAccessModuleNodeStack, textBuffer);
335
				}
336

    
337
				if (needToCheckAccessModule
338
						&& (processingAdditionalAccess || processingOtherAccess || processingTopLevelAccess)) {
339
					// stored the pull out nodes into storedNode stack
340
					NodeRecord nodeElement = new NodeRecord(-2, -2, -2, "TEXT", null,
341
							null, MetacatUtil.normalize(textBuffer.toString()));
342
					storedAccessNodeStack.push(nodeElement);
343

    
344
				}
345

    
346
				// write the textbuffer into db for parent node.
347
				endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer, parentNode);
348
				// rest hitTextNode
349
				hitTextNode = false;
350
				// reset textbuffer
351
				textBuffer = null;
352
				textBuffer = new StringBuffer();
353

    
354
			}
355

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

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

    
411
					// create documentImpl object by the constructor which can
412
					// specify the revision
413
					if (!super.getIsRevisionDoc()) {
414
						currentDocument = new DocumentImpl(connection, rootNode
415
								.getNodeID(), docname, doctype, docid, revision, action,
416
								user, this.pub, catalogid, this.serverCode, createDate,
417
								updateDate);
418
					}
419

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

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

    
458
			// Add all of the attributes
459
			for (int i = 0; i < atts.getLength(); i++) {
460
				String attributeName = atts.getQName(i);
461
				String attributeValue = atts.getValue(i);
462
				endNodeId = currentNode
463
						.setAttribute(attributeName, attributeValue, docid);
464

    
465
				// To handle name space and schema location if the attribute
466
				// name is xsi:schemaLocation. If the name space is in not
467
				// in catalog table it will be registered.
468
				if (attributeName != null
469
						&& attributeName.indexOf(MetaCatServlet.SCHEMALOCATIONKEYWORD) != -1) {
470
					SchemaLocationResolver resolver = new SchemaLocationResolver(
471
							attributeValue);
472
					resolver.resolveNameSpace();
473

    
474
				} else if (attributeName != null && attributeName.equals(ID)) {
475

    
476
				}
477
			}// for
478

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

    
504
				// load top level node stack to
505
				// currentUnchangableAccessModuleNodeStack
506
				if (processingTopLevelAccess && needToCheckAccessModule) {
507
					// get the node stack for
508
					currentUnchangeableAccessModuleNodeStack = topAccessSection
509
							.getSubTreeNodeStack();
510
				}
511
			} else if (localName.equals(DISTRIBUTION)) {
512
				distributionIndex++;
513
				currentDistributionSection = new DistributionSection(distributionIndex);
514

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

    
531
				accessRule = new AccessRule();
532

    
533
				// set permission type "allow"
534
				accessRule.setPermissionType(ALLOW);
535

    
536
			}
537
			// set up an access rule for deny
538
			else if (parentNode.getTagName() != null
539
					&& (parentNode.getTagName()).equals(ACCESS) && localName.equals(DENY)) {
540
				accessRule = new AccessRule();
541
				// set permission type "allow"
542
				accessRule.setPermissionType(DENY);
543
			}
544

    
545
			// Add the node to the stack, so that any text data can be
546
			// added as it is encountered
547
			nodeStack.push(currentNode);
548
			// Add the node to the vector used by thread for writing XML Index
549
			nodeIndex.addElement(currentNode);
550

    
551
			// compare top access level module
552
			if (processingTopLevelAccess && needToCheckAccessModule) {
553
				compareElementNameSpaceAttributes(
554
						currentUnchangeableAccessModuleNodeStack, namespaces, atts,
555
						localName, UPDATEACCESSERROR);
556

    
557
			}
558

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

    
574
			}
575

    
576
			// reset name space
577
			namespaces = null;
578
			namespaces = new Hashtable<String, String>();
579
		}// not inline data
580
		else {
581
			// we don't buffer the inline data in characters() method
582
			// so start character don't need to hand text node.
583

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

    
620
	}
621

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

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

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

    
684
		}// while
685

    
686
		// compare attributes
687
		for (int i = 0; i < attributes.getLength(); i++) {
688
			NodeRecord attriNode = null;
689
			try {
690
				attriNode = unchangeableNodeStack.pop();
691

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

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

    
721
	}
722

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

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

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

    
783
	/** SAX Handler that is called at the end of each XML element */
784
	public void endElement(String uri, String localName, String qName)
785
			throws SAXException {
786
		logMetacat.debug("End ELEMENT " + qName);
787

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

    
800
			// write put inline data file name into text buffer (without path)
801
			textBuffer = new StringBuffer(inlineDataFileName);
802
			// write file name into db
803
			endNodeId = writeTextForDBSAXNode(endNodeId, textBuffer, currentNode);
804
			// reset textbuff
805
			textBuffer = null;
806
			textBuffer = new StringBuffer();
807
			return;
808
		}
809

    
810
		if (!handleInlineData) {
811
			// Get the node from the stack
812
			DBSAXNode currentNode = (DBSAXNode) nodeStack.pop();
813
			String currentTag = currentNode.getTagName();
814

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

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

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

    
859
					}// if
860
				}// else if
861
				
862
				// write text to db if it is not inline data
863
				logMetacat.debug("Write text into DB in End Element");
864

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

    
881
			}
882

    
883
			// set hitText false
884
			hitTextNode = false;
885
			// reset textbuff
886
			textBuffer = null;
887
			textBuffer = new StringBuffer();
888

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

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

    
916
				accessObject.setEndNodeId(endNodeId);
917

    
918
				if (parentNode != null && parentNode.getTagName() != null
919
						&& parentNode.getTagName().equals(DISTRIBUTION)) {
920
					describesId.add(String.valueOf(distributionIndex));
921
					currentDistributionSection.setAccessSection(accessObject);
922
				}
923

    
924
				AccessSection newAccessObject = accessObject;
925

    
926
				if (newAccessObject != null) {
927

    
928
					// add the accessSection into a vector to store it
929
					// if it is not a reference, need to store it
930
					if (newAccessObject.getReferences() == null) {
931

    
932
						newAccessObject.setStoredTmpNodeStack(storedAccessNodeStack);
933
						accessObjectList.add(newAccessObject);
934
					}
935
					if (processingTopLevelAccess) {
936

    
937
						// top level access control will handle whole document
938
						// -docid
939
						topLevelAccessControlMap.put(docid, newAccessObject);
940
						// reset processtopleveraccess tag
941

    
942
					}// if
943
					else if (processingAdditionalAccess) {
944
						// for additional control put everything in describes
945
						// value
946
						// and access object into hash
947
						for (int i = 0; i < describesId.size(); i++) {
948

    
949
							String subId = describesId.elementAt(i);
950
							if (subId != null) {
951
								additionalAccessControlMap.put(subId, newAccessObject);
952
							}// if
953
						}// for
954
						// add this hashtable in to vector
955

    
956
						additionalAccessMapList.add(additionalAccessControlMap);
957
						// reset this hashtable in order to store another
958
						// additional
959
						// accesscontrol
960
						additionalAccessControlMap = null;
961
						additionalAccessControlMap = new Hashtable<String, AccessSection>();
962
					}// if
963

    
964
				}// if
965
				// check if access node stack is empty after parsing top access
966
				// module
967

    
968
				if (needToCheckAccessModule && processingTopLevelAccess
969
						&& !currentUnchangeableAccessModuleNodeStack.isEmpty()) {
970

    
971
					logMetacat.error("Access node stack is not empty after "
972
							+ "parsing access subtree");
973
					throw new SAXException(UPDATEACCESSERROR);
974

    
975
				}
976
				// reset access section object
977

    
978
				accessObject = null;
979

    
980
				// reset tmp stored node stack
981
				storedAccessNodeStack = null;
982
				storedAccessNodeStack = new Stack<NodeRecord>();
983

    
984
				// reset flag
985
				processingAdditionalAccess = false;
986
				processingTopLevelAccess = false;
987
				processingOtherAccess = false;
988

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

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

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

    
1049
				}
1050
			}
1051
		} else {
1052
			// inline data comment
1053
			StringBuffer inlineComment = new StringBuffer();
1054
			inlineComment.append("<!--");
1055
			inlineComment.append(new String(ch, start, length));
1056
			inlineComment.append("-->");
1057
			logMetacat.debug("inline data comment: " + inlineComment.toString());
1058
			writeInlineDataIntoFile(inlineDataFileWriter, inlineComment);
1059
		}
1060
	}
1061

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

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

    
1110
	/** SAX Handler that is called at the start of Namespace */
1111
	public void startPrefixMapping(String prefix, String uri) throws SAXException {
1112
		logMetacat.debug("NAMESPACE");
1113
		if (!handleInlineData) {
1114
			namespaces.put(prefix, uri);
1115
		} else {
1116
			inlineDataNameSpace.put(prefix, uri);
1117
		}
1118
	}
1119

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

    
1145
				}
1146
				endNodeId = currentNode.writeChildNodeToDB("TEXT", null, data, docid);
1147
		} else {
1148
			// This is inline data write to file directly
1149
			StringBuffer inlineWhiteSpace = new StringBuffer(new String(cbuf, start, len));
1150
			writeInlineDataIntoFile(inlineDataFileWriter, inlineWhiteSpace);
1151
		}
1152

    
1153
	}
1154

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

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

    
1194
	/* The method to write all access rule into db */
1195
	private void writeAccessRuleToDB() throws SAXException {
1196
		// Delete old permssion
1197
		deletePermissionsInAccessTable();
1198
		// write top leve access rule
1199
		writeTopLevelAccessRuleToDB();
1200
		// write additional access rule
1201
		// writeAdditionalAccessRuleToDB();
1202
		writeAdditionalAccessRulesToDB();
1203
	}// writeAccessRuleToDB
1204

    
1205
	/* The method to write top level access rule into db. */
1206
	private void writeTopLevelAccessRuleToDB() throws SAXException {
1207
		// for top document level
1208
		AccessSection accessSection = topLevelAccessControlMap.get(docid);
1209
		boolean top = true;
1210
		String subSectionId = null;
1211
		if (accessSection != null) {
1212
			AccessSection accessSectionObj = accessSection;
1213

    
1214
			// if accessSection is not null and is not reference
1215
			if (accessSectionObj.getReferences() == null) {
1216
				// write the top level access module into xml_accesssubtree to
1217
				// store info and then when update to check if the user can
1218
				// update it or not
1219
				deleteAccessSubTreeRecord(docid);
1220
				writeAccessSubTreeIntoDB(accessSectionObj, TOPLEVEL);
1221

    
1222
				// write access section into xml_access table
1223
				writeGivenAccessRuleIntoDB(accessSectionObj, top, subSectionId);
1224
				// write online data file into xml_access too.
1225
				// for (int i= 0; i <onlineDataFileIdInTopAccessVector.size();
1226
				// i++)
1227
				// {
1228
				// String id = onlineDataFileIdInTopAccessVector.elementAt(i);
1229
				// writeAccessRuleForRelatedDataFileIntoDB(accessSectionObj,
1230
				// id);
1231
				// }
1232

    
1233
			} else {
1234

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

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

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

    
1301
		}// if
1302
		else {
1303
			// couldn't find a access section object
1304
			logMetacat.warn("couldn't find access control for document: " + docid);
1305
		}
1306

    
1307
	}// writeTopLevelAccessRuletoDB
1308

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

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

    
1353
		// now stack1 is empty and we should make sure stack2 is empty too
1354
		if (!stack2.isEmpty()) {
1355
			logMetacat
1356
					.error("stack2 still has some elements while stack " + "is empty! ");
1357
			throw new SAXException(UPDATEACCESSERROR);
1358
		}// if
1359
	}// comparingNodeStacks
1360

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

    
1383
				if (distributionType == DistributionSection.DATA_DISTRIBUTION) {
1384
					try {
1385
						// check for the previous version for permissions on update
1386
						String dataDocid = distributionSection.getDataFileName();
1387
						String previousDocid = dataDocid;
1388
						if (action == "UPDATE") {
1389
							String docidWithoutRev = DocumentUtil.getDocIdFromString(dataDocid);
1390
							int latestRevision = DBUtil.getLatestRevisionInDocumentTable(docidWithoutRev);
1391
							if (latestRevision > 0) {
1392
								previousDocid = docidWithoutRev + PropertyService.getProperty("document.accNumSeparator") + latestRevision;
1393
							}
1394
						}
1395
						
1396
						PermissionController controller = new PermissionController(previousDocid);
1397
						
1398
						if (AccessionNumber.accNumberUsed(docid)
1399
								&& !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
				} else if (distributionType == DistributionSection.INLINE_DATA_DISTRIBUTION && action == "UPDATE") {
1412
					try {
1413
						
1414
						// check for the previous version for permissions
1415
						int latestRevision = DBUtil.getLatestRevisionInDocumentTable(docid);
1416
						String previousDocid = 
1417
							docid + PropertyService.getProperty("document.accNumSeparator") + latestRevision;
1418
						PermissionController controller = new PermissionController(previousDocid);
1419

    
1420
						if (!controller.hasPermission(user, groups, "WRITE")) {
1421
							throw new SAXException(UPDATEACCESSERROR);
1422
						}
1423
					} catch (SQLException sqle) {
1424
						throw new SAXException(
1425
								"Database error checking user permissions: "
1426
										+ sqle.getMessage());
1427
					} catch (Exception e) {
1428
						throw new SAXException(
1429
								"General error checking user permissions: "
1430
										+ e.getMessage());
1431
					}
1432
				}
1433
				
1434
				// clear previous versions first
1435
				deleteAccessRule(accessSection, false);
1436
				
1437
				// now write the new ones
1438
				String subSectionId = Integer.toString(distributionSection.getDistributionId());
1439
				writeGivenAccessRuleIntoDB(accessSection, false, subSectionId);
1440
			}
1441

    
1442
		}
1443
		
1444
		
1445
	}
1446
	
1447
	/**
1448
	 *  delete existing access for given access rule
1449
	 *  
1450
	 */
1451
	private void deleteAccessRule(AccessSection accessSection, boolean topLevel) throws SAXException {
1452
		
1453
		if (accessSection == null) {
1454
			throw new SAXException("The access object is null");
1455
		}
1456
		
1457
		PreparedStatement pstmt = null;
1458

    
1459
		String sql = null;
1460
		sql = "DELETE FROM xml_access WHERE guid = ?";
1461
			
1462
		try {
1463

    
1464
			pstmt = connection.prepareStatement(sql);
1465
			// Increase DBConnection usage count
1466
			connection.increaseUsageCount(1);
1467
			// Bind the values to the query
1468
			String guid = null;
1469
			if (topLevel) {
1470
				try {
1471
					guid = IdentifierManager.getInstance().getGUID(docid, Integer.valueOf(revision));
1472
				} catch (NumberFormatException e) {
1473
					throw new SAXException(e.getMessage(), e);
1474
				} catch (McdbDocNotFoundException e) {
1475
					// register the default mapping now
1476
					guid = docid + "." + revision;
1477
					IdentifierManager.getInstance().createMapping(guid, guid);
1478
				}
1479
			} else {
1480
				guid = accessSection.getDataFileName();
1481
				
1482
			}
1483
			pstmt.setString(1, guid);
1484
			logMetacat.debug("guid in accesstable: " + guid);
1485
			
1486
			logMetacat.debug("running sql: " + pstmt.toString());
1487
			pstmt.execute();
1488
			
1489
			pstmt.close();
1490
		}// try
1491
		catch (SQLException e) {
1492
			throw new SAXException("EMLSAXHandler.deleteAccessRule(): "
1493
					+ e.getMessage());
1494
		}// catch
1495
		finally {
1496
			try {
1497
				pstmt.close();
1498
			} catch (SQLException ee) {
1499
				throw new SAXException("EMLSAXHandler.deleteAccessRule(): "
1500
						+ ee.getMessage());
1501
			}
1502
		}// finally
1503

    
1504
	}
1505

    
1506
	/* Write a given access rule into db */
1507
	private void writeGivenAccessRuleIntoDB(AccessSection accessSection,
1508
			boolean topLevel, String subSectionId) throws SAXException {
1509
		if (accessSection == null) {
1510
			throw new SAXException("The access object is null");
1511
		}
1512

    
1513
		String guid = null;
1514
		String referencedGuid = accessSection.getDataFileName();
1515

    
1516
		try {
1517
			guid = IdentifierManager.getInstance().getGUID(docid, Integer.valueOf(revision));
1518
		} catch (NumberFormatException e) {
1519
			throw new SAXException(e.getMessage(), e);
1520
		} catch (McdbDocNotFoundException e) {
1521
			// register the default mapping now
1522
			guid = docid + "." + revision;
1523
			IdentifierManager.getInstance().createMapping(guid, guid);
1524
		}
1525
		
1526
		String permOrder = accessSection.getPermissionOrder();
1527
		String sql = null;
1528
		PreparedStatement pstmt = null;
1529
		if (topLevel) {
1530
			sql = "INSERT INTO xml_access (guid, principal_name, permission, "
1531
					+ "perm_type, perm_order, accessfileid) VALUES "
1532
					+ " (?, ?, ?, ?, ?, ?)";
1533
		} else {
1534
			sql = "INSERT INTO xml_access (guid,principal_name, "
1535
					+ "permission, perm_type, perm_order, accessfileid, subtreeid"
1536
					+ ") VALUES" + " (?, ?, ?, ?, ?, ?, ?)";
1537
		}
1538
		try {
1539

    
1540
			pstmt = connection.prepareStatement(sql);
1541
			// Increase DBConnection usage count
1542
			connection.increaseUsageCount(1);
1543
			// Bind the values to the query
1544
			pstmt.setString(6, guid);
1545
			logMetacat.debug("Accessfileid in accesstable: " + guid);
1546
			pstmt.setString(5, permOrder);
1547
			logMetacat.debug("PermOder in accesstable: " + permOrder);
1548
			// if it is not top level, set subsection id
1549
			if (topLevel) {
1550
				pstmt.setString(1, guid);
1551
				logMetacat.debug("Guid in accesstable: " + guid);
1552
			}
1553
			if (!topLevel) {
1554
				// use the referenced guid
1555
				pstmt.setString(1, referencedGuid );
1556
				logMetacat.debug("Docid in accesstable: " + inlineDataFileName);
1557

    
1558
				// for subtree should specify the
1559
				if (subSectionId == null) {
1560
					throw new SAXException("The subsection is null");
1561
				}
1562

    
1563
				pstmt.setString(7, subSectionId);
1564
				logMetacat.debug("SubSectionId in accesstable: " + subSectionId);
1565
			}
1566

    
1567
			Vector<AccessRule> accessRules = accessSection.getAccessRules();
1568
			// go through every rule
1569
			for (int i = 0; i < accessRules.size(); i++) {
1570
				AccessRule rule = accessRules.elementAt(i);
1571
				String permType = rule.getPermissionType();
1572
				int permission = rule.getPermission();
1573
				pstmt.setInt(3, permission);
1574
				logMetacat.debug("permission in accesstable: " + permission);
1575
				pstmt.setString(4, permType);
1576
				logMetacat.debug("Permtype in accesstable: " + permType);
1577
				// go through every principle in rule
1578
				Vector<String> nameVector = rule.getPrincipal();
1579
				for (int j = 0; j < nameVector.size(); j++) {
1580
					String prName = nameVector.elementAt(j);
1581
					pstmt.setString(2, prName);
1582
					logMetacat.debug("Principal in accesstable: " + prName);
1583
					logMetacat.debug("running sql: " + pstmt.toString());
1584
					pstmt.execute();
1585
				}// for
1586
			}// for
1587
			pstmt.close();
1588
		}// try
1589
		catch (SQLException e) {
1590
			throw new SAXException("EMLSAXHandler.writeAccessRuletoDB(): "
1591
					+ e.getMessage());
1592
		}// catch
1593
		finally {
1594
			try {
1595
				pstmt.close();
1596
			} catch (SQLException ee) {
1597
				throw new SAXException("EMLSAXHandler.writeAccessRuletoDB(): "
1598
						+ ee.getMessage());
1599
			}
1600
		}// finally
1601
		
1602
		// for D1, refresh the entries
1603
		HazelcastService.getInstance().refreshSystemMetadataEntry(guid);
1604
		HazelcastService.getInstance().refreshSystemMetadataEntry(referencedGuid);
1605
		
1606

    
1607
	}// writeGivenAccessRuleIntoDB
1608

    
1609
	/* Delete from db all permission for resources related to the document, if any */
1610
	private void deletePermissionsInAccessTable() throws SAXException {
1611
		PreparedStatement pstmt = null;
1612
		try {
1613
			
1614
			String sql = "DELETE FROM xml_access " +
1615
					// the file defines access for another file
1616
					"WHERE accessfileid IN " +
1617
						"(SELECT guid from identifier where docid = ? and rev = ?) " +
1618
					// the described file has other versions describing it	
1619
					"OR guid IN " +
1620
						"(SELECT xa.guid from xml_access xa, identifier id" +
1621
						" WHERE xa.accessfileid = id.guid " +
1622
						" AND id.docid = ?" +
1623
						" AND id.rev = ?)";
1624
			// delete all acl records for resources related to @aclid if any
1625
			pstmt = connection.prepareStatement(sql);
1626
			pstmt.setString(1, docid);
1627
			pstmt.setInt(2, Integer.valueOf(revision));
1628
			// second part of query
1629
			pstmt.setString(3, docid);
1630
			pstmt.setInt(4, Integer.valueOf(revision));
1631
			// Increase DBConnection usage count
1632
			connection.increaseUsageCount(1);
1633
			logMetacat.debug("running sql: " + sql);
1634
			pstmt.execute();
1635

    
1636
		} catch (SQLException e) {
1637
			throw new SAXException(e.getMessage());
1638
		} finally {
1639
			try {
1640
				pstmt.close();
1641
			} catch (SQLException ee) {
1642
				throw new SAXException(ee.getMessage());
1643
			}
1644
		}
1645
	}// deletePermissionsInAccessTable
1646

    
1647
	/*
1648
	 * In order to make sure only usr has "all" permission can update access
1649
	 * subtree in eml document we need to keep access subtree info in
1650
	 * xml_accesssubtree table, such as docid, version, startnodeid, endnodeid
1651
	 */
1652
	private void writeAccessSubTreeIntoDB(AccessSection accessSection, String level)
1653
			throws SAXException {
1654
		if (accessSection == null) {
1655
			throw new SAXException("The access object is null");
1656
		}
1657

    
1658
		String sql = null;
1659
		PreparedStatement pstmt = null;
1660
		sql = "INSERT INTO xml_accesssubtree (docid, rev, controllevel, "
1661
				+ "subtreeid, startnodeid, endnodeid) VALUES " + " (?, ?, ?, ?, ?, ?)";
1662
		try {
1663

    
1664
			pstmt = connection.prepareStatement(sql);
1665
			// Increase DBConnection usage count
1666
			connection.increaseUsageCount(1);
1667
			long startNodeId = accessSection.getStartNodeId();
1668
			long endNodeId = accessSection.getEndNodeId();
1669
			String sectionId = accessSection.getSubTreeId();
1670
			// Bind the values to the query
1671
			pstmt.setString(1, docid);
1672
			logMetacat.debug("Docid in access-subtreetable: " + docid);
1673
			pstmt.setLong(2, (new Long(revision)).longValue());
1674
			logMetacat.debug("rev in accesssubtreetable: " + revision);
1675
			pstmt.setString(3, level);
1676
			logMetacat.debug("contorl level in access-subtree table: " + level);
1677
			pstmt.setString(4, sectionId);
1678
			logMetacat.debug("Subtree id in access-subtree table: " + sectionId);
1679
			pstmt.setLong(5, startNodeId);
1680
			logMetacat.debug("Start node id is: " + startNodeId);
1681
			pstmt.setLong(6, endNodeId);
1682
			logMetacat.debug("End node id is: " + endNodeId);
1683
			logMetacat.debug("running sql: " + pstmt.toString());
1684
			pstmt.execute();
1685
			pstmt.close();
1686
		}// try
1687
		catch (SQLException e) {
1688
			throw new SAXException("EMLSAXHandler.writeAccessSubTreeIntoDB(): "
1689
					+ e.getMessage());
1690
		}// catch
1691
		finally {
1692
			try {
1693
				pstmt.close();
1694
			} catch (SQLException ee) {
1695
				throw new SAXException("EMLSAXHandler.writeAccessSubTreeIntoDB(): "
1696
						+ ee.getMessage());
1697
			}
1698
		}// finally
1699

    
1700
	}// writeAccessSubtreeIntoDB
1701

    
1702
	/* Delete every access subtree record from xml_accesssubtree. */
1703
	private void deleteAccessSubTreeRecord(String docId) throws SAXException {
1704
		PreparedStatement pstmt = null;
1705
		try {
1706
			String sql = "DELETE FROM xml_accesssubtree WHERE docid = ?";
1707
			// delete all acl records for resources related to @aclid if any
1708
			pstmt = connection.prepareStatement(sql);
1709
			pstmt.setString(1, docId);
1710
			// Increase DBConnection usage count
1711
			connection.increaseUsageCount(1);
1712
			logMetacat.debug("running sql: " + sql);
1713
			pstmt.execute();
1714

    
1715
		} catch (SQLException e) {
1716
			throw new SAXException(e.getMessage());
1717
		} finally {
1718
			try {
1719
				pstmt.close();
1720
			} catch (SQLException ee) {
1721
				throw new SAXException(ee.getMessage());
1722
			}
1723
		}
1724
	}// deleteAccessSubTreeRecord
1725

    
1726
	// open a file writer for writing inline data to file
1727
	private Writer createInlineDataFileWriter(String fileName, String encoding) throws SAXException {
1728
		Writer writer = null;
1729
		String path;
1730
		try {
1731
			path = PropertyService.getProperty("application.inlinedatafilepath");
1732
		} catch (PropertyNotFoundException pnfe) {
1733
			throw new SAXException(pnfe.getMessage());
1734
		}
1735
		/*
1736
		 * File inlineDataDirectory = new File(path);
1737
		 */
1738
		String newFile = path + "/" + fileName;
1739
		logMetacat.debug("inline file name: " + newFile);
1740
		try {
1741
			// true means append
1742
			writer = new OutputStreamWriter(new FileOutputStream(newFile, true), encoding);
1743
		} catch (IOException ioe) {
1744
			throw new SAXException(ioe.getMessage());
1745
		}
1746
		return writer;
1747
	}
1748

    
1749
	// write inline data into file system and return file name(without path)
1750
	private void writeInlineDataIntoFile(Writer writer, StringBuffer data)
1751
			throws SAXException {
1752
		try {
1753
			writer.write(data.toString());
1754
			writer.flush();
1755
		} catch (Exception e) {
1756
			throw new SAXException(e.getMessage());
1757
		}
1758
	}
1759

    
1760

    
1761

    
1762
	// if xml file failed to upload, we need to call this method to delete
1763
	// the inline data already in file system
1764
	public void deleteInlineFiles() throws SAXException {
1765
		if (!inlineFileIdList.isEmpty()) {
1766
			for (int i = 0; i < inlineFileIdList.size(); i++) {
1767
				String fileName = inlineFileIdList.elementAt(i);
1768
				deleteInlineDataFile(fileName);
1769
			}
1770
		}
1771
	}
1772

    
1773
	/* delete the inline data file */
1774
	private void deleteInlineDataFile(String fileName) throws SAXException {
1775
		String path;
1776
		try {
1777
			path = PropertyService.getProperty("application.inlinedatafilepath");
1778
		} catch (PropertyNotFoundException pnfe) {
1779
			throw new SAXException("Could not find inline data file path: "
1780
					+ pnfe.getMessage());
1781
		}
1782
		File inlineDataDirectory = new File(path);
1783
		File newFile = new File(inlineDataDirectory, fileName);
1784
		newFile.delete();
1785

    
1786
	}
1787

    
1788
	/* Delete relations */
1789
	private void deleteRelations() throws SAXException {
1790
		PreparedStatement pStmt = null;
1791
		String sql = "DELETE FROM xml_relation where docid =?";
1792
		try {
1793
			pStmt = connection.prepareStatement(sql);
1794
			// bind variable
1795
			pStmt.setString(1, docid);
1796
			// execute query
1797
			pStmt.execute();
1798
			pStmt.close();
1799
		}// try
1800
		catch (SQLException e) {
1801
			throw new SAXException("EMLSAXHandler.deleteRelations(): " + e.getMessage());
1802
		}// catch
1803
		finally {
1804
			try {
1805
				pStmt.close();
1806
			}// try
1807
			catch (SQLException ee) {
1808
				throw new SAXException("EMLSAXHandler.deleteRelations: "
1809
						+ ee.getMessage());
1810
			}// catch
1811
		}// finally
1812
	}
1813

    
1814
	/*
1815
	 * Write an online data file id into xml_relation table. The dataId
1816
	 * shouldnot have the revision
1817
	 */
1818
	private void writeOnlineDataFileIdIntoRelationTable(String dataId)
1819
			throws SAXException {
1820
		PreparedStatement pStmt = null;
1821
		String sql = "INSERT into xml_relation (docid, packagetype, subject, "
1822
				+ "relationship, object) values (?, ?, ?, ?, ?)";
1823
		try {
1824
			pStmt = connection.prepareStatement(sql);
1825
			// bind variable
1826
			pStmt.setString(1, docid);
1827
			pStmt.setString(2, doctype); //DocumentImpl.EML2_1_0NAMESPACE);
1828
			pStmt.setString(3, docid);
1829
			pStmt.setString(4, RELATION);
1830
			pStmt.setString(5, dataId);
1831
			// execute query
1832
			pStmt.execute();
1833
			pStmt.close();
1834
		}// try
1835
		catch (SQLException e) {
1836
			throw new SAXException(
1837
					"EMLSAXHandler.writeOnlineDataFileIdIntoRelationTable(): "
1838
							+ e.getMessage());
1839
		}// catch
1840
		finally {
1841
			try {
1842
				pStmt.close();
1843
			}// try
1844
			catch (SQLException ee) {
1845
				throw new SAXException(
1846
						"EMLSAXHandler.writeOnlineDataFileIdIntoRelationTable(): "
1847
								+ ee.getMessage());
1848
			}// catch
1849
		}// finally
1850

    
1851
	}// writeOnlineDataFileIdIntoRelationTable
1852

    
1853
	/*
1854
	 * This method will handle data file in online url. If the data file is in
1855
	 * ecogrid protocol, then the datafile identifier(without rev)should be put
1856
	 * into onlineDataFileRelationVector. The docid in this vector will be
1857
	 * insert into xml_relation table in endDocument(). If the data file doesn't
1858
	 * exsit in xml_documents or xml_revision table, or the user has all
1859
	 * permission to the data file if the docid already existed, the data file
1860
	 * id (without rev)will be put into onlineDataFileTopAccessVector. The top
1861
	 * access rules specified in this eml document will apply to the data file.
1862
	 * NEED to do: We should also need to implement http and ftp. Those external
1863
	 * files should be download and assign a data file id to it.
1864
	 */
1865
	private void handleOnlineUrlDataFile(String url) throws SAXException {
1866
		logMetacat.warn("The url is " + url);
1867

    
1868
		if (currentDistributionSection == null) {
1869
			throw new SAXException("Trying to set the online file name for a null"
1870
					+ " distribution section");
1871
		}
1872

    
1873
		// if the url is not in ecogrid protocol, null will be returned
1874
		String accessionNumber = DocumentUtil.getAccessionNumberFromEcogridIdentifier(url);
1875
		if (accessionNumber == null) {
1876
			// the accession number is null if the url does not references a
1877
			// local data file (url would start with "ecogrid://"
1878
			currentDistributionSection
1879
					.setDistributionType(DistributionSection.ONLINE_DATA_DISTRIBUTION);
1880
		} else {
1881
			// handle ecogrid protocol
1882
			// get rid of revision number to get the docid.
1883
			String docid = DocumentUtil.getDocIdFromAccessionNumber(accessionNumber);
1884
			int rev = DocumentUtil.getRevisionFromAccessionNumber(accessionNumber);
1885
			String guid = null;
1886
			try {
1887
				guid = IdentifierManager.getInstance().getGUID(docid, rev);
1888
			} catch (McdbDocNotFoundException e1) {
1889
				guid = docid + "." + rev;
1890
				IdentifierManager.getInstance().createMapping(guid, guid);
1891
			}
1892

    
1893
			currentDistributionSection
1894
					.setDistributionType(DistributionSection.DATA_DISTRIBUTION);
1895
			currentDistributionSection.setDataFileName(guid);
1896

    
1897
			// distributionOnlineFileName = docid;
1898
			onlineDataFileIdInRelationVector.add(guid);
1899
			try {				
1900
				if (!AccessionNumber.accNumberUsed(docid)) {
1901
					onlineDataFileIdInTopAccessVector.add(guid);
1902
				} else {
1903
					// check the previous revision if we have it
1904
					int previousRevision = rev;
1905
					Vector<Integer> revisions = DBUtil.getRevListFromRevisionTable(docid);
1906
					if (revisions != null && revisions.size() > 0) {
1907
						previousRevision = revisions.get(revisions.size() - 1);
1908
					}
1909
					String previousDocid = 
1910
						docid + PropertyService.getProperty("document.accNumSeparator") + previousRevision;
1911
					
1912
					PermissionController controller = new PermissionController(previousDocid);				
1913
					if (controller.hasPermission(user, groups,AccessControlInterface.ALLSTRING)) {
1914
						onlineDataFileIdInTopAccessVector.add(guid);
1915
					} else {
1916
						throw new SAXException(UPDATEACCESSERROR);
1917
					}
1918
				} 
1919
			}// try
1920
			catch (Exception e) {
1921
				logMetacat.error("Eorr in "
1922
								+ "Eml210SAXHanlder.handleOnlineUrlDataFile is "
1923
								+ e.getMessage());
1924
				throw new SAXException(e.getMessage());
1925
			}
1926
		}
1927
	}
1928
}
(33-33/64)