001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 * $Id$
019 */
020
021package org.nuxeo.runtime.model.impl;
022
023import org.apache.commons.logging.Log;
024import org.apache.commons.logging.LogFactory;
025import org.nuxeo.common.xmap.XMap;
026import org.nuxeo.common.xmap.annotation.XNode;
027import org.nuxeo.common.xmap.annotation.XObject;
028import org.w3c.dom.DocumentFragment;
029import org.w3c.dom.Element;
030import org.w3c.dom.Node;
031import org.w3c.dom.ranges.DocumentRange;
032import org.w3c.dom.ranges.Range;
033
034/**
035 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
036 */
037@XObject("config")
038public class ConfigurationDescriptorImpl {
039
040    private static final Log log = LogFactory.getLog(ConfigurationDescriptorImpl.class);
041
042    private static final Object NULL = new Object();
043
044    @XNode
045    public Element element;
046
047    private Object config;
048
049    public Element getElement() {
050        return element;
051    }
052
053    public DocumentFragment getFragment() {
054        element.normalize();
055        Node node = element.getFirstChild();
056        if (node == null) {
057            return null;
058        }
059        Range range = ((DocumentRange) element.getOwnerDocument()).createRange();
060        range.setStartBefore(node);
061        range.setEndAfter(element.getLastChild());
062        return range.cloneContents();
063    }
064
065    public Object getConfiguration() {
066        if (config == null) {
067            XMap xmap = new XMap();
068            String klass = element.getAttribute("class");
069            if (klass != null) {
070                try {
071                    Class<?> cl = Thread.currentThread().getContextClassLoader().loadClass(klass);
072                    xmap.register(cl);
073                    config = xmap.load(element);
074                } catch (ClassNotFoundException e) {
075                    config = NULL;
076                    log.error(e, e);
077                }
078            } else {
079                config = NULL;
080            }
081        }
082        return config;
083    }
084
085}