package br.gov.servicos.legado;

import br.gov.servicos.servico.Servico;
import br.gov.servicos.servico.ServicoRepository;
import com.github.slugify.Slugify;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;
import static lombok.AccessLevel.PRIVATE;

@Slf4j
@Component
@FieldDefaults(level = PRIVATE, makeFinal = true)
@ManagedResource(
        objectName = "ServicosGovBr:type=ImportadorLegado",
        description = "Importa XML do Guia legado para o ElasticSearch"
)
public class ImportadorLegado {

    private static final String XML_LEGADO = "guiadeservicos.xml";

    ResourcePatternResolver resolver;
    ServicoRepository servicos;
    ServicoLegadoParaServico servicoLegadoParaServico;

    @Autowired
    ImportadorLegado(ResourcePatternResolver resolver, ServicoRepository servicos, ServicoLegadoParaServico servicoLegadoParaServico) {
        this.resolver = resolver;
        this.servicos = servicos;
        this.servicoLegadoParaServico = servicoLegadoParaServico;
    }

    private Stream<ServicoType> servicosLegados() throws IOException, JAXBException {

        return Stream.of(resolver.getResources("classpath:legado/*.xml"))
                .parallel()
                .map(r -> {
                    log.debug("XML legado utilizado para importação: {}", r);
                    try {
                        return (ServicoType) unmarshaller().unmarshal(r.getURL());
                    } catch (JAXBException | IOException e) {
                        log.error("Erro ao importar {}", r, e);
                        return null;
                    }
                })
                .filter(i -> i != null);
    }

    private static Unmarshaller unmarshaller() throws JAXBException {
        JAXBContext contexto = JAXBContext.newInstance("br.gov.servicos.legado");
        return contexto.createUnmarshaller();
    }

    public Iterable<Servico> importar() throws IOException, JAXBException {
        return servicos.save(
                servicosLegados()
                        .map(servicoLegadoParaServico)
                        .collect(toList()));
    }

    @ManagedOperation
    public void mapearParaXMLsIndependentes() throws JAXBException, IOException {
        JAXBContext contexto = JAXBContext.newInstance("br.gov.servicos.legado");

        URL xmlLegado = new ClassPathResource(XML_LEGADO).getURL();
        log.debug("XML legado utilizado para importação: {}", xmlLegado);

        JAXBElement element = (JAXBElement) unmarshaller().unmarshal(xmlLegado);
        log.debug("XML legado lido com sucesso");

        ((DadosType) element.getValue()).getServicos().getServico().parallelStream().forEach(s -> {
            try {
                contexto.createMarshaller().marshal(s, new File("src/main/resources/legado/" + new Slugify().slugify(s.getTitulo()) + ".xml"));
            } catch (IOException | JAXBException e) {
                throw new RuntimeException(e);
            }

        });
    }
}

@@ -120,43 +120,8 @@
 ry;%0A
-import com.github.slugify.Slugify;%0A
 impo
@@ -290,25 +290,16 @@
 core.io.
-ClassPath
 Resource
@@ -372,141 +372,8 @@
 er;%0A
-import org.springframework.jmx.export.annotation.ManagedOperation;%0Aimport org.springframework.jmx.export.annotation.ManagedResource;%0A
 impo
@@ -457,43 +457,8 @@
 xt;%0A
-import javax.xml.bind.JAXBElement;%0A
 impo
@@ -530,29 +530,8 @@
 er;%0A
-import java.io.File;%0A
 impo
@@ -570,15 +570,43 @@
 ava.
-net.URL
+util.List;%0Aimport java.util.Objects
 ;%0Aim
@@ -801,160 +801,8 @@
 ue)%0A
-@ManagedResource(%0A        objectName = %22ServicosGovBr:type=ImportadorLegado%22,%0A        description = %22Importa XML do Guia legado para o ElasticSearch%22%0A)%0A
 publ
@@ -1325,338 +1325,607 @@
    p
-rivate Stream%3CServicoType%3E servicosLegados() throws IOException, JAXBException %7B%0A%0A        return Stream.of(resolver.getResources(%22classpath:legado/*.xml%22))%0A                .parallel()%0A                .map(r -%3E %7B%0A                    log.debug(%22XML legado utilizado para importa%C3%A7%C3%A3o: %7B%7D%22, r);%0A                    try %7B%0A              
+ublic Iterable%3CServico%3E importar() throws IOException, JAXBException %7B%0A        return servicos.save(servicosImportados());%0A    %7D%0A%0A    private List%3CServico%3E servicosImportados() throws IOException %7B%0A        return Stream.of(resolver.getResources(%22classpath:legado/*.xml%22))%0A                .parallel()%0A                .map(this::parsearXML)%0A                .filter(Objects::nonNull)%0A                .map(servicoLegadoParaServico)%0A                .collect(toList());%0A    %7D%0A%0A    private ServicoType parsearXML(Resource resource) %7B%0A        log.debug(%22Importando XML legado: %7B%7D%22, resource);%0A        try %7B%0A
     
@@ -1926,24 +1926,26 @@
 %7B%0A          
+  
 return (Serv
@@ -1979,16 +1979,23 @@
 arshal(r
+esource
 .getURL(
@@ -1998,28 +1998,16 @@
 URL());%0A
-            
         
@@ -2060,28 +2060,16 @@
         
-     
-       
 log.erro
@@ -2098,26 +2098,21 @@
 %22, r
-, e);%0A            
+esource, e);%0A
     
@@ -2144,81 +2144,9 @@
     
-            %7D%0A                %7D)%0A                .filter(i -%3E i != null);
+%7D
 %0A   
@@ -2356,1113 +2356,7 @@
    %7D
-%0A%0A    public Iterable%3CServico%3E importar() throws IOException, JAXBException %7B%0A        return servicos.save(%0A                servicosLegados()%0A                        .map(servicoLegadoParaServico)%0A                        .collect(toList()));%0A    %7D%0A%0A    @ManagedOperation%0A    public void mapearParaXMLsIndependentes() throws JAXBException, IOException %7B%0A        JAXBContext contexto = JAXBContext.newInstance(%22br.gov.servicos.legado%22);%0A%0A        URL xmlLegado = new ClassPathResource(XML_LEGADO).getURL();%0A        log.debug(%22XML legado utilizado para importa%C3%A7%C3%A3o: %7B%7D%22, xmlLegado);%0A%0A        JAXBElement element = (JAXBElement) unmarshaller().unmarshal(xmlLegado);%0A        log.debug(%22XML legado lido com sucesso%22);%0A%0A        ((DadosType) element.getValue()).getServicos().getServico().parallelStream().forEach(s -%3E %7B%0A            try %7B%0A                contexto.createMarshaller().marshal(s, new File(%22src/main/resources/legado/%22 + new Slugify().slugify(s.getTitulo()) + %22.xml%22));%0A            %7D catch (IOException %7C JAXBException e) %7B%0A                throw new RuntimeException(e);%0A            %7D%0A%0A        %7D);%0A    %7D
 %0A%7D%0A

Simplifica o código de importação