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: 2012-04-09 15:18:39 -0700 (Mon, 09 Apr 2012) $'
11
 * '$Revision: 7128 $'
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, 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
				// write the top level access module into xml_accesssubtree to
1219
				// store info and then when update to check if the user can
1220
				// update it or not
1221
				deleteAccessSubTreeRecord(docid);
1222
				writeAccessSubTreeIntoDB(accessSectionObj, TOPLEVEL);
1223

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

    
1235
			} else {
1236

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

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

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

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

    
1309
	}// writeTopLevelAccessRuletoDB
1310

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

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

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

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

    
1385
				if (distributionType == DistributionSection.DATA_DISTRIBUTION) {
1386
					try {
1387
						// check for the previous version for permissions on update
1388
						String dataDocid = distributionSection.getDataFileName();
1389
						String previousDocid = dataDocid;
1390
						if (action == "UPDATE") {
1391
							String docidWithoutRev = DocumentUtil.getDocIdFromString(dataDocid);
1392
							int latestRevision = DBUtil.getLatestRevisionInDocumentTable(docidWithoutRev);
1393
							if (latestRevision > 0) {
1394
								previousDocid = docidWithoutRev + PropertyService.getProperty("document.accNumSeparator") + latestRevision;
1395
							}
1396
						}
1397
						
1398
						PermissionController controller = new PermissionController(previousDocid);
1399
						
1400
						if (AccessionNumber.accNumberUsed(docid)
1401
								&& !controller.hasPermission(user, groups, "WRITE")) {
1402
							throw new SAXException(UPDATEACCESSERROR);
1403
						}
1404
					} catch (SQLException sqle) {
1405
						throw new SAXException(
1406
								"Database error checking user permissions: "
1407
										+ sqle.getMessage());
1408
					} catch (Exception e) {
1409
						throw new SAXException(
1410
								"General error checking user permissions: "
1411
										+ e.getMessage());
1412
					}
1413
				} else if (distributionType == DistributionSection.INLINE_DATA_DISTRIBUTION && action == "UPDATE") {
1414
					try {
1415
						
1416
						// check for the previous version for permissions
1417
						int latestRevision = DBUtil.getLatestRevisionInDocumentTable(docid);
1418
						String previousDocid = 
1419
							docid + PropertyService.getProperty("document.accNumSeparator") + latestRevision;
1420
						PermissionController controller = new PermissionController(previousDocid);
1421

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

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

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

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

    
1506
	}
1507

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

    
1515
		String guid = null;
1516
		String referencedGuid = accessSection.getDataFileName();
1517

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

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

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

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

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

    
1609
	}// writeGivenAccessRuleIntoDB
1610

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

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

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

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

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

    
1702
	}// writeAccessSubtreeIntoDB
1703

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

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

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

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

    
1762

    
1763

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

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

    
1788
	}
1789

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

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

    
1853
	}// writeOnlineDataFileIdIntoRelationTable
1854

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

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

    
1875
		// if the url is not in ecogrid protocol, null will be returned
1876
		String accessionNumber = DocumentUtil.getAccessionNumberFromEcogridIdentifier(url);
1877
		
1878
		// check he accession number and get docid.rev if we can
1879
		String docid = null;
1880
		int rev = 0;
1881
		if (accessionNumber != null) {
1882
			// get rid of revision number to get the docid.
1883
			try {
1884
				docid = DocumentUtil.getDocIdFromAccessionNumber(accessionNumber);
1885
				rev = DocumentUtil.getRevisionFromAccessionNumber(accessionNumber);
1886
			} catch (Exception e) {
1887
				logMetacat.warn(e.getClass().getName() + " - Problem parsing accession number for: " + accessionNumber + ". Message: " + e.getMessage());
1888
				accessionNumber = null;
1889
			}
1890
		}
1891
		
1892
		if (accessionNumber == null) {
1893
			// the accession number is null if the url does not references a
1894
			// local data file (url would start with "ecogrid://"
1895
			currentDistributionSection
1896
					.setDistributionType(DistributionSection.ONLINE_DATA_DISTRIBUTION);
1897
		} else {
1898
			// look up the guid using docid/rev
1899
			String guid = null;
1900
			try {
1901
				guid = IdentifierManager.getInstance().getGUID(docid, rev);
1902
			} catch (McdbDocNotFoundException e1) {
1903
				guid = docid + "." + rev;
1904
				IdentifierManager.getInstance().createMapping(guid, guid);
1905
			}
1906

    
1907
			currentDistributionSection
1908
					.setDistributionType(DistributionSection.DATA_DISTRIBUTION);
1909
			currentDistributionSection.setDataFileName(guid);
1910

    
1911
			// distributionOnlineFileName = docid;
1912
			onlineDataFileIdInRelationVector.add(guid);
1913
			try {				
1914
				if (!AccessionNumber.accNumberUsed(docid)) {
1915
					onlineDataFileIdInTopAccessVector.add(guid);
1916
				} else {
1917
					// check the previous revision if we have it
1918
					int previousRevision = rev;
1919
					Vector<Integer> revisions = DBUtil.getRevListFromRevisionTable(docid);
1920
					if (revisions != null && revisions.size() > 0) {
1921
						previousRevision = revisions.get(revisions.size() - 1);
1922
					}
1923
					String previousDocid = 
1924
						docid + PropertyService.getProperty("document.accNumSeparator") + previousRevision;
1925
					
1926
					PermissionController controller = new PermissionController(previousDocid);				
1927
					if (controller.hasPermission(user, groups,AccessControlInterface.ALLSTRING)) {
1928
						onlineDataFileIdInTopAccessVector.add(guid);
1929
					} else {
1930
						throw new SAXException(UPDATEACCESSERROR);
1931
					}
1932
				} 
1933
			}// try
1934
			catch (Exception e) {
1935
				logMetacat.error("Eorr in "
1936
								+ "Eml210SAXHanlder.handleOnlineUrlDataFile is "
1937
								+ e.getMessage());
1938
				throw new SAXException(e.getMessage());
1939
			}
1940
		}
1941
	}
1942
}
(33-33/64)