net.itransformers.postDiscoverer.core.ReportManager.java Source code

Java tutorial

Introduction

Here is the source code for net.itransformers.postDiscoverer.core.ReportManager.java

Source

/*
 * ReportManager.java
 *
 * This work 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 2 of the License,
 * or (at your option) any later version.
 *
 * This work 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 this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 * Copyright (c) 2010-2016 iTransformers Labs. All rights reserved.
 */

package net.itransformers.postDiscoverer.core;

import groovy.util.ResourceException;
import groovy.util.ScriptException;
import net.itransformers.expect4groovy.Expect4GroovyScriptLauncher;
import net.itransformers.postDiscoverer.reportGenerator.*;
import net.itransformers.resourcemanager.ResourceManager;
import net.itransformers.resourcemanager.ResourceManagerFactory;
import net.itransformers.resourcemanager.config.ConnectionParamsType;
import net.itransformers.resourcemanager.config.ParamType;
import net.itransformers.resourcemanager.config.ResourceType;
import net.itransformers.resourcemanager.xmlResourceManager.XmlResourceManagerFactory;
import net.itransformers.utils.JaxbMarshalar;
import net.itransformers.utils.XmlFormatter;
import net.itransformers.utils.XsltTransformer;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReportManager {
    static Logger logger = Logger.getLogger(ReportManager.class);

    private ReportGeneratorType reportGenerator;
    private String scriptPath;
    private File projectPath;
    private String xsltTransformator;

    public ReportManager(ReportGeneratorType reportGenerator, String scriptPath, File projectPath,
            String xsltTransformator) {
        this.reportGenerator = reportGenerator;
        this.scriptPath = scriptPath;
        this.projectPath = projectPath;
        this.xsltTransformator = xsltTransformator;
    }

    public StringBuffer reportExecutor(File postDiscoveryPath, Map<String, Object> params)
            throws ParserConfigurationException, SAXException, IOException {

        List<ReportEntryType> reportEnties = reportGenerator.getReportEntry();
        StringBuffer sb = new StringBuffer();
        String deviceType = (String) params.get("deviceType");
        String deviceName = (String) params.get("deviceName");
        File postDiscoveryNodeFolder = new File(postDiscoveryPath, (String) params.get("deviceName"));
        if (!postDiscoveryNodeFolder.exists()) {
            postDiscoveryNodeFolder.mkdir();
        }

        if (params.get("port") instanceof String) {
            params.put("port", Integer.parseInt((String) params.get("port")));
        }
        if (params.get("retries") instanceof String) {
            params.put("retries", Integer.parseInt((String) params.get("retries")));

        }

        for (ReportEntryType reportEntry : reportEnties) {
            String reportName = reportEntry.getName();
            File postDiscoveryReportOutput = new File(
                    postDiscoveryNodeFolder + File.separator + reportName + ".xml");

            logger.debug("Report id: " + reportName + " " + reportEntry.getDeviceType() + " "
                    + reportEntry.getDeviceName() + "with params" + params.toString());
            if (reportEntry.getDeviceType().equals(deviceType)) {

                sb.append("<?xml version=\"1.0\"?>\n");

                // sb.append("<report name=\""+reportEntry.getName()+"\" " + "deviceType=\""+deviceType+"\" "+ "deviceName=\""+deviceName+"\">");
                sb.append("<report>\n");
                List<CommandType> commands = reportEntry.getCommand();
                List<CommandDescriptorType> commandDescriptors = reportGenerator.getCommandDescriptor();

                for (CommandDescriptorType commandDescriptor : commandDescriptors) {

                    if (commandDescriptor.getDeviceType().equals(deviceType)) {
                        LoginScriptType loginScript = commandDescriptor.getLoginScript();
                        LogoutScriptType logoutScript = commandDescriptor.getLogoutScript();
                        SendCommandScriptType sendCommandScript = commandDescriptor.getSendCommandScript();

                        try {
                            Expect4GroovyScriptLauncher launcher = new Expect4GroovyScriptLauncher();
                            logger.debug(
                                    "Launch connection to :" + deviceName + " with params " + params.toString());
                            logger.debug(
                                    "Script path = " + scriptPath + " |login script " + loginScript.getValue());

                            Map<String, Object> loginResult = launcher.open(
                                    new String[] { scriptPath + File.separator }, loginScript.getValue(), params);

                            int loginresult = (Integer) loginResult.get("status");

                            if (loginresult == 2) {
                                logger.debug(loginResult);
                                return null;
                            }

                            List<CommandType> commandDescriptorCommands = commandDescriptor.getCommand();

                            for (CommandType descriptorCommand : commandDescriptorCommands) {

                                for (CommandType command : commands) {

                                    if (descriptorCommand.getName().equals(command.getName())) {
                                        String evalScriptName = descriptorCommand.getEvalScript();
                                        String commandString = descriptorCommand.getSendCommand();
                                        File script = null;
                                        Map<String, Object> result = null;

                                        if (evalScriptName != null) {
                                            script = new File(scriptPath, evalScriptName);
                                            HashMap<String, Object> scriptParams = new HashMap<>();
                                            scriptParams.put("command", commandString);
                                            scriptParams.put("evalScript", evalScriptName);
                                            result = launcher.sendCommand(sendCommandScript.getValue(),
                                                    scriptParams);

                                            Map<String, Object> evalData = (Map<String, Object>) result
                                                    .get("reportResult");
                                            if (evalData != null) {
                                                for (String key : evalData.keySet()) {
                                                    sb.append("\n\t<entry>\n");
                                                    sb.append("\t\t<AuditRule>" + key + "</AuditRule>" + "\n");
                                                    Map<String, Map<String, Integer>> keyMap = (Map<String, Map<String, Integer>>) evalData
                                                            .get(key);
                                                    if (keyMap.get("message") != null) {
                                                        sb.append("\t\t<Statement><![CDATA[" + keyMap.get("message")
                                                                + "]]></Statement>" + "\n");
                                                    }

                                                    if (keyMap.get("score") != null) {

                                                        sb.append("\t\t<Score>" + keyMap.get("score") + "</Score>"
                                                                + "\n");
                                                    }
                                                    sb.append("\t</entry>");
                                                    logger.debug(key + " " + evalData.get(key));
                                                }

                                            }
                                            // result = launcher.sendCommand(sendCommandScript.getValue(), commandString, null);
                                            if (result.get("commandResult") != null) {
                                                File postDiscoveryCommandOutput = new File(postDiscoveryNodeFolder
                                                        + File.separator + command.getName() + ".txt");
                                                try {
                                                    FileUtils.writeStringToFile(postDiscoveryCommandOutput,
                                                            result.get("commandResult").toString());
                                                } catch (IOException e) {
                                                    logger.info(e); //To change body of catch statement use File | Settings | File Templates.
                                                }
                                            }
                                        } else {
                                            HashMap<String, Object> scriptParams = new HashMap<>();
                                            scriptParams.put("command", commandString);
                                            result = launcher.sendCommand(sendCommandScript.getValue(),
                                                    scriptParams);

                                            if (result.get("commandResult") != null) {
                                                File postDiscoveryCommandOutput = new File(postDiscoveryNodeFolder
                                                        + File.separator + command.getName() + ".txt");
                                                try {
                                                    FileUtils.writeStringToFile(postDiscoveryCommandOutput,
                                                            result.get("commandResult").toString());
                                                } catch (IOException e) {
                                                    logger.info(e); //To change body of catch statement use File | Settings | File Templates.
                                                }
                                            }

                                        }

                                    }

                                }
                            }

                            launcher.close(logoutScript.getValue());
                        } catch (ResourceException e) {
                            logger.info(e); //To change body of catch statement use File | Settings | File Templates.
                        } catch (ScriptException e) {
                            logger.info(e); //To change body of catch statement use File | Settings | File Templates.
                            //To change body of catch statement use File | Settings | File Templates.
                        }
                    }

                }
                sb.append("\n</report>");
                try {
                    String report = new XmlFormatter().format(sb.toString());

                    ByteArrayOutputStream finalReport = generateTableReport(
                            new ByteArrayInputStream(report.getBytes()));
                    FileUtils.writeStringToFile(postDiscoveryReportOutput, finalReport.toString());
                } catch (IOException e) {
                    logger.info(e); //To change body of catch statement use File | Settings | File Templates.
                }

            }
        }

        return sb;
    }

    public static void main(String[] args) throws IOException {

        File projectDir = new File(".");
        File scriptPath = new File("postDiscoverer/src/main/resources/postDiscoverer/conf/groovy/");

        ResourceManagerFactory resourceManagerFactory = new XmlResourceManagerFactory(
                "iDiscover/resourceManager/xmlResourceManager/src/main/resources/xmlResourceManager/conf/xml/resource.xml");
        Map<String, String> resourceManagerParams = new HashMap<>();
        resourceManagerParams.put("projectPath", projectDir.getAbsolutePath());
        ResourceManager resourceManager = resourceManagerFactory.createResourceManager("xml",
                resourceManagerParams);

        Map<String, String> params = new HashMap<String, String>();
        params.put("protocol", "telnet");
        params.put("deviceName", "R1");
        params.put("deviceType", "CISCO");
        params.put("address", "10.17.1.5");
        params.put("port", "23");

        ResourceType resource = resourceManager.findFirstResourceBy(params);
        List connectParameters = resource.getConnectionParams();

        for (int i = 0; i < connectParameters.size(); i++) {
            ConnectionParamsType connParamsType = (ConnectionParamsType) connectParameters.get(i);

            String connectionType = connParamsType.getConnectionType();
            if (connectionType.equalsIgnoreCase(params.get("protocol"))) {

                for (ParamType param : connParamsType.getParam()) {
                    params.put(param.getName(), param.getValue());
                }

            }
        }

        File postDiscoveryConfing = new File(
                projectDir + "/postDiscoverer/src/main/resources/postDiscoverer/conf/xml/reportGenerator.xml");
        if (!postDiscoveryConfing.exists()) {
            System.out.println("File missing: " + postDiscoveryConfing.getAbsolutePath());
            return;
        }

        ReportGeneratorType reportGenerator = null;

        FileInputStream is = new FileInputStream(postDiscoveryConfing);
        try {
            reportGenerator = JaxbMarshalar.unmarshal(ReportGeneratorType.class, is);
        } catch (JAXBException e) {
            logger.info(e); //To change body of catch statement use File | Settings | File Templates.
        } finally {
            is.close();
        }

        ReportManager reportManager = new ReportManager(reportGenerator, scriptPath.getPath(), projectDir,
                "postDiscoverer/conf/xslt/table_creator.xslt");
        StringBuffer report = null;

        HashMap<String, Object> groovyExecutorParams = new HashMap<String, Object>();

        for (String s : params.keySet()) {
            groovyExecutorParams.put(s, params.get(s));
        }

        try {
            report = reportManager.reportExecutor(
                    new File("/Users/niau/Projects/Projects/netTransformer10/version1/post-discovery"),
                    groovyExecutorParams);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        if (report != null) {
            System.out.println(report.toString());

        } else {
            System.out.println("Report generation failed!");

        }
    }

    private ByteArrayOutputStream generateTableReport(ByteArrayInputStream inputStream) {
        XsltTransformer transformer = new XsltTransformer();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ByteArrayOutputStream reportOutputStream = new ByteArrayOutputStream();

        try {
            transformer.transformXML(inputStream, xsltTransformator, reportOutputStream, null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return reportOutputStream;
    }
}