001/*
002 * Copyright (c) 2006-2012 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 *     Bogdan Stefanescu
011 *     Florent Guillaume
012 */
013package org.nuxeo.ecm.core.schema.types;
014
015import java.util.HashMap;
016import java.util.Map;
017import java.util.Set;
018
019import org.nuxeo.ecm.core.schema.Namespace;
020import org.nuxeo.ecm.core.schema.SchemaNames;
021import org.nuxeo.ecm.core.schema.types.constraints.Constraint;
022
023/**
024 * The implementation of a Schema
025 */
026public class SchemaImpl extends ComplexTypeImpl implements Schema {
027
028    private static final long serialVersionUID = 1L;
029
030    private final Map<String, Type> types = new HashMap<String, Type>();
031
032    /**
033     * Constructor for a schema. Its types (fields) are then added through {@link #registerType}.
034     */
035    public SchemaImpl(String name, Namespace ns) {
036        super(null, SchemaNames.SCHEMAS, name, ns == null ? Namespace.DEFAULT_NS : ns);
037    }
038
039    /**
040     * Create a schema from a ComplexType
041     *
042     * @since 5.7
043     * @param complexType
044     * @param name
045     * @param ns
046     */
047    public SchemaImpl(ComplexType complexType, String name, Namespace ns) {
048        super(null, SchemaNames.SCHEMAS, name, ns == null ? Namespace.DEFAULT_NS : ns);
049        if (complexType != null) {
050            for (Field field : complexType.getFields()) {
051                QName fieldname = QName.valueOf(field.getName().getLocalName(), ns.prefix);
052                Type type = field.getType();
053                String defaultValue = type.encode(field.getDefaultValue());
054                Set<Constraint> constraint = field.getConstraints();
055                FieldImpl newField = new FieldImpl(fieldname, this, type, defaultValue, 0, constraint);
056                newField.setConstant(field.isConstant());
057                addField(newField);
058            }
059        }
060    }
061
062    @Override
063    public Type getType(String typeName) {
064        return types.get(typeName);
065    }
066
067    @Override
068    public Type[] getTypes() {
069        return types.values().toArray(new Type[types.size()]);
070    }
071
072    @Override
073    public void registerType(Type type) {
074        types.put(type.getName(), type);
075    }
076
077    @Override
078    public String toString() {
079        return getClass().getSimpleName() + '(' + name + ')';
080    }
081
082    @Override
083    public Schema getSchema() {
084        return this;
085    }
086
087}