com.pactera.edg.am.metamanager.extractor.adapter.mapping.impl.CommonMappingServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.pactera.edg.am.metamanager.extractor.adapter.mapping.impl.CommonMappingServiceImpl.java

Source

/*
 * Copyright 2009 by pactera.edg.am Corporation. Address:HePingLi East Street No.11
 * 5-5, BeiJing,
 * 
 * All rights reserved.
 * 
 * This software is the confidential and proprietary information of pactera.edg.am
 * Corporation ("Confidential Information"). You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with pactera.edg.am.
 */

package com.pactera.edg.am.metamanager.extractor.adapter.mapping.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Element;
import org.dom4j.Node;

import com.pactera.edg.am.metamanager.extractor.adapter.extract.AbstractXmlAdapter;
import com.pactera.edg.am.metamanager.extractor.adapter.mapping.IMetadataMappingService;
import com.pactera.edg.am.metamanager.extractor.bo.mm.AppendMetadata;
import com.pactera.edg.am.metamanager.extractor.bo.mm.MMDDependency;
import com.pactera.edg.am.metamanager.extractor.bo.mm.MMMetaModel;
import com.pactera.edg.am.metamanager.extractor.bo.mm.MMMetadata;
import com.pactera.edg.am.metamanager.extractor.dao.IMetadataDao;
import com.pactera.edg.am.metamanager.extractor.ex.SpringContextLoadException;
import com.pactera.edg.am.metamanager.extractor.util.Dom4jReader;
import com.pactera.edg.am.metamanager.extractor.util.ExtractorContextLoader;

/**
 * xml?
 * 
 * @author user
 * @version 1.0 Date: Aug 24, 2009
 * 
 */
public class CommonMappingServiceImpl extends BaseMappingServiceImpl implements IMetadataMappingService {

    private Log log = LogFactory.getLog(CommonMappingServiceImpl.class);

    /**
     * XSLT???
     */
    private AbstractXmlAdapter commonAdapter;

    private IMetadataDao metadataDao;

    /**
     * ??,?
     */
    private Map<Integer, MMMetadata> metadatasCache = new HashMap<Integer, MMMetadata>();

    /**
     * 
     * 
     * @throws SpringContextLoadException
     *             Spring?
     */
    public CommonMappingServiceImpl() throws SpringContextLoadException {
        metadataDao = (IMetadataDao) ExtractorContextLoader.getBean(IMetadataDao.SPRING_NAME);
    }

    private void parseSingleStream(InputStream iStream, AppendMetadata aMetadata) throws Exception {
        Dom4jReader reader = new Dom4jReader();

        try {
            if (reader.initDocument(iStream)) {
                try {
                    iStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // ??
                List<Element> elements = reader.selectNodes("/root/instances/instance");
                if (elements != null && elements.size() > 0) {
                    aMetadata.setChildMetaModels(
                            genRootMetaModels(elements, aMetadata.getMetadata(), aMetadata.getMetaModel()));
                    aMetadata.setDDependencies(genDependencies(reader.selectNodes("//relationships/relationship")));

                }
            }
        } finally {
            if (iStream != null) {
                try {
                    iStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            reader.close();
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.pactera.edg.am.metamanager.extractor.adapter.mapping.IMetadataMappingService#metadataMapping()
     */
    public void metadataMapping(AppendMetadata aMetadata) throws Exception {
        InputStream iStream = null;
        try {
            iStream = commonAdapter.parse();
            parseSingleStream(iStream, aMetadata);
        } finally {
            metadatasCache.clear();
        }
    }

    private List<MMDDependency> genDependencies(List<Element> elements) {

        /**
         * ??
         */
        Set<String> duplicateRelationships = new HashSet<String>();

        List<MMDDependency> dependencies = new ArrayList<MMDDependency>();
        // ?
        for (Element element : elements) {
            MMDDependency dependency = new MMDDependency();
            // XMLXSLT????trim()add by fbchen 2011-01-12
            int ownerId = element.attributeValue("frominstanceid").trim().hashCode();
            int valueId = element.attributeValue("toinstanceid").trim().hashCode();
            if (metadatasCache.containsKey(ownerId) && metadatasCache.containsKey(valueId)) {
                // OWNERIDVALUEID?,ID
                String relationshipId = new StringBuilder().append(ownerId).append("_").append(valueId).toString();

                if (duplicateRelationships.contains(relationshipId)) {
                    log.warn(new StringBuilder("???:??:")
                            .append(metadatasCache.get(ownerId).getCode()).append(",??:")
                            .append(metadatasCache.get(valueId).getCode()).toString());
                    continue;
                }
                duplicateRelationships.add(relationshipId);

                dependency.setOwnerMetadata(metadatasCache.get(ownerId));
                dependency.setValueMetadata(metadatasCache.get(valueId));
                dependency.setOwnerRole(element.attributeValue("deprole"));
                dependency.setValueRole(element.attributeValue("depedrole"));
                dependencies.add(dependency);
            }
        }

        return dependencies;
    }

    /**
     * ?
     * 
     * @param elements
     * @param parentMetadata
     * @param parentMetaModel
     * @return
     */
    private Set<MMMetaModel> genRootMetaModels(List<Element> elements, MMMetadata parentMetadata,
            MMMetaModel parentMetaModel) {
        Set<MMMetaModel> metaModels = new HashSet<MMMetaModel>(2);

        // list???,???,???
        Collections.reverse(elements);
        /**
         * ??,??
         */
        Set<String> duplicateElement = new HashSet<String>();
        for (Element element : elements) {

            String modelId = element.attributeValue("class");

            String code = element.selectSingleNode("./attributes/instancecode").getText();
            if (code == null || code.equals("")) {
                log.warn(new StringBuilder("Code!").append(",:").append(modelId).toString());
                continue;
            }
            String duplicateString = new StringBuilder().append(code).append("_").append(modelId).toString();

            if (duplicateElement.contains(duplicateString)) {
                // ?,?CODE?,??
                log.warn(new StringBuilder("??Element:").append(code).append(",:").append(modelId)
                        .toString());
                continue;
            }

            duplicateElement.add(duplicateString);

            MMMetadata relativeMetadata = parentMetadata;
            MMMetaModel relativeModel = parentMetaModel;
            // ?Excel?
            Node pathNode = element.selectSingleNode("./path");

            if (pathNode != null) {
                relativeMetadata = genRelativeMetadata(parentMetadata, pathNode.getText());
                if (relativeMetadata == null) {
                    continue;
                }
                relativeModel = new MMMetaModel();
                relativeModel.setCode(relativeMetadata.getClassifierId());
            }

            MMMetaModel cntMetaModel = getMetaModel(relativeModel, metaModels, element);
            MMMetadata metadata = genMetadata(relativeMetadata, cntMetaModel, element);
            //         cntMetaModel.addMetadata(metadata);
            //         cntMetaModel.setHasMetadata(true);
            List<Element> childElements = element.selectNodes("./instances/instance");
            if (childElements != null && childElements.size() > 0) {
                genMetaModels(childElements, metadata, cntMetaModel);
                //            cntMetaModel.setHasChildMetaModel(true);
            }
        }
        return metaModels;
    }

    /**
     * ?Excel?Excel(,?)
     * ????,??(???)
     * 
     * @param dsMetadataId
     *            ??ID
     * @param relativePath
     *            ,?:/metadataCode(metaModelCode)/metadataCode(metaModelCode)/...
     * @return
     */
    private MMMetadata genRelativeMetadata(MMMetadata parentMetadata, String relativePath) {
        String[] relativePaths = relativePath.split("/");
        if (relativePaths.length <= 1) {
            return parentMetadata;
        }
        String dsMetadataId = parentMetadata.getId();
        String parentId = dsMetadataId;
        MMMetadata metadata = new MMMetadata();
        int index, lastIndex;
        String metadataCode, modelCode;

        for (int i = 1; i < relativePaths.length; i++) {
            // ???"/"
            index = relativePaths[i].indexOf("(");
            lastIndex = relativePaths[i].indexOf(")");
            metadataCode = relativePaths[i].substring(0, index);
            modelCode = relativePaths[i].substring(index + 1, lastIndex);

            metadata.setCode(metadataCode);
            metadata.setClassifierId(modelCode);

            if (!metadataDao.existMetadata(parentId, metadata)) {
                // ???
                log.error(new StringBuilder(":").append(relativePath)
                        .append(",?:").append(parentId).append(", ?code:")
                        .append(metadataCode).append(", :").append(modelCode)
                        .append(",?,?.").toString());
                return null;
            }
            parentId = metadata.getId();

        }

        metadata.setHasExist(true);
        return metadata;
    }

    private MMMetaModel getMetaModel(MMMetaModel parentMetaModel, Set<MMMetaModel> metaModels, Element element) {
        boolean existMetaModel = false;
        MMMetaModel cntMetaModel = null;

        String metaModelCode = element.attributeValue("class");
        for (Iterator<MMMetaModel> iter = metaModels.iterator(); iter.hasNext();) {
            MMMetaModel metaModel = iter.next();
            if (metaModel.getCode().equals(metaModelCode)) {
                // ?,???
                cntMetaModel = metaModel;
                existMetaModel = true;
                break;
            }

        }
        if (!existMetaModel) {
            cntMetaModel = new MMMetaModel();
            cntMetaModel.setCode(metaModelCode);
            cntMetaModel.setParentMetaModel(parentMetaModel);
            // String compedRelationCode =
            // element.attributeValue("composition");
            // if (compedRelationCode != null) {
            // cntMetaModel.setCompedRelationCode(compedRelationCode);
            // }
            metaModels.add(cntMetaModel);

        }
        return cntMetaModel;
    }

    private void genMetaModels(List<Element> elements, MMMetadata parentMetadata, MMMetaModel parentMetaModel) {

        // list???,???,???
        Collections.reverse(elements);
        /**
         * ??,CODE???
         */
        Set<String> duplicateElement = new HashSet<String>();
        for (Element element : elements) {
            String modelId = element.attributeValue("class");

            String code = element.selectSingleNode("./attributes/instancecode").getText();
            if (code == null || code.equals("")) {
                log.warn(new StringBuilder("Code!").append(",:").append(modelId).toString());
                continue;
            }

            String duplicateString = new StringBuilder().append(code.hashCode()).append("_")
                    .append(modelId.hashCode()).toString();

            if (duplicateElement.contains(duplicateString)) {
                // ?,?CODE?,??
                log.warn(new StringBuilder("??Element:").append(code).append(":").append(modelId)
                        .toString());
                continue;
            }

            duplicateElement.add(duplicateString);

            MMMetaModel cntMetaModel = getMetaModel(parentMetaModel, element);
            MMMetadata metadata = genMetadata(parentMetadata, cntMetaModel, element);
            //         cntMetaModel.addMetadata(metadata);
            //         cntMetaModel.setHasMetadata(true);
            List<Element> childElements = element.selectNodes("./instances/instance");
            if (childElements != null && childElements.size() > 0) {
                genMetaModels(childElements, metadata, cntMetaModel);
                //            cntMetaModel.setHasChildMetaModel(true);
            }
        }
    }

    private MMMetaModel getMetaModel(MMMetaModel parentMetaModel, Element element) {
        boolean existMetaModel = false;
        MMMetaModel cntMetaModel = null;
        String metaModelCode = element.attributeValue("class");

        for (Iterator<MMMetaModel> iter = parentMetaModel.getChildMetaModels().iterator(); iter.hasNext();) {
            MMMetaModel childMetaModel = iter.next();
            if (childMetaModel.getCode().equals(metaModelCode)) {
                // ?,???
                cntMetaModel = childMetaModel;
                existMetaModel = true;
                break;
            }

        }
        if (!existMetaModel) {
            parentMetaModel.addChildMetaModels(metaModelCode);
            cntMetaModel = parentMetaModel.getChildMetaModel(metaModelCode);
        }
        return cntMetaModel;
    }

    private MMMetadata genMetadata(MMMetadata parentMetadata, MMMetaModel cntMetaModel, Element element) {
        new MMMetadata();
        // metadata.setClassifierId(element.attributeValue("class"));
        String code = element.selectSingleNode("./attributes/instancecode").getText();
        String name = element.selectSingleNode("./attributes/instancename").getText();
        // metadata.setCode(code == null ? "" : code.trim());
        // metadata.setName(name == null ? "" : name.trim());
        MMMetadata metadata = super.createMetadata(parentMetadata, cntMetaModel, code == null ? "" : code.trim(),
                name == null ? "" : name.trim());
        // metadata.setParentMetadata(parentMetadata);
        //      
        // parentMetadata.addChildMetadata(metadata);

        Map<String, String> attrs = new HashMap<String, String>();

        List<Element> attrElements = ((Element) element.selectSingleNode("./features")).elements();
        for (Element attrElement : attrElements) {
            String value = attrElement.getText();
            value = (value == null) ? null : value.trim(); // XML?trim()
            if (value == null || value.equals("")) {
                continue;
            }
            attrs.put(attrElement.getName(), value);
        }
        metadata.setAttrs(attrs);

        // ?
        metadatasCache.put(element.selectSingleNode("./attributes/instanceid").getText().hashCode(), metadata);
        return metadata;
    }

    public void setService(AbstractXmlAdapter service) {
        this.commonAdapter = service;
    }

}