class DomainSchemaHelper {

    public static <T extends SchemaElement> T findResourceElement(String resourcePath, List<ResourceElement> resources){
        SchemaElement result = null;
        List<? extends SchemaElement> currentElements = resources;
        if(resources != null && resourcePath != null){
            final String[] pathTokens = resourcePath.split("\\.");
            for(int i = 0; i < pathTokens.length; i++){
                String name = pathTokens[i];
                SchemaElement currentResult = null;
                if (currentElements == null) break;
                for(SchemaElement element : currentElements){
                    if(element != null && name.equals(element.getName())){
                        currentResult = element;
                        break;
                    }
                }
                if(i == pathTokens.length - 1){
                    result = currentResult;
                } else if(currentResult instanceof AbstractResourceGroupElement){
                    currentElements = ((AbstractResourceGroupElement) currentResult).getElements();
                } else if(currentResult instanceof ConstantsResourceGroupElement){
                    currentElements = ((ConstantsResourceGroupElement) currentResult).getElements();
                } else if(currentResult instanceof ReferenceElement){
                    SchemaElement referenced = findResourceElement(((ReferenceElement) currentResult).getReferencePath(), resources);
                    if(referenced != null && referenced instanceof AbstractResourceGroupElement){
                        currentElements = ((AbstractResourceGroupElement) referenced).getElements();
                    }
                } else {
                    // not found
                    break;
                }
            }
        }
        return (T)result;
    }

}