View Javadoc
1   /*
2    * Copyright (C) 2007-2012 Argeo GmbH
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *         http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.argeo.slc.jcr;
17  
18  import java.util.HashMap;
19  import java.util.Map;
20  
21  import javax.jcr.Node;
22  import javax.jcr.RepositoryException;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.argeo.jcr.JcrUtils;
27  import org.argeo.slc.SlcException;
28  import org.argeo.slc.SlcNames;
29  
30  /**
31   * Writes arbitrary metadata into a child node of a given node (or the node
32   * itself if metadata node name is set to null)
33   */
34  public class JcrMetadataWriter implements Runnable {
35  	private final static Log log = LogFactory.getLog(JcrMetadataWriter.class);
36  
37  	private Node baseNode;
38  	private String metadataNodeName = SlcNames.SLC_METADATA;
39  
40  	private Map<String, String> metadata = new HashMap<String, String>();
41  
42  	public void run() {
43  		try {
44  			Node metadataNode;
45  			if (metadataNodeName != null)
46  				metadataNode = baseNode.hasNode(metadataNodeName) ? baseNode
47  						.getNode(metadataNodeName) : baseNode
48  						.addNode(metadataNodeName);
49  			else
50  				metadataNode = baseNode;
51  
52  			for (String key : metadata.keySet())
53  				metadataNode.setProperty(key, metadata.get(key));
54  
55  			baseNode.getSession().save();
56  
57  			if (log.isDebugEnabled())
58  				log.debug("Wrote " + metadata.size() + " metadata entries to "
59  						+ metadataNode);
60  		} catch (RepositoryException e) {
61  			throw new SlcException("Cannot write metadata to " + baseNode, e);
62  		} finally {
63  			JcrUtils.discardUnderlyingSessionQuietly(baseNode);
64  		}
65  
66  	}
67  
68  	public void setBaseNode(Node baseNode) {
69  		this.baseNode = baseNode;
70  	}
71  
72  	public void setMetadataNodeName(String metadataNodeName) {
73  		this.metadataNodeName = metadataNodeName;
74  	}
75  
76  	public void setMetadata(Map<String, String> metadata) {
77  		this.metadata = metadata;
78  	}
79  
80  }