org.squale.squalix.tools.ruleschecking.RulesCheckingTask.java Source code

Java tutorial

Introduction

Here is the source code for org.squale.squalix.tools.ruleschecking.RulesCheckingTask.java

Source

/**
 * Copyright (C) 2008-2010, Squale Project - http://www.squale.org
 *
 * This file is part of Squale.
 *
 * Squale is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or any later version.
 *
 * Squale 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 Lesser General Public License
 * along with Squale.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.squale.squalix.tools.ruleschecking;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.squale.jraf.commons.exception.JrafDaoException;
import org.squale.squalecommon.daolayer.result.MeasureDAOImpl;
import org.squale.squalecommon.daolayer.rulechecking.CheckstyleRuleSetDAOImpl;
import org.squale.squalecommon.enterpriselayer.businessobject.component.parameters.ListParameterBO;
import org.squale.squalecommon.enterpriselayer.businessobject.component.parameters.ParametersConstants;
import org.squale.squalecommon.enterpriselayer.businessobject.component.parameters.StringParameterBO;
import org.squale.squalecommon.enterpriselayer.businessobject.result.rulechecking.CheckstyleTransgressionBO;
import org.squale.squalecommon.enterpriselayer.businessobject.rulechecking.checkstyle.CheckstyleRuleSetBO;
import org.squale.squalecommon.util.file.FileUtility;
import org.squale.squalix.core.AbstractTask;
import org.squale.squalix.core.TaskData;
import org.squale.squalix.core.TaskException;
import org.squale.squalix.core.exception.ConfigurationException;
import org.squale.squalix.util.buildpath.BuildProjectPath;

/**
 * Excute le rulesChecking sur un sous-projet grace au connecteur rulesChecking<code>rulesCheckingFacade<code>.<br>
 * Si aucun fichier de configuration rulesChecking n'est spcifier dans les paramtres du sous projet,<br>
 * elle prend celui par dfaut(stock sur le serveur)
 * 
 * @author sportorico
 */

public class RulesCheckingTask extends AbstractTask {

    /**
     * Logger
     */
    private static final Log LOGGER = LogFactory.getLog(RulesCheckingTask.class);

    /**
     * Constructeur par defaut
     */
    public RulesCheckingTask() {
        mName = "RulesCheckingTask";
    }

    /**
     * L'analyse complte consiste en : <ul> <li>lancement du connecteur rulesChecking</li> <li>recupration des
     * resultats gners par rulesChecking</li> <li>Persistance des beans</li> </ul>
     * 
     * @throws RulesCheckingException Si un problme d'excution apparat.
     * @throws JrafDaoException Si un problme d'excution apparat.
     * @throws IOException Si un problme d'excution apparat.
     * @throws RulesCheckingConnectorException Si un problme d'excution apparat.
     * @throws ConfigurationException si erreur
     * @throws FileNotFoundException si erreur
     */
    private void analyze() throws JrafDaoException, RulesCheckingException, FileNotFoundException, IOException,
            RulesCheckingConnectorException, ConfigurationException {
        LOGGER.info(RulesCheckingMessages.getString("logs.analyzing") + mProject.getParent().getName() + " - "
                + mProject.getName());
        // On rcupre le nom du ruleset  appliquer
        StringParameterBO param = (StringParameterBO) getProject()
                .getParameter(ParametersConstants.CHECKSTYLE_RULESET_NAME);
        if (param == null) {
            String message = RulesCheckingMessages.getString("exception.rulesChecking.parameter.missing");
            // On affiche un warning sans lancer d'exception, la tche ne sera pas excute.
            initError(message);
            LOGGER.warn(message);
            // Les paramtres sont mal configurs, on annule la tche
            mStatus = CANCELLED;
        } else {
            CheckstyleRuleSetBO versionBo = CheckstyleRuleSetDAOImpl.getInstance().getLastVersion(getSession(),
                    param.getValue());
            // On recupre la version du fichier de configuration checkstyle rferentile  utiliser
            // Cas peu probable si la configuration est mal faite
            if (versionBo == null) {
                throw new RulesCheckingException(
                        RulesCheckingMessages.getString("exception.rulesChecking.version.unfound"));
            }
            // On rcupre la version de java
            StringParameterBO javaVersion = (StringParameterBO) getProject()
                    .getParameter(ParametersConstants.DIALECT);
            if (javaVersion == null) {
                throw new RulesCheckingException(
                        RulesCheckingMessages.getString("exception.rulesChecking.dialect.unfound"));
            }
            // On ne calcule pas les transgressions si aucune rgle n'est dfinie
            if (versionBo.getRules().size() > 0) {
                CheckstyleTransgressionBO transgression = ckeck(versionBo, javaVersion.getValue());
                if (null != transgression) {
                    transgression.setAudit(getAudit());
                    transgression.setTaskName(getName());
                    transgression.setComponent(getProject());
                    MeasureDAOImpl.getInstance().create(getSession(), transgression);
                } else {
                    throw new RulesCheckingException(RulesCheckingMessages.getString("exception.during.audit"));
                }
            }
        }
    }

    /**
     * Recupre les paramtres checkstyle du projet; Fait appel au connecteur et recupre l'ensemble des violations
     * gnres par le connector checkstyle.
     * 
     * @param pVersion La version du fichier de configuration
     * @param pJavaVersion la version de java
     * @return la liste des transgressions
     * @throws IOException si l'analyse ne s'est pas droule correctement
     * @throws RulesCheckingConnectorException si l'analyse ne s'est pas droule correctement
     * @throws ConfigurationException si erreur
     * @throws FileNotFoundException si erreur
     */
    public CheckstyleTransgressionBO ckeck(CheckstyleRuleSetBO pVersion, String pJavaVersion)
            throws IOException, RulesCheckingConnectorException, FileNotFoundException, ConfigurationException {
        /*
         * Permet de prciser le pays et le language de l'ordi ... cela permet de contourner un problme de messages
         * avec Checkstyle 3.5
         */
        Locale bufferLocal = Locale.getDefault(); // memoriser la valeur courante
        try {
            Locale.setDefault(Locale.US); // changer cette valeur avec celle des USA

            File file = FileUtility.byteToFile(pVersion.getValue());
            // Configuration Checkstyle
            CheckstyleConfiguration config = new CheckstyleConfiguration();
            config.parse(new FileInputStream("config/checkstyle-config.xml"));
            // rcupration des sources du project
            List srcs = ((ListParameterBO) mProject.getParameters().getParameters()
                    .get(ParametersConstants.SOURCES)).getParameters();
            List paths = BuildProjectPath.buildProjectPath((String) mData.getData(TaskData.VIEW_PATH), srcs);
            // On rcupre les sources qui peuvent tre analyses
            List includedFileNames = org.squale.squalix.util.file.FileUtility.getIncludedFiles(
                    (String) mData.getData(TaskData.VIEW_PATH), paths,
                    (ListParameterBO) mProject.getParameter(ParametersConstants.INCLUDED_PATTERNS),
                    (ListParameterBO) mProject.getParameter(ParametersConstants.EXCLUDED_PATTERNS), null,
                    new String[] { ".java" });

            File tempDir = new File(config.getTempSourceDir());
            tempDir.mkdir();

            for (Object fl : includedFileNames) {
                File fileToCopy = new File(fl.toString());
                File vPath = new File((String) mData.getData(TaskData.VIEW_PATH));
                String path = fileToCopy.getCanonicalPath().replace(vPath.getCanonicalPath(),
                        tempDir.getCanonicalPath());
                File destFile = new File(path);
                FileUtils.copyFile(fileToCopy, destFile);
            }

            CheckStyleProcess process = new CheckStyleProcess(new File(config.getJarDirectory()),
                    new File(config.getReportDirectory()), pJavaVersion);
            File report = process.analyseSources(file, tempDir, "checkstyle-report" + getProject().getId());
            CheckstyleReportParser parser = new CheckstyleReportParser(tempDir.getAbsolutePath());
            CheckStylePersistor persistor = new CheckStylePersistor(pVersion);
            parser.parse(new FileInputStream(report), persistor);
            // On rcupre le transgression
            CheckstyleTransgressionBO transgression = persistor.computeTransgression();

            // positionne les donnes sur la taille du file System
            ArrayList<Object[]> listDirectory = new ArrayList<Object[]>();
            Object[] obj1 = { config.getReportDirectory(), Boolean.FALSE };
            Object[] obj2 = { tempDir, Boolean.FALSE };
            listDirectory.add(obj1);
            listDirectory.add(obj2);
            affectFileSystemSize(listDirectory);

            // Destruction du rapport
            report.delete();
            FileUtils.deleteDirectory(tempDir);
            return transgression;
        } finally {
            Locale.setDefault(bufferLocal); // remettre  la valeur initiale
        }
    }

    /**
     * Excute la mthode init(), puis une analyse complte, et enfin la mthode close().
     * 
     * @throws TaskException en cas de problmes lis  la base
     */
    public void execute() throws TaskException {
        try {
            analyze();
        } catch (Exception e) {
            throw new TaskException(e);
        }
    }

    /**
     * Acces au nom de la tche CheckStyleTask
     * 
     * @return le nom de la tche
     */
    public String getName() {
        return mName;
    }

}