001/*
002 * Copyright (c) 2015 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 *
012 */
013package org.nuxeo.ecm.core.io.impl.transformers;
014
015import java.io.IOException;
016import java.util.List;
017
018import org.dom4j.Element;
019import org.dom4j.Namespace;
020import org.dom4j.QName;
021import org.nuxeo.ecm.core.io.DocumentTransformer;
022import org.nuxeo.ecm.core.io.ExportedDocument;
023
024/**
025 * Renames a schema
026 *
027 * @since 7.4
028 */
029public class SchemaRenamer implements DocumentTransformer {
030
031    protected final String srcSchema;
032
033    protected final String dstSchema;
034
035    protected final String dstPrefix;
036
037    public SchemaRenamer(String srcSchema, String dstSchema, String dstPrefix) {
038        this.srcSchema = srcSchema;
039        this.dstSchema = dstSchema;
040        this.dstPrefix = dstPrefix;
041    }
042
043    @Override
044    public boolean transform(ExportedDocument xdoc) throws IOException {
045        Element root = xdoc.getDocument().getRootElement();
046
047        List<Object> schemas = root.elements("schema");
048        Element src = null;
049        if (schemas != null) {
050            for (Object s : schemas) {
051                Element schema = (Element) s;
052                String name = schema.attribute("name").getText();
053                if (srcSchema.equalsIgnoreCase(name)) {
054                    Namespace ns = new Namespace(dstPrefix, "http://www.nuxeo.org/ecm/schemas/" + dstSchema);
055                    schema.add(ns);
056                    schema.setAttributeValue("name", dstSchema);
057                    List<Element> fields = schema.elements();
058                    for (Element field : fields) {
059                        field.setQName(new QName(field.getName(), ns));
060                        ;
061                    }
062                }
063            }
064        }
065        return true;
066    }
067}