com.tera.common.vcontext.model.elements.AbstractContext.java Source code

Java tutorial

Introduction

Here is the source code for com.tera.common.vcontext.model.elements.AbstractContext.java

Source

/**
 * This file is part of tera-api.
 * 
 * tera-api is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * tera-api is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with tera-api.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.tera.common.vcontext.model.elements;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import com.tera.common.vcontext.model.NodeId;
import com.tera.common.vcontext.model.VElement;

/**
 * @author ATracer
 */
public abstract class AbstractContext extends VirtualNode implements VContext {

    /**
     * @param name
     */
    public AbstractContext(String name) {
        super(name);
    }

    @Override
    public VElement getRoot() {
        return getElement(NodeId.ROOT_NODE.getId());
    }

    @Override
    public void setRoot(VElement element) {
        addElement(element);
        element.setParent(this);
    }

    @Override
    public VElement find(String name) {
        String[] nodes = extractNames(name);

        String rootNode = nodes[0];

        // TODO throw exceptions
        if (!NodeId.ROOT.name().equals(rootNode)) {
            return null;
        }
        VElement targetElement = getRoot();
        for (int i = 1; i < nodes.length; i++) {
            targetElement = targetElement.getElement(nodes[i]);
        }
        return targetElement;
    }

    @Override
    public void put(String name, VElement element) {
        String[] nodes = extractNames(name);

        String rootNode = nodes[0];

        // TODO throw exceptions
        if (!NodeId.ROOT.name().equals(rootNode)) {
            return;
        }

        VElement currentElement = getRoot();
        for (int i = 1; i < nodes.length; i++) {
            VElement elem = currentElement.getElement(nodes[i]);
            if (elem == null) {
                elem = new VirtualNode(nodes[i]);
                currentElement.addElement(elem);
            }
            currentElement = elem;
        }

        currentElement.addElement(element);
    }

    /**
     * @param name
     * @return
     */
    private String[] extractNames(String name) {
        String[] nodes = name.split("/");
        nodes = (String[]) ArrayUtils.removeElement(nodes, StringUtils.EMPTY);
        return nodes;
    }

}