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.LoginException;
020 import javax.jcr.Node;
021 import javax.jcr.RepositoryException;
022 import javax.jcr.Session;
023 import javax.jcr.Value;
024
025 import org.apache.camel.Exchange;
026 import org.apache.camel.TypeConverter;
027 import org.apache.camel.impl.DefaultExchange;
028 import org.apache.camel.impl.DefaultProducer;
029
030 public class JcrProducer extends DefaultProducer<DefaultExchange> {
031
032 public JcrProducer(JcrEndpoint jcrEndpoint) throws LoginException,
033 RepositoryException {
034 super(jcrEndpoint);
035 }
036
037 public void process(Exchange exchange) throws Exception {
038 Session session = openSession();
039 try {
040 Node base = getBaseNode(session);
041 Node node = base.addNode(getNodeName(exchange));
042 TypeConverter converter = exchange.getContext().getTypeConverter();
043 for (String key : exchange.getProperties().keySet()) {
044 Value value = converter.convertTo(Value.class,
045 exchange, exchange.getProperty(key));
046 node.setProperty(key, value);
047 }
048 node.addMixin("mix:referenceable");
049 session.save();
050 exchange.getOut().setBody(node.getUUID());
051 } finally {
052 if (session != null && session.isLive()) {
053 session.logout();
054 }
055 }
056 }
057
058 private String getNodeName(Exchange exchange) {
059 if (exchange.getProperty(JcrComponent.NODE_NAME) != null) {
060 return exchange.getProperty(JcrComponent.NODE_NAME).toString();
061 }
062 return exchange.getExchangeId();
063 }
064
065 private Node getBaseNode(Session session) throws Exception {
066 Node baseNode = session.getRootNode();
067 for (String node : getJcrEndpoint().getBase().split("/")) {
068 baseNode = baseNode.addNode(node);
069 }
070 return baseNode;
071 }
072
073 protected Session openSession() throws LoginException, RepositoryException {
074 return getJcrEndpoint().getRepository().login(getJcrEndpoint().getCredentials());
075 }
076
077 private JcrEndpoint getJcrEndpoint() {
078 JcrEndpoint endpoint = (JcrEndpoint) getEndpoint();
079 return endpoint;
080 }
081 }