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: 2013-09-10 15:17:55 -0700 (Tue, 10 Sep 2013) $'
11
 * '$Revision: 8178 $'
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.utilities.access.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, boolean writeAccessRules) throws SAXException {
195
		super(conn, action, docid, revision, user, groups, pub, serverCode, createDate,
196
				updateDate, writeAccessRules);
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
			if (writeAccessRules) {
1184
				writeAccessRuleToDB();
1185
			}
1186
			// delete relation table
1187
			deleteRelations();
1188
			// write relations
1189
			for (int i = 0; i < onlineDataFileIdInRelationVector.size(); i++) {
1190
				String id = onlineDataFileIdInRelationVector.elementAt(i);
1191
				writeOnlineDataFileIdIntoRelationTable(id);
1192
			}
1193
		}
1194
	}
1195

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

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

    
1216
			// if accessSection is not null and is not reference
1217
			if (accessSectionObj.getReferences() == null) {
1218
				// check for denyFirst permOrder
1219
				String permOrder = accessSectionObj.getPermissionOrder();
1220
				if (permOrder.equals(AccessControlInterface.DENYFIRST) && ignoreDenyFirst) {
1221
					logMetacat.warn("Metacat no longer supports EML 'denyFirst' access rules - ignoring this access block");
1222
			    	return;
1223
			    }
1224
				// write the top level access module into xml_accesssubtree to
1225
				// store info and then when update to check if the user can
1226
				// update it or not
1227
				deleteAccessSubTreeRecord(docid);
1228
				writeAccessSubTreeIntoDB(accessSectionObj, TOPLEVEL);
1229

    
1230
				// write access section into xml_access table
1231
				writeGivenAccessRuleIntoDB(accessSectionObj, top, subSectionId);
1232
				// write online data file into xml_access too.
1233
				// for (int i= 0; i <onlineDataFileIdInTopAccessVector.size();
1234
				// i++)
1235
				// {
1236
				// String id = onlineDataFileIdInTopAccessVector.elementAt(i);
1237
				// writeAccessRuleForRelatedDataFileIntoDB(accessSectionObj,
1238
				// id);
1239
				// }
1240

    
1241
			} else {
1242

    
1243
				// this is a reference and go trough the vector which contains
1244
				// all access object
1245
				String referenceId = accessSectionObj.getReferences();
1246
				boolean findAccessObject = false;
1247
				logMetacat.debug("referered id for top access: " + referenceId);
1248
				for (int i = 0; i < accessObjectList.size(); i++) {
1249
					AccessSection accessObj = accessObjectList.elementAt(i);
1250
					String accessObjId = accessObj.getSubTreeId();
1251
					// check for denyFirst permOrder
1252
					String permOrder = accessObj.getPermissionOrder();
1253
					if (permOrder.equals(AccessControlInterface.DENYFIRST) && ignoreDenyFirst) {
1254
						logMetacat.warn("Metacat no longer supports EML 'denyFirst' access rules - ignoring this access block, subtree id: " + accessObjId);
1255
				    	continue;
1256
				    }
1257
					if (referenceId != null && accessObj != null
1258
							&& referenceId.equals(accessObjId)) {
1259
						// make sure the user didn't change any thing in this
1260
						// access moduel
1261
						// too if user doesn't have all permission
1262
						if (needToCheckAccessModule) {
1263

    
1264
							Stack<NodeRecord> newStack = accessObj
1265
									.getStoredTmpNodeStack();
1266
							// revise order
1267
							newStack = DocumentUtil.reviseStack(newStack);
1268
							// go throught the vector of
1269
							// unChangeableAccessSubtreevector
1270
							// and find the one whose id is as same as
1271
							// referenceid
1272
							AccessSection oldAccessObj = getAccessSectionFromUnchangableAccessVector(referenceId);
1273
							// if oldAccessObj is null something is wrong
1274
							if (oldAccessObj == null) {
1275
								throw new SAXException(UPDATEACCESSERROR);
1276
							}// if
1277
							else {
1278
								// Get the node stack from old access obj
1279
								Stack<NodeRecord> oldStack = oldAccessObj
1280
										.getSubTreeNodeStack();
1281
								compareNodeStacks(newStack, oldStack);
1282
							}// else
1283
						}// if
1284
						// write accessobject into db
1285
						writeGivenAccessRuleIntoDB(accessObj, top, subSectionId);
1286
						// write online data file into xml_access too.
1287
						// for (int j= 0; j
1288
						// <onlineDataFileIdInTopAccessVector.size(); j++)
1289
						// {
1290
						// String id =
1291
						// onlineDataFileIdInTopAccessVector.elementAt(j);
1292
						// writeAccessRuleForRelatedDataFileIntoDB(accessSectionObj,
1293
						// id);
1294
						// }
1295

    
1296
						// write the reference access into xml_accesssubtree
1297
						// too write the top level access module into
1298
						// xml_accesssubtree to store info and then when update
1299
						// to check if the user can update it or not
1300
						deleteAccessSubTreeRecord(docid);
1301
						writeAccessSubTreeIntoDB(accessSectionObj, TOPLEVEL);
1302
						writeAccessSubTreeIntoDB(accessObj, SUBTREELEVEL);
1303
						findAccessObject = true;
1304
						break;
1305
					}
1306
				}// for
1307
				// if we couldn't find an access subtree id for this reference
1308
				// id
1309
				if (!findAccessObject) {
1310
					throw new SAXException("The referenceid: " + referenceId
1311
							+ " is not access subtree");
1312
				}// if
1313
			}// else
1314

    
1315
		}// if
1316
		else {
1317
			// couldn't find a access section object
1318
			logMetacat.warn("couldn't find access control for document: " + docid);
1319
		}
1320

    
1321
	}// writeTopLevelAccessRuletoDB
1322

    
1323
	/* Given a subtree id and find the responding access section */
1324
	private AccessSection getAccessSectionFromUnchangableAccessVector(String id) {
1325
		AccessSection result = null;
1326
		// Makse sure the id
1327
		if (id == null || id.equals("")) {
1328
			return result;
1329
		}
1330
		// go throught vector and find the list
1331
		for (int i = 0; i < unChangeableAccessSubTreeVector.size(); i++) {
1332
			AccessSection accessObj = unChangeableAccessSubTreeVector.elementAt(i);
1333
			if (accessObj.getSubTreeId() != null && (accessObj.getSubTreeId()).equals(id)) {
1334
				result = accessObj;
1335
			}// if
1336
		}// for
1337
		return result;
1338
	}// getAccessSectionFromUnchangableAccessVector
1339

    
1340
	/* Compare two node stacks to see if they are same */
1341
	private void compareNodeStacks(Stack<NodeRecord> stack1, Stack<NodeRecord> stack2)
1342
			throws SAXException {
1343
		// make sure stack1 and stack2 are not empty
1344
		if (stack1.isEmpty() || stack2.isEmpty()) {
1345
			logMetacat.error("Because stack is empty!");
1346
			throw new SAXException(UPDATEACCESSERROR);
1347
		}
1348
		// go throw two stacks and compare every element
1349
		while (!stack1.isEmpty()) {
1350
			// Pop an element from stack1
1351
			NodeRecord record1 = stack1.pop();
1352
			// Pop an element from stack2(stack 2 maybe empty)
1353
			NodeRecord record2 = null;
1354
			try {
1355
				record2 = stack2.pop();
1356
			} catch (EmptyStackException ee) {
1357
				logMetacat.error("Node stack2 is empty but stack1 isn't!");
1358
				throw new SAXException(UPDATEACCESSERROR);
1359
			}
1360
			// if two records are not same throw a exception
1361
			if (!record1.contentEquals(record2)) {
1362
				logMetacat.error("Two records from new and old stack are not " + "same!");
1363
				throw new SAXException(UPDATEACCESSERROR);
1364
			}// if
1365
		}// while
1366

    
1367
		// now stack1 is empty and we should make sure stack2 is empty too
1368
		if (!stack2.isEmpty()) {
1369
			logMetacat
1370
					.error("stack2 still has some elements while stack " + "is empty! ");
1371
			throw new SAXException(UPDATEACCESSERROR);
1372
		}// if
1373
	}// comparingNodeStacks
1374

    
1375
	/* The method to write additional access rule into db. */
1376
	private void writeAdditionalAccessRulesToDB() throws SAXException {
1377
		
1378
		// Iterate through every distribution and write access sections for data and inline
1379
		// types to the database
1380
		for (DistributionSection distributionSection : allDistributionSections) {			
1381
			// we're only interested in data and inline distributions
1382
			int distributionType = distributionSection.getDistributionType();
1383
			if (distributionType == DistributionSection.DATA_DISTRIBUTION
1384
					|| distributionType == DistributionSection.INLINE_DATA_DISTRIBUTION) {
1385
				AccessSection accessSection = distributionSection.getAccessSection();
1386
				
1387
				// If the distribution doesn't have an access section, we continue.
1388
				if (accessSection == null) {
1389
					continue;		
1390
				}
1391
				
1392
				// check for denyFirst permOrder
1393
				String permOrder = accessSection.getPermissionOrder();
1394
				if (permOrder.equals(AccessControlInterface.DENYFIRST) && ignoreDenyFirst) {
1395
					logMetacat.warn("Metacat no longer supports EML 'denyFirst' access rules - ignoring this access block: " + distributionSection.getDataFileName());
1396
			    	continue;
1397
			    }
1398
				
1399
				// We want to check file permissions for all online data updates and inserts, or for 
1400
				// inline updates.
1401
//				if (distributionType == DistributionSection.DATA_DISTRIBUTION
1402
//						|| (distributionType == DistributionSection.INLINE_DATA_DISTRIBUTION && action == "UPDATE")) {
1403

    
1404
				if (distributionType == DistributionSection.DATA_DISTRIBUTION) {
1405
					try {
1406
						// check for the previous version for permissions on update
1407
						// we need to look up the docid from the guid, if we have it
1408
						String dataDocid = distributionSection.getDataFileName();
1409
						try {
1410
							dataDocid = IdentifierManager.getInstance().getLocalId(dataDocid);
1411
						} catch (McdbDocNotFoundException mcdbnfe) {
1412
							// ignore
1413
							logMetacat.warn("Could not find guid/docid mapping for " + dataDocid);
1414
						}
1415
						String previousDocid = dataDocid;
1416
						if (action == "UPDATE") {
1417
							String docidWithoutRev = DocumentUtil.getDocIdFromString(dataDocid);
1418
							int latestRevision = DBUtil.getLatestRevisionInDocumentTable(docidWithoutRev);
1419
							if (latestRevision > 0) {
1420
								previousDocid = docidWithoutRev + PropertyService.getProperty("document.accNumSeparator") + latestRevision;
1421
							}
1422
						}
1423
						
1424
						// check both the previous and current data permissions
1425
						// see: https://projects.ecoinformatics.org/ecoinfo/issues/5647
1426
						PermissionController controller = new PermissionController(previousDocid);
1427
						PermissionController currentController = new PermissionController(dataDocid);
1428

    
1429
						if (AccessionNumber.accNumberUsed(docid)
1430
								&& 
1431
								!(controller.hasPermission(user, groups, "WRITE") 
1432
										|| currentController.hasPermission(user, groups, "WRITE")
1433
										)
1434
								) {
1435
							throw new SAXException(UPDATEACCESSERROR + " id: " + dataDocid);
1436
						}
1437
					} catch (SQLException sqle) {
1438
						throw new SAXException(
1439
								"Database error checking user permissions: "
1440
										+ sqle.getMessage());
1441
					} catch (Exception e) {
1442
						throw new SAXException(
1443
								"General error checking user permissions: "
1444
										+ e.getMessage());
1445
					}
1446
				} else if (distributionType == DistributionSection.INLINE_DATA_DISTRIBUTION && action == "UPDATE") {
1447
					try {
1448
						
1449
						// check for the previous version for permissions
1450
						int latestRevision = DBUtil.getLatestRevisionInDocumentTable(docid);
1451
						String previousDocid = 
1452
							docid + PropertyService.getProperty("document.accNumSeparator") + latestRevision;
1453
						PermissionController controller = new PermissionController(previousDocid);
1454

    
1455
						if (!controller.hasPermission(user, groups, "WRITE")) {
1456
							throw new SAXException(UPDATEACCESSERROR);
1457
						}
1458
					} catch (SQLException sqle) {
1459
						throw new SAXException(
1460
								"Database error checking user permissions: "
1461
										+ sqle.getMessage());
1462
					} catch (Exception e) {
1463
						throw new SAXException(
1464
								"General error checking user permissions: "
1465
										+ e.getMessage());
1466
					}
1467
				}
1468
				
1469
				// clear previous versions first
1470
				deleteAccessRule(accessSection, false);
1471
				
1472
				// now write the new ones
1473
				String subSectionId = Integer.toString(distributionSection.getDistributionId());
1474
				writeGivenAccessRuleIntoDB(accessSection, false, subSectionId);
1475
			}
1476

    
1477
		}
1478
		
1479
		
1480
	}
1481
	
1482
	/**
1483
	 *  delete existing access for given access rule
1484
	 *  
1485
	 */
1486
	private void deleteAccessRule(AccessSection accessSection, boolean topLevel) throws SAXException {
1487
		
1488
		if (accessSection == null) {
1489
			throw new SAXException("The access object is null");
1490
		}
1491
		
1492
		PreparedStatement pstmt = null;
1493

    
1494
		String sql = null;
1495
		sql = "DELETE FROM xml_access WHERE guid = ?";
1496
			
1497
		try {
1498

    
1499
			pstmt = connection.prepareStatement(sql);
1500
			// Increase DBConnection usage count
1501
			connection.increaseUsageCount(1);
1502
			// Bind the values to the query
1503
			String guid = null;
1504
			if (topLevel) {
1505
				try {
1506
					guid = IdentifierManager.getInstance().getGUID(docid, Integer.valueOf(revision));
1507
				} catch (NumberFormatException e) {
1508
					throw new SAXException(e.getMessage(), e);
1509
				} catch (McdbDocNotFoundException e) {
1510
					// register the default mapping now
1511
					guid = docid + "." + revision;
1512
					IdentifierManager.getInstance().createMapping(guid, guid);
1513
				}
1514
			} else {
1515
				guid = accessSection.getDataFileName();
1516
				
1517
			}
1518
			pstmt.setString(1, guid);
1519
			logMetacat.debug("guid in accesstable: " + guid);
1520
			
1521
			logMetacat.debug("running sql: " + pstmt.toString());
1522
			pstmt.execute();
1523
			
1524
			pstmt.close();
1525
		}// try
1526
		catch (SQLException e) {
1527
			throw new SAXException("EMLSAXHandler.deleteAccessRule(): "
1528
					+ e.getMessage());
1529
		}// catch
1530
		finally {
1531
			try {
1532
				pstmt.close();
1533
			} catch (SQLException ee) {
1534
				throw new SAXException("EMLSAXHandler.deleteAccessRule(): "
1535
						+ ee.getMessage());
1536
			}
1537
		}// finally
1538

    
1539
	}
1540

    
1541
	/* Write a given access rule into db */
1542
	private void writeGivenAccessRuleIntoDB(AccessSection accessSection,
1543
			boolean topLevel, String subSectionId) throws SAXException {
1544
		if (accessSection == null) {
1545
			throw new SAXException("The access object is null");
1546
		}
1547

    
1548
		String guid = null;
1549
		String referencedGuid = accessSection.getDataFileName();
1550

    
1551
		try {
1552
			guid = IdentifierManager.getInstance().getGUID(docid, Integer.valueOf(revision));
1553
		} catch (NumberFormatException e) {
1554
			throw new SAXException(e.getMessage(), e);
1555
		} catch (McdbDocNotFoundException e) {
1556
			// register the default mapping now
1557
			guid = docid + "." + revision;
1558
			IdentifierManager.getInstance().createMapping(guid, guid);
1559
		}
1560
		
1561
		String permOrder = accessSection.getPermissionOrder();
1562
		String sql = null;
1563
		PreparedStatement pstmt = null;
1564
		if (topLevel) {
1565
			sql = "INSERT INTO xml_access (guid, principal_name, permission, "
1566
					+ "perm_type, perm_order, accessfileid) VALUES "
1567
					+ " (?, ?, ?, ?, ?, ?)";
1568
		} else {
1569
			sql = "INSERT INTO xml_access (guid,principal_name, "
1570
					+ "permission, perm_type, perm_order, accessfileid, subtreeid"
1571
					+ ") VALUES" + " (?, ?, ?, ?, ?, ?, ?)";
1572
		}
1573
		try {
1574

    
1575
			pstmt = connection.prepareStatement(sql);
1576
			// Increase DBConnection usage count
1577
			connection.increaseUsageCount(1);
1578
			// Bind the values to the query
1579
			pstmt.setString(6, guid);
1580
			logMetacat.debug("Accessfileid in accesstable: " + guid);
1581
			pstmt.setString(5, permOrder);
1582
			logMetacat.debug("PermOder in accesstable: " + permOrder);
1583
			// if it is not top level, set subsection id
1584
			if (topLevel) {
1585
				pstmt.setString(1, guid);
1586
				logMetacat.debug("Guid in accesstable: " + guid);
1587
			}
1588
			if (!topLevel) {
1589
				// use the referenced guid
1590
				pstmt.setString(1, referencedGuid );
1591
				logMetacat.debug("Docid in accesstable: " + inlineDataFileName);
1592

    
1593
				// for subtree should specify the
1594
				if (subSectionId == null) {
1595
					throw new SAXException("The subsection is null");
1596
				}
1597

    
1598
				pstmt.setString(7, subSectionId);
1599
				logMetacat.debug("SubSectionId in accesstable: " + subSectionId);
1600
			}
1601

    
1602
			Vector<AccessRule> accessRules = accessSection.getAccessRules();
1603
			// go through every rule
1604
			for (int i = 0; i < accessRules.size(); i++) {
1605
				AccessRule rule = accessRules.elementAt(i);
1606
				String permType = rule.getPermissionType();
1607
				int permission = rule.getPermission();
1608
				pstmt.setInt(3, permission);
1609
				logMetacat.debug("permission in accesstable: " + permission);
1610
				pstmt.setString(4, permType);
1611
				logMetacat.debug("Permtype in accesstable: " + permType);
1612
				// go through every principle in rule
1613
				Vector<String> nameVector = rule.getPrincipal();
1614
				for (int j = 0; j < nameVector.size(); j++) {
1615
					String prName = nameVector.elementAt(j);
1616
					pstmt.setString(2, prName);
1617
					logMetacat.debug("Principal in accesstable: " + prName);
1618
					logMetacat.debug("running sql: " + pstmt.toString());
1619
					pstmt.execute();
1620
				}// for
1621
			}// for
1622
			pstmt.close();
1623
		}// try
1624
		catch (SQLException e) {
1625
			throw new SAXException("EMLSAXHandler.writeAccessRuletoDB(): "
1626
					+ e.getMessage());
1627
		}// catch
1628
		finally {
1629
			try {
1630
				pstmt.close();
1631
			} catch (SQLException ee) {
1632
				throw new SAXException("EMLSAXHandler.writeAccessRuletoDB(): "
1633
						+ ee.getMessage());
1634
			}
1635
		}// finally
1636
		
1637
		// for D1, refresh the entries
1638
		HazelcastService.getInstance().refreshSystemMetadataEntry(guid);
1639
		HazelcastService.getInstance().refreshSystemMetadataEntry(referencedGuid);
1640
		
1641

    
1642
	}// writeGivenAccessRuleIntoDB
1643

    
1644
	/* Delete from db all permission for resources related to the document, if any */
1645
	private void deletePermissionsInAccessTable() throws SAXException {
1646
		PreparedStatement pstmt = null;
1647
		try {
1648
			
1649
			String sql = "DELETE FROM xml_access " +
1650
					// the file defines access for another file
1651
					"WHERE accessfileid IN " +
1652
						"(SELECT guid from identifier where docid = ? and rev = ?) " +
1653
					// the described file has other versions describing it	
1654
					"OR guid IN " +
1655
						"(SELECT xa.guid from xml_access xa, identifier id" +
1656
						" WHERE xa.accessfileid = id.guid " +
1657
						" AND id.docid = ?" +
1658
						" AND id.rev = ?)";
1659
			// delete all acl records for resources related to @aclid if any
1660
			pstmt = connection.prepareStatement(sql);
1661
			pstmt.setString(1, docid);
1662
			pstmt.setInt(2, Integer.valueOf(revision));
1663
			// second part of query
1664
			pstmt.setString(3, docid);
1665
			pstmt.setInt(4, Integer.valueOf(revision));
1666
			// Increase DBConnection usage count
1667
			connection.increaseUsageCount(1);
1668
			logMetacat.debug("running sql: " + sql);
1669
			pstmt.execute();
1670

    
1671
		} catch (SQLException e) {
1672
			throw new SAXException(e.getMessage());
1673
		} finally {
1674
			try {
1675
				pstmt.close();
1676
			} catch (SQLException ee) {
1677
				throw new SAXException(ee.getMessage());
1678
			}
1679
		}
1680
	}// deletePermissionsInAccessTable
1681

    
1682
	/*
1683
	 * In order to make sure only usr has "all" permission can update access
1684
	 * subtree in eml document we need to keep access subtree info in
1685
	 * xml_accesssubtree table, such as docid, version, startnodeid, endnodeid
1686
	 */
1687
	private void writeAccessSubTreeIntoDB(AccessSection accessSection, String level)
1688
			throws SAXException {
1689
		if (accessSection == null) {
1690
			throw new SAXException("The access object is null");
1691
		}
1692

    
1693
		String sql = null;
1694
		PreparedStatement pstmt = null;
1695
		sql = "INSERT INTO xml_accesssubtree (docid, rev, controllevel, "
1696
				+ "subtreeid, startnodeid, endnodeid) VALUES " + " (?, ?, ?, ?, ?, ?)";
1697
		try {
1698

    
1699
			pstmt = connection.prepareStatement(sql);
1700
			// Increase DBConnection usage count
1701
			connection.increaseUsageCount(1);
1702
			long startNodeId = accessSection.getStartNodeId();
1703
			long endNodeId = accessSection.getEndNodeId();
1704
			String sectionId = accessSection.getSubTreeId();
1705
			// Bind the values to the query
1706
			pstmt.setString(1, docid);
1707
			logMetacat.debug("Docid in access-subtreetable: " + docid);
1708
			pstmt.setLong(2, (new Long(revision)).longValue());
1709
			logMetacat.debug("rev in accesssubtreetable: " + revision);
1710
			pstmt.setString(3, level);
1711
			logMetacat.debug("contorl level in access-subtree table: " + level);
1712
			pstmt.setString(4, sectionId);
1713
			logMetacat.debug("Subtree id in access-subtree table: " + sectionId);
1714
			pstmt.setLong(5, startNodeId);
1715
			logMetacat.debug("Start node id is: " + startNodeId);
1716
			pstmt.setLong(6, endNodeId);
1717
			logMetacat.debug("End node id is: " + endNodeId);
1718
			logMetacat.debug("running sql: " + pstmt.toString());
1719
			pstmt.execute();
1720
			pstmt.close();
1721
		}// try
1722
		catch (SQLException e) {
1723
			throw new SAXException("EMLSAXHandler.writeAccessSubTreeIntoDB(): "
1724
					+ e.getMessage());
1725
		}// catch
1726
		finally {
1727
			try {
1728
				pstmt.close();
1729
			} catch (SQLException ee) {
1730
				throw new SAXException("EMLSAXHandler.writeAccessSubTreeIntoDB(): "
1731
						+ ee.getMessage());
1732
			}
1733
		}// finally
1734

    
1735
	}// writeAccessSubtreeIntoDB
1736

    
1737
	/* Delete every access subtree record from xml_accesssubtree. */
1738
	private void deleteAccessSubTreeRecord(String docId) throws SAXException {
1739
		PreparedStatement pstmt = null;
1740
		try {
1741
			String sql = "DELETE FROM xml_accesssubtree WHERE docid = ?";
1742
			// delete all acl records for resources related to @aclid if any
1743
			pstmt = connection.prepareStatement(sql);
1744
			pstmt.setString(1, docId);
1745
			// Increase DBConnection usage count
1746
			connection.increaseUsageCount(1);
1747
			logMetacat.debug("running sql: " + sql);
1748
			pstmt.execute();
1749

    
1750
		} catch (SQLException e) {
1751
			throw new SAXException(e.getMessage());
1752
		} finally {
1753
			try {
1754
				pstmt.close();
1755
			} catch (SQLException ee) {
1756
				throw new SAXException(ee.getMessage());
1757
			}
1758
		}
1759
	}// deleteAccessSubTreeRecord
1760

    
1761
	// open a file writer for writing inline data to file
1762
	private Writer createInlineDataFileWriter(String fileName, String encoding) throws SAXException {
1763
		Writer writer = null;
1764
		String path;
1765
		try {
1766
			path = PropertyService.getProperty("application.inlinedatafilepath");
1767
		} catch (PropertyNotFoundException pnfe) {
1768
			throw new SAXException(pnfe.getMessage());
1769
		}
1770
		/*
1771
		 * File inlineDataDirectory = new File(path);
1772
		 */
1773
		String newFile = path + "/" + fileName;
1774
		logMetacat.debug("inline file name: " + newFile);
1775
		try {
1776
			// true means append
1777
			writer = new OutputStreamWriter(new FileOutputStream(newFile, true), encoding);
1778
		} catch (IOException ioe) {
1779
			throw new SAXException(ioe.getMessage());
1780
		}
1781
		return writer;
1782
	}
1783

    
1784
	// write inline data into file system and return file name(without path)
1785
	private void writeInlineDataIntoFile(Writer writer, StringBuffer data)
1786
			throws SAXException {
1787
		try {
1788
			writer.write(data.toString());
1789
			writer.flush();
1790
		} catch (Exception e) {
1791
			throw new SAXException(e.getMessage());
1792
		}
1793
	}
1794

    
1795

    
1796

    
1797
	// if xml file failed to upload, we need to call this method to delete
1798
	// the inline data already in file system
1799
	public void deleteInlineFiles() throws SAXException {
1800
		if (!inlineFileIdList.isEmpty()) {
1801
			for (int i = 0; i < inlineFileIdList.size(); i++) {
1802
				String fileName = inlineFileIdList.elementAt(i);
1803
				deleteInlineDataFile(fileName);
1804
			}
1805
		}
1806
	}
1807

    
1808
	/* delete the inline data file */
1809
	private void deleteInlineDataFile(String fileName) throws SAXException {
1810
		String path;
1811
		try {
1812
			path = PropertyService.getProperty("application.inlinedatafilepath");
1813
		} catch (PropertyNotFoundException pnfe) {
1814
			throw new SAXException("Could not find inline data file path: "
1815
					+ pnfe.getMessage());
1816
		}
1817
		File inlineDataDirectory = new File(path);
1818
		File newFile = new File(inlineDataDirectory, fileName);
1819
		newFile.delete();
1820

    
1821
	}
1822

    
1823
	/* Delete relations */
1824
	private void deleteRelations() throws SAXException {
1825
		PreparedStatement pStmt = null;
1826
		String sql = "DELETE FROM xml_relation where docid =?";
1827
		try {
1828
			pStmt = connection.prepareStatement(sql);
1829
			// bind variable
1830
			pStmt.setString(1, docid);
1831
			// execute query
1832
			pStmt.execute();
1833
			pStmt.close();
1834
		}// try
1835
		catch (SQLException e) {
1836
			throw new SAXException("EMLSAXHandler.deleteRelations(): " + e.getMessage());
1837
		}// catch
1838
		finally {
1839
			try {
1840
				pStmt.close();
1841
			}// try
1842
			catch (SQLException ee) {
1843
				throw new SAXException("EMLSAXHandler.deleteRelations: "
1844
						+ ee.getMessage());
1845
			}// catch
1846
		}// finally
1847
	}
1848

    
1849
	/*
1850
	 * Write an online data file id into xml_relation table. The dataId
1851
	 * shouldnot have the revision
1852
	 */
1853
	private void writeOnlineDataFileIdIntoRelationTable(String dataId)
1854
			throws SAXException {
1855
		PreparedStatement pStmt = null;
1856
		String sql = "INSERT into xml_relation (docid, packagetype, subject, "
1857
				+ "relationship, object) values (?, ?, ?, ?, ?)";
1858
		try {
1859
			pStmt = connection.prepareStatement(sql);
1860
			// bind variable
1861
			pStmt.setString(1, docid);
1862
			pStmt.setString(2, doctype); //DocumentImpl.EML2_1_0NAMESPACE);
1863
			pStmt.setString(3, docid);
1864
			pStmt.setString(4, RELATION);
1865
			pStmt.setString(5, dataId);
1866
			// execute query
1867
			pStmt.execute();
1868
			pStmt.close();
1869
		}// try
1870
		catch (SQLException e) {
1871
			throw new SAXException(
1872
					"EMLSAXHandler.writeOnlineDataFileIdIntoRelationTable(): "
1873
							+ e.getMessage());
1874
		}// catch
1875
		finally {
1876
			try {
1877
				pStmt.close();
1878
			}// try
1879
			catch (SQLException ee) {
1880
				throw new SAXException(
1881
						"EMLSAXHandler.writeOnlineDataFileIdIntoRelationTable(): "
1882
								+ ee.getMessage());
1883
			}// catch
1884
		}// finally
1885

    
1886
	}// writeOnlineDataFileIdIntoRelationTable
1887

    
1888
	/*
1889
	 * This method will handle data file in online url. If the data file is in
1890
	 * ecogrid protocol, then the datafile identifier(without rev)should be put
1891
	 * into onlineDataFileRelationVector. The docid in this vector will be
1892
	 * insert into xml_relation table in endDocument(). If the data file doesn't
1893
	 * exsit in xml_documents or xml_revision table, or the user has all
1894
	 * permission to the data file if the docid already existed, the data file
1895
	 * id (without rev)will be put into onlineDataFileTopAccessVector. The top
1896
	 * access rules specified in this eml document will apply to the data file.
1897
	 * NEED to do: We should also need to implement http and ftp. Those external
1898
	 * files should be download and assign a data file id to it.
1899
	 */
1900
	private void handleOnlineUrlDataFile(String url) throws SAXException {
1901
		logMetacat.warn("The url is " + url);
1902

    
1903
		if (currentDistributionSection == null) {
1904
			throw new SAXException("Trying to set the online file name for a null"
1905
					+ " distribution section");
1906
		}
1907

    
1908
		// if the url is not in ecogrid protocol, null will be returned
1909
		String accessionNumber = DocumentUtil.getAccessionNumberFromEcogridIdentifier(url);
1910
		
1911
		// check he accession number and get docid.rev if we can
1912
		String docid = null;
1913
		int rev = 0;
1914
		if (accessionNumber != null) {
1915
			// get rid of revision number to get the docid.
1916
			try {
1917
				docid = DocumentUtil.getDocIdFromAccessionNumber(accessionNumber);
1918
				rev = DocumentUtil.getRevisionFromAccessionNumber(accessionNumber);
1919
			} catch (Exception e) {
1920
				logMetacat.warn(e.getClass().getName() + " - Problem parsing accession number for: " + accessionNumber + ". Message: " + e.getMessage());
1921
				accessionNumber = null;
1922
			}
1923
		}
1924
		
1925
		if (accessionNumber == null) {
1926
			// the accession number is null if the url does not references a
1927
			// local data file (url would start with "ecogrid://"
1928
			currentDistributionSection
1929
					.setDistributionType(DistributionSection.ONLINE_DATA_DISTRIBUTION);
1930
		} else {
1931
			// look up the guid using docid/rev
1932
			String guid = null;
1933
			try {
1934
				guid = IdentifierManager.getInstance().getGUID(docid, rev);
1935
			} catch (McdbDocNotFoundException e1) {
1936
				// no need to do this if we are not writing access rules for the data
1937
				if (!writeAccessRules) {
1938
					logMetacat.warn("Not configured to write access rules for data referenced by: " + url);
1939
					return;
1940
				}
1941
				guid = docid + "." + rev;
1942
				IdentifierManager.getInstance().createMapping(guid, guid);
1943
			}
1944

    
1945
			currentDistributionSection
1946
					.setDistributionType(DistributionSection.DATA_DISTRIBUTION);
1947
			currentDistributionSection.setDataFileName(guid);
1948

    
1949
			// distributionOnlineFileName = docid;
1950
			onlineDataFileIdInRelationVector.add(guid);
1951
			try {				
1952
				if (!AccessionNumber.accNumberUsed(docid)) {
1953
					onlineDataFileIdInTopAccessVector.add(guid);
1954
				} else {
1955
					// check the previous revision if we have it
1956
					int previousRevision = rev;
1957
					Vector<Integer> revisions = DBUtil.getRevListFromRevisionTable(docid);
1958
					if (revisions != null && revisions.size() > 0) {
1959
						previousRevision = revisions.get(revisions.size() - 1);
1960
					}
1961
					String previousDocid = 
1962
						docid + PropertyService.getProperty("document.accNumSeparator") + previousRevision;
1963

    
1964
					// check EITHER previous or current id for access rules
1965
					// see: https://projects.ecoinformatics.org/ecoinfo/issues/5647
1966
					PermissionController previousController = new PermissionController(previousDocid);
1967
					PermissionController currentController = new PermissionController(accessionNumber);				
1968
					if (previousController.hasPermission(user, groups, AccessControlInterface.ALLSTRING)
1969
							|| currentController.hasPermission(user, groups, AccessControlInterface.ALLSTRING)
1970
							) {
1971
						onlineDataFileIdInTopAccessVector.add(guid);
1972
					} else {
1973
						throw new SAXException(UPDATEACCESSERROR);
1974
					}
1975
				} 
1976
			}// try
1977
			catch (Exception e) {
1978
				logMetacat.error("Eorr in "
1979
								+ "Eml210SAXHanlder.handleOnlineUrlDataFile is "
1980
								+ e.getMessage());
1981
				throw new SAXException(e.getMessage());
1982
			}
1983
		}
1984
	}
1985
}
(32-32/63)