001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.component.jcr;
018
019 import javax.jcr.Node;
020 import javax.jcr.RepositoryException;
021 import javax.jcr.Session;
022 import javax.jcr.Value;
023
024 import org.apache.camel.Exchange;
025 import org.apache.camel.TypeConverter;
026 import org.apache.camel.impl.DefaultProducer;
027
028 public class JcrProducer extends DefaultProducer {
029
030 public JcrProducer(JcrEndpoint jcrEndpoint) throws RepositoryException {
031 super(jcrEndpoint);
032 }
033
034 public void process(Exchange exchange) throws Exception {
035 Session session = openSession();
036 try {
037 Node base = getBaseNode(session);
038 Node node = base.addNode(getNodeName(exchange));
039 TypeConverter converter = exchange.getContext().getTypeConverter();
040 for (String key : exchange.getProperties().keySet()) {
041 Value value = converter.convertTo(Value.class,
042 exchange, exchange.getProperty(key));
043 node.setProperty(key, value);
044 }
045 node.addMixin("mix:referenceable");
046 session.save();
047 exchange.getOut().setBody(node.getUUID());
048 } finally {
049 if (session != null && session.isLive()) {
050 session.logout();
051 }
052 }
053 }
054
055 private String getNodeName(Exchange exchange) {
056 if (exchange.getProperty(JcrConstants.JCR_NODE_NAME) != null) {
057 return exchange.getProperty(JcrConstants.JCR_NODE_NAME, String.class);
058 }
059 return exchange.getExchangeId();
060 }
061
062 private Node getBaseNode(Session session) throws Exception {
063 Node baseNode = session.getRootNode();
064 for (String node : getJcrEndpoint().getBase().split("/")) {
065 baseNode = baseNode.addNode(node);
066 }
067 return baseNode;
068 }
069
070 protected Session openSession() throws RepositoryException {
071 return getJcrEndpoint().getRepository().login(getJcrEndpoint().getCredentials());
072 }
073
074 private JcrEndpoint getJcrEndpoint() {
075 JcrEndpoint endpoint = (JcrEndpoint) getEndpoint();
076 return endpoint;
077 }
078 }