001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Nuxeo - initial API and implementation
011 * $Id$
012 */
013
014package org.nuxeo.runtime.model.impl;
015
016import org.apache.commons.logging.Log;
017import org.apache.commons.logging.LogFactory;
018import org.nuxeo.common.xmap.XMap;
019import org.nuxeo.common.xmap.annotation.XNode;
020import org.nuxeo.common.xmap.annotation.XObject;
021import org.w3c.dom.DocumentFragment;
022import org.w3c.dom.Element;
023import org.w3c.dom.Node;
024import org.w3c.dom.ranges.DocumentRange;
025import org.w3c.dom.ranges.Range;
026
027/**
028 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
029 */
030@XObject("config")
031public class ConfigurationDescriptorImpl {
032
033    private static final Log log = LogFactory.getLog(ConfigurationDescriptorImpl.class);
034
035    private static final Object NULL = new Object();
036
037    @XNode
038    public Element element;
039
040    private Object config;
041
042    public Element getElement() {
043        return element;
044    }
045
046    public DocumentFragment getFragment() {
047        element.normalize();
048        Node node = element.getFirstChild();
049        if (node == null) {
050            return null;
051        }
052        Range range = ((DocumentRange) element.getOwnerDocument()).createRange();
053        range.setStartBefore(node);
054        range.setEndAfter(element.getLastChild());
055        return range.cloneContents();
056    }
057
058    public Object getConfiguration() {
059        if (config == null) {
060            XMap xmap = new XMap();
061            String klass = element.getAttribute("class");
062            if (klass != null) {
063                try {
064                    Class cl = Thread.currentThread().getContextClassLoader().loadClass(klass);
065                    xmap.register(cl);
066                    config = xmap.load(element);
067                } catch (ClassNotFoundException e) {
068                    config = NULL;
069                    log.error(e, e);
070                }
071            } else {
072                config = NULL;
073            }
074        }
075        return config;
076    }
077
078}