/**
 * Copyright 2015-2017 Red Hat, Inc, and individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.wildfly.swarm.container.runtime.xmlconfig;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;

import javax.enterprise.inject.Vetoed;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.jboss.as.controller.ProcessType;
import org.jboss.as.controller.RunningMode;
import org.jboss.as.controller.RunningModeControl;
import org.jboss.as.controller.extension.ExtensionRegistry;
import org.jboss.as.controller.parsing.DeferredExtensionContext;
import org.jboss.as.controller.parsing.Namespace;
import org.jboss.as.controller.parsing.ProfileParsingCompletionHandler;
import org.jboss.as.server.parsing.ExtensionHandler;
import org.jboss.as.server.parsing.StandaloneXml;
import org.jboss.as.server.parsing.StandaloneXml.ParsingOption;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLExtendedStreamReader;
import org.jboss.staxmapper.XMLExtendedStreamWriter;
import org.jboss.staxmapper.XMLMapper;
import org.wildfly.swarm.bootstrap.modules.BootModuleLoader;

/**
 * @author Heiko Braun
 * @author Ken Finnigan
 * @since 27/11/15
 */
@Vetoed
public class StandaloneXMLParser {

    private static final String SERVER = "server";

    private Set<QName> recognizedNames = new HashSet<>();

    public StandaloneXMLParser() {

        //WF14, THORN-2210
        @SuppressWarnings("deprecation")
        final ExtensionRegistry extensionRegistry =
            new ExtensionRegistry(ProcessType.EMBEDDED_SERVER, new RunningModeControl(RunningMode.NORMAL));
        final DeferredExtensionContext deferredExtensionContext =
            new DeferredExtensionContext(new BootModuleLoader(), extensionRegistry, null);
        //End of WF14
        parserDelegate = new StandaloneXml(
            new ExtensionHandler() {
                @Override
                public void parseExtensions(XMLExtendedStreamReader reader, ModelNode address, Namespace namespace, List<ModelNode> list) throws XMLStreamException {
                    reader.discardRemainder(); // noop
                }

                @Override
                public Set<ProfileParsingCompletionHandler> getProfileParsingCompletionHandlers() {
                    return Collections.emptySet();
                }

                @Override
                public void writeExtensions(XMLExtendedStreamWriter writer, ModelNode modelNode) throws XMLStreamException {
                    // noop
                }
            },
            //WF14, THORN-2210
            deferredExtensionContext,
            ParsingOption.IGNORE_SUBSYSTEM_FAILURES);

        xmlMapper = XMLMapper.Factory.create();

        addDelegate(new QName(Namespace.CURRENT.getUriString(), SERVER), parserDelegate);
        addDelegate(new QName("urn:jboss:domain:4.1", SERVER), parserDelegate);
        addDelegate(new QName("urn:jboss:domain:4.0", SERVER), parserDelegate);
        addDelegate(new QName("urn:jboss:domain:2.0", SERVER), parserDelegate);
    }

    /**
     * Add a parser for a subpart of the XML model.
     *
     * @param elementName the FQ element name (i.e. subsystem name)
     * @param parser      creates ModelNode's from XML input
     * @return
     */
    public StandaloneXMLParser addDelegate(QName elementName, XMLElementReader<List<ModelNode>> parser) {
        this.recognizedNames.add(elementName);
        xmlMapper.registerRootElement(elementName, parser);
        return this;
    }

    public StandaloneXMLParser addDelegate(QName elementName, Supplier<XMLElementReader<List<ModelNode>>> supplier) {
        this.recognizedNames.add(elementName);
        xmlMapper.registerRootElement(elementName, supplier.get());
        return this;
    }

    public List<ModelNode> parse(URL xml) throws Exception {
        final List<ModelNode> operationList = new ArrayList<>();

        try (InputStream input = xml.openStream()) {
            final XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(input);
            WrappedXMLStreamReader wrappedReader = new WrappedXMLStreamReader(reader, this.recognizedNames, xmlMapper);
            xmlMapper.parseDocument(operationList, wrappedReader);
        }

        return operationList;
    }

    private final XMLMapper xmlMapper;

    private final StandaloneXml parserDelegate;

    @Vetoed
    private static class NoopXMLElementReader implements XMLElementReader<List<ModelNode>> {
        @Override
        public void readElement(XMLExtendedStreamReader reader, List<ModelNode> modelNode) throws XMLStreamException {
            //System.out.println("Skip " + reader.getNamespaceURI() + "::" + reader.getLocalName());
            reader.discardRemainder();
        }
    }

}

@@ -851,24 +851,63 @@
 a.util.Set;%0A
+import java.util.concurrent.Executors;%0A
 import java.
@@ -926,24 +926,24 @@
 n.Supplier;%0A
-
 %0Aimport java
@@ -1326,24 +1326,100 @@
 onRegistry;%0A
+import org.jboss.as.controller.extension.RuntimeHostControllerInfoAccessor;%0A
 import org.j
@@ -2309,17 +2309,16 @@
 ser() %7B%0A
-%0A
         
@@ -2323,65 +2323,112 @@
   //
+ 
 WF14
-, THORN-2210%0A        @SuppressWarnings(%22deprecation%22)
+ this is similar to BootstrapPersister.createDelegate, so should be OK, but better review once more
 %0A   
@@ -2432,22 +2432,16 @@
         
-final 
 Extensio
@@ -2469,28 +2469,16 @@
 gistry =
-%0A           
  new Ext
@@ -2496,36 +2496,68 @@
 try(
-ProcessType.EMBEDDED_SERVER,
+%0A                ProcessType.SELF_CONTAINED,%0A               
  new
@@ -2595,18 +2595,17 @@
 .NORMAL)
-);
+,
 %0A       
@@ -2605,21 +2605,149 @@
         
-final
+        null,%0A                null,%0A                null,%0A                RuntimeHostControllerInfoAccessor.SERVER%0A        );%0A       
  Deferre
@@ -2879,36 +2879,45 @@
 ry, 
-null);%0A        //End of WF14
+Executors.newSingleThreadExecutor());
 %0A   
@@ -3649,24 +3649,24 @@
           %7D%0A
+
             
@@ -3672,39 +3672,8 @@
  %7D,%0A
-            //WF14, THORN-2210%0A
     

fix creating DeferredExtensionContext