<commit_before>package cz.muni.fi.jboss.migration.migrators.logging;

import cz.muni.fi.jboss.migration.*;
import cz.muni.fi.jboss.migration.actions.CliCommandAction;
import cz.muni.fi.jboss.migration.actions.ModuleCreationAction;
import cz.muni.fi.jboss.migration.conf.GlobalConfiguration;
import cz.muni.fi.jboss.migration.ex.*;
import cz.muni.fi.jboss.migration.migrators.logging.jaxb.*;
import cz.muni.fi.jboss.migration.spi.IConfigFragment;
import cz.muni.fi.jboss.migration.utils.Utils;
import org.apache.commons.collections.map.MultiValueMap;
import org.apache.commons.lang.StringUtils;
import org.jboss.as.controller.client.helpers.ClientConstants;
import org.jboss.dmr.ModelNode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

/**
 * Migrator of logging subsystem implementing IMigrator
 *
 * @author <NAME>
 */
public class LoggingMigrator extends AbstractMigrator {

    // Sequence number for driver names.
    // TODO: Perhaps move this property to migration context.
    private int number = 1;
    
    @Override protected String getConfigPropertyModuleName() { return "logging"; }
    

    public LoggingMigrator(GlobalConfiguration globalConfig, MultiValueMap config) {
        super(globalConfig, config);
    }

    @Override
    public void loadAS5Data(MigrationContext ctx) throws LoadMigrationException {
        try {
            Unmarshaller unmarshaller = JAXBContext.newInstance(LoggingAS5Bean.class).createUnmarshaller();
            File log4jConfFile = Utils.createPath( 
                    super.getGlobalConfig().getAS5Config().getDir(),  "server",
                    super.getGlobalConfig().getAS5Config().getProfileName(),
                    "conf", "jboss-log4j.xml");

            XMLInputFactory xif = XMLInputFactory.newFactory();
            xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(log4jConfFile));

            LoggingAS5Bean loggingAS5;

            if (log4jConfFile.canRead()) {
                loggingAS5 = (LoggingAS5Bean) unmarshaller.unmarshal(xsr);
            } else {
                throw new LoadMigrationException("Cannot find/open file: " + log4jConfFile.getAbsolutePath(), new
                        FileNotFoundException());
            }

            MigrationData mData = new MigrationData();

            if(loggingAS5.getCategories() != null){
                mData.getConfigFragments().addAll(loggingAS5.getCategories());
            }

            if(loggingAS5.getLoggers() != null){
                mData.getConfigFragments().addAll(loggingAS5.getLoggers());
            }

            mData.getConfigFragments().addAll(loggingAS5.getAppenders());
            mData.getConfigFragments().add(loggingAS5.getRootLoggerAS5());

            ctx.getMigrationData().put(LoggingMigrator.class, mData);

        } catch (JAXBException | XMLStreamException e) {
            throw new LoadMigrationException(e);
        }
    }
    
    
    
    @Override
    public void createActions(MigrationContext ctx) throws ActionException {
        
        List<CustomHandlerBean> customHandlers = new ArrayList();

        for( IConfigFragment fragment : ctx.getMigrationData().get(LoggingMigrator.class).getConfigFragments() ){
            if (fragment instanceof AppenderBean) {
                AppenderBean appender = (AppenderBean) fragment;
                CustomHandlerBean customHandler = processAppenderBean( appender, ctx );
                if( null != customHandler )
                    customHandlers.add( customHandler );
                continue;
            }

            if (fragment instanceof CategoryBean) {
                try {
                    ctx.getActions().add(createLoggerCliAction(migrateCategory((CategoryBean) fragment)));
                } catch (CliScriptException e) {
                    throw new ActionException("Migration of the Category failed: " + e.getMessage(), e);
                }
                continue;
            }

            if (fragment instanceof RootLoggerAS5Bean) {
                RootLoggerAS5Bean root = (RootLoggerAS5Bean) fragment;
                // For now empty => Find way to create CLI API command for root-logger
                continue;
            }

            throw new ActionException("Config fragment unrecognized by " + this.getClass().getSimpleName() + ": " + fragment );
        }

        HashMap<File, String> tempModules = new HashMap();
        for(CustomHandlerBean handler : customHandlers){
            File src;
            try {
                src = Utils.findJarFileWithClass(handler.getClassValue(), getGlobalConfig().getAS5Config().getDir(),
                        getGlobalConfig().getAS5Config().getProfileName());
            } catch (IOException e) {
                throw new ActionException("Finding jar containing driver class " + handler.getClassValue() + " failed: " + e.getMessage(), e);
            }

            if(tempModules.containsKey(src)){
                // It means that moduleAction is already set. No need for another one => create CLI for CustomHandler and
                // continue on the next iteration
                handler.setModule(tempModules.get(src));
                try {
                    ctx.getActions().add(createCustomHandlerCliAction(handler));
                } catch (CliScriptException e) {
                    throw new ActionException("Migration of the appeneder " + handler.getName() + " failed (CLI command): " + e.getMessage(), e);
                }
                continue;
            }

            // Driver file is new => create ModuleCreationAction, new module and CLI script for driver
            handler.setModule("migration.logging.customHandler" + number);
            tempModules.put(src, handler.getModule());

            try {
                ctx.getActions().add(createCustomHandlerCliAction(handler));
            } catch (CliScriptException e) {
                throw new ActionException("Migration of the appeneder " + handler.getName() + " failed (CLI command): " + e.getMessage(), e);
            }

            File targetDir = Utils.createPath(getGlobalConfig().getAS7Config().getDir(), "modules", "migration",
                    "logging", "customHandler" + number, "main", src.getName());

            Document doc;
            try {
                doc  =  LoggingUtils.createLoggingModuleXML(handler.getModule(), src.getName());
            } catch (ParserConfigurationException e) {
                throw new ActionException("Creation of Document representing module.xml for Custom-Handler failed: " + e.getMessage(), e);
            }

            // Default for now => false
            ModuleCreationAction moduleAction = new ModuleCreationAction(src, targetDir, doc, false);

            ctx.getActions().add(moduleAction);
            // iterate number of custom handlers for creation of modules
            number++;
        }
    }

    

    /**
     *  Processes AppenderBean. Only used above.
     */
    private CustomHandlerBean processAppenderBean( AppenderBean appenderBean, MigrationContext ctx ) throws ActionException {
        
        // Selection of classes which are stored in log4j or jboss logging jars.
        String type = appenderBean.getAppenderClass();
        if(type.contains("org.apache.log4j") || type.contains("org.jboss.logging.appender")){<commit_msg>Forgot to negate the condition<commit_after>package cz.muni.fi.jboss.migration.migrators.logging;

import cz.muni.fi.jboss.migration.*;
import cz.muni.fi.jboss.migration.actions.CliCommandAction;
import cz.muni.fi.jboss.migration.actions.ModuleCreationAction;
import cz.muni.fi.jboss.migration.conf.GlobalConfiguration;
import cz.muni.fi.jboss.migration.ex.*;
import cz.muni.fi.jboss.migration.migrators.logging.jaxb.*;
import cz.muni.fi.jboss.migration.spi.IConfigFragment;
import cz.muni.fi.jboss.migration.utils.Utils;
import org.apache.commons.collections.map.MultiValueMap;
import org.apache.commons.lang.StringUtils;
import org.jboss.as.controller.client.helpers.ClientConstants;
import org.jboss.dmr.ModelNode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

/**
 * Migrator of logging subsystem implementing IMigrator
 *
 * @author <NAME>
 */
public class LoggingMigrator extends AbstractMigrator {

    // Sequence number for driver names.
    // TODO: Perhaps move this property to migration context.
    private int number = 1;
    
    @Override protected String getConfigPropertyModuleName() { return "logging"; }
    

    public LoggingMigrator(GlobalConfiguration globalConfig, MultiValueMap config) {
        super(globalConfig, config);
    }

    @Override
    public void loadAS5Data(MigrationContext ctx) throws LoadMigrationException {
        try {
            Unmarshaller unmarshaller = JAXBContext.newInstance(LoggingAS5Bean.class).createUnmarshaller();
            File log4jConfFile = Utils.createPath( 
                    super.getGlobalConfig().getAS5Config().getDir(),  "server",
                    super.getGlobalConfig().getAS5Config().getProfileName(),
                    "conf", "jboss-log4j.xml");

            XMLInputFactory xif = XMLInputFactory.newFactory();
            xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(log4jConfFile));

            LoggingAS5Bean loggingAS5;

            if (log4jConfFile.canRead()) {
                loggingAS5 = (LoggingAS5Bean) unmarshaller.unmarshal(xsr);
            } else {
                throw new LoadMigrationException("Cannot find/open file: " + log4jConfFile.getAbsolutePath(), new
                        FileNotFoundException());
            }

            MigrationData mData = new MigrationData();

            if(loggingAS5.getCategories() != null){
                mData.getConfigFragments().addAll(loggingAS5.getCategories());
            }

            if(loggingAS5.getLoggers() != null){
                mData.getConfigFragments().addAll(loggingAS5.getLoggers());
            }

            mData.getConfigFragments().addAll(loggingAS5.getAppenders());
            mData.getConfigFragments().add(loggingAS5.getRootLoggerAS5());

            ctx.getMigrationData().put(LoggingMigrator.class, mData);

        } catch (JAXBException | XMLStreamException e) {
            throw new LoadMigrationException(e);
        }
    }
    
    
    
    @Override
    public void createActions(MigrationContext ctx) throws ActionException {
        
        List<CustomHandlerBean> customHandlers = new ArrayList();

        for( IConfigFragment fragment : ctx.getMigrationData().get(LoggingMigrator.class).getConfigFragments() ){
            if (fragment instanceof AppenderBean) {
                AppenderBean appender = (AppenderBean) fragment;
                CustomHandlerBean customHandler = processAppenderBean( appender, ctx );
                if( null != customHandler )
                    customHandlers.add( customHandler );
                continue;
            }

            if (fragment instanceof CategoryBean) {
                try {
                    ctx.getActions().add(createLoggerCliAction(migrateCategory((CategoryBean) fragment)));
                } catch (CliScriptException e) {
                    throw new ActionException("Migration of the Category failed: " + e.getMessage(), e);
                }
                continue;
            }

            if (fragment instanceof RootLoggerAS5Bean) {
                RootLoggerAS5Bean root = (RootLoggerAS5Bean) fragment;
                // For now empty => Find way to create CLI API command for root-logger
                continue;
            }

            throw new ActionException("Config fragment unrecognized by " + this.getClass().getSimpleName() + ": " + fragment );
        }

        HashMap<File, String> tempModules = new HashMap();
        for(CustomHandlerBean handler : customHandlers){
            File src;
            try {
                src = Utils.findJarFileWithClass(handler.getClassValue(), getGlobalConfig().getAS5Config().getDir(),
                        getGlobalConfig().getAS5Config().getProfileName());
            } catch (IOException e) {
                throw new ActionException("Finding jar containing driver class " + handler.getClassValue() + " failed: " + e.getMessage(), e);
            }

            if(tempModules.containsKey(src)){
                // It means that moduleAction is already set. No need for another one => create CLI for CustomHandler and
                // continue on the next iteration
                handler.setModule(tempModules.get(src));
                try {
                    ctx.getActions().add(createCustomHandlerCliAction(handler));
                } catch (CliScriptException e) {
                    throw new ActionException("Migration of the appeneder " + handler.getName() + " failed (CLI command): " + e.getMessage(), e);
                }
                continue;
            }

            // Driver file is new => create ModuleCreationAction, new module and CLI script for driver
            handler.setModule("migration.logging.customHandler" + number);
            tempModules.put(src, handler.getModule());

            try {
                ctx.getActions().add(createCustomHandlerCliAction(handler));
            } catch (CliScriptException e) {
                throw new ActionException("Migration of the appeneder " + handler.getName() + " failed (CLI command): " + e.getMessage(), e);
            }

            File targetDir = Utils.createPath(getGlobalConfig().getAS7Config().getDir(), "modules", "migration",
                    "logging", "customHandler" + number, "main", src.getName());

            Document doc;
            try {
                doc  =  LoggingUtils.createLoggingModuleXML(handler.getModule(), src.getName());
            } catch (ParserConfigurationException e) {
                throw new ActionException("Creation of Document representing module.xml for Custom-Handler failed: " + e.getMessage(), e);
            }

            // Default for now => false
            ModuleCreationAction moduleAction = new ModuleCreationAction(src, targetDir, doc, false);

            ctx.getActions().add(moduleAction);
            // iterate number of custom handlers for creation of modules
            number++;
        }
    }

    

    /**
     *  Processes AppenderBean. Only used above.
     */
    private CustomHandlerBean processAppenderBean( AppenderBean appenderBean, MigrationContext ctx ) throws ActionException {
        
        // Selection of classes which are stored in log4j or jboss logging jars.
        String type = appenderBean.getAppenderClass();
        if( ! (type.contains("org.apache.log4j") || type.contains("org.jboss.logging.appender")) ){
{'fraction_non_alphanumeric': 0.09986818153286046, 'fraction_numerical': 0.004142866110099805, 'mean_word_length': 2.4455017301038064, 'pattern_counts': {'":': 2, '<': 9, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 22}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2772916', 'n_tokens_mistral': 4250, 'n_tokens_neox': 4112, 'n_words': 884}