Child pages
  • How to create a custom export

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagegroovy
themeEmacs
linenumberstrue
collapsetrue
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import org.apache.poi.xssf.streaming.SXSSFWorkbook
import org.apache.poi.xssf.usermodel.XSSFWorkbook

class LevelEToExcel {
    /*
    Firs method used when the groovy script is executed
     */
    static void main(String[] args) {

        //Find the script GroovyScriptUtils.groovy defined in form.xml or the first parameter in CLI command
        def commonUtils = getGroovyScriptUtils(args)
        //transforms all parameters into Map<String,String>
        def mapArgs = commonUtils.argsParsing(args, '-')

        def toExcelEngine = new LevelEToExcelEngine()
        //Call the method to generate export
        toExcelEngine.generateExcelFinalFile(commonUtils, mapArgs)
    }

    /*
    Load GroovyScriptUtils.groovy in Classpath and return an instance of object
     */
    private static Object getGroovyScriptUtils(args) {
        def commonSrcipt
        args.each {
            if (it.contains('GroovyScriptUtils.groovy')) {
                commonSrcipt = new GroovyClassLoader().parseClass(it as File).newInstance()
            }
        }
        return commonSrcipt
    }
}

class LevelEToExcelEngine {

    def static IMPORT_SCRIPT = '-importScript'
    def static TEMPLATE = '-template'
    def static EXCEL_UTILS_SCRIPT = '-excelUtilsScript'
    def commonUtil
    def excelUtil
    def squoreApiUtils

    def generateExcelFinalFile(commonUtil, mapArgs) {
        println("[INFO] Start processing Excel !")
        this.commonUtil = commonUtil
        try {

            //Final File name
            def outputName = "highlightsModels.xlsx";
            //The file in ${SquorePath}addons/exports/Shared/exports_utils.groovy will be transformed in Groovy Class
            def exportUtil = commonUtil.getGroovyClass(mapArgs.get(IMPORT_SCRIPT))

            //The file ${SquorePath}addons/shared/ExcelUtils.groovy will be transformed in Groovy Class
            excelUtil = commonUtil.getGroovyClass(mapArgs.get(EXCEL_UTILS_SCRIPT))

            //The file  ${SquorePath}addons/shared/SquoreApiUtils.groovy will be transformed in Groovy Class
            squoreApiUtils = commonUtil.getGroovyClass(mapArgs.get(exportUtil.SQUORE_API_UTILS))

            //The output directory where the data.properties file will be created
            commonUtil.initGlobalData(mapArgs.get(exportUtil.OUTPUT_DIRECTORY));

            //Final file in data.properties
            commonUtil.addGlobalData("filename", outputName, mapArgs.get(exportUtil.OUTPUT_DIRECTORY));

            //Init de output file path and name
            def fnout = mapArgs.get(exportUtil.OUTPUT_DIRECTORY) + "/" + outputName;

            commonUtil.removeFileIfExits(fnout)

            //Check if a template is configured
            def templatePath = mapArgs.get(TEMPLATE)

            //Defined the API URL
            def apiUrl = mapArgs.get(exportUtil.SERVER_URL) + '/api'

            //Is the auto-generated token for on the fly authentification to the API REST
            def token =  mapArgs.get(exportUtil.TOKEN)

            //Api URL that will return the list of model projects
            def group = commonUtil.isEmptyString(mapArgs.get(exportUtil.GROUP)) ? '' : '?group=' + URLEncoder.encode(mapArgs.get(exportUtil.GROUP), "UTF-8")
            def modelProjectsUrl = apiUrl + '/models/' + mapArgs.get(exportUtil.ID_MODEL) + '/projects'+group

            //Api Rest Service call to get model context information
            def modelFull = squoreApiUtils.getObjectByApi(Model.class, apiUrl + '/models/' + mapArgs.get(exportUtil.ID_MODEL),token)

            //Api Rest Service call to get the list of model projects can be filtered by group
            def model = squoreApiUtils.getObjectByApi(Model.class, modelProjectsUrl,token)

            modelFull.setProjects(model.projects)

            //Create Excel Sheets by POI library
            def workbook = buildWorkbook(modelFull, templatePath, apiUrl, token)

            //generate the output excel file
            def outputStream = null;
            try {
                outputStream = new FileOutputStream(fnout);
                workbook.write(outputStream);
            } finally {
                outputStream?.close()
            }
        } catch (Exception e) {
            System.err.println("[ERROR] An error occurred " + e.getMessage() + " stackTrace " + e.getStackTrace())
        }
        println("[INFO] End processing !")
    }


    private def buildWorkbook(model, templatePath, apiUrl, token) {
        //Init workbook
        def workbook = excelUtil.getWorkbook(templatePath)

        def sheetNum = 0;
        def helper = workbook.getCreationHelper();

        //cell style for hyperlinks
        //by default hyperlinks are blue and underlined
        def hlink_style = excelUtil.getHlinkStyle(workbook);

        //Create the firs Sheet Context if there is a template file defined
        contextSheet(templatePath, workbook, model, apiUrl + '/versions/', token)

        workbook = new SXSSFWorkbook(workbook, 10000);
        helper = workbook.getCreationHelper();
        def styles = [:];

        model.projects.each { project ->
            def jsonQuery = '{"artefactTypes":["FILES"],"columns":[{"type":"MEASURE","id":"LC"}],"filters":[{"type":"indicator","id":"ANALYTICS","data":{"checked":["LEVELE"]}}]}'
            def highlightUrl = apiUrl + '/artefacts/' + project.artefactId + '/query'
            def high = squoreApiUtils.getObjectByApiAndQuery(Highlight.class, highlightUrl, jsonQuery, token)
            sheetNum++;
            workbook.createSheet(project.name).with { sheet ->
                excelUtil.createHightlightSheet(commonUtil, workbook, sheet, project, high, helper, hlink_style, styles)
            }
        }
        return workbook;
    }

    /*
    Create the first Sheet that contains model context. It's base on template.xlsx
     */
    private void contextSheet(templatePath, XSSFWorkbook workbook, model, apiUrlVersion, token) {
        if (templatePath) {
            // The first tab of excel file
            def rowNum = 11;
            workbook.getSheetAt(0).with { sheet ->
                getRow(5).with { row ->
                    createCell(3).with { cell ->
                        setCellValue(model.name)
                    }
                }
                def projectCellStyle = getRow(11).getCell(1).getCellStyle()
                model.projects.each { project ->
                    def version = squoreApiUtils.getObjectByApi(Version.class, apiUrlVersion + project.versionId, token)
                    createRow(rowNum).with { row ->
                        excelUtil.applyStyleforCell(row, 3, projectCellStyle)
                        getCell(2).with {
                            cellValue = 'Name'
                        }
                        createCell(3).with {
                            setCellValue(project.name)
                        }
                    }
                    rowNum++
                    createRow(rowNum).with { row ->
                        excelUtil.applyStyleforCell(row, 3, projectCellStyle)
                        getCell(2).with {
                            cellValue = 'Version'
                        }
                        createCell(3).with {
                            setCellValue(version.name)
                        }
                    }
                    rowNum++
                    createRow(rowNum).with { row ->
                        excelUtil.applyStyleforCell(row, 2, projectCellStyle)
                    }
                    rowNum++
                }
            }
        }
    }
}

/*
List of all Objects needed to transform Json result
 */
@JsonIgnoreProperties(ignoreUnknown = true)
class Project {
    String name
    int id
    String artefactId
    int versionId
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Model {
    String name
    String externalId
    String id
    List<Project> projects
}

class Values {
    Object value
    String formatted
    Object[] bgColor
}

class Columns {
    String externalId
    String id
    String name
    String description
    String kind
    String format
    String suffix
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Highlight {
    String name
    List<Columns> columns
    List<Artefact> artefacts
    boolean hidePath
    boolean hideRating   
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Artefact {
    String name
    String path
    String id
    String url
    List<Values> values
    Type type
    Level level
	String viewPath
}

class Type {
    String name;
    String externalId
    String id
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Version {
    int id
    String name
}

class Level {
    String id
    String icon
    Object[] color
    String mnemonic
}

...