<|start_filename|>src/groovy/org/restapidoc/utils/BuildPathMap.groovy<|end_filename|>
package org.restapidoc.utils

import grails.util.Holders
import org.codehaus.groovy.grails.commons.UrlMappingsArtefactHandler
import org.codehaus.groovy.grails.web.mapping.UrlMapping
import org.codehaus.groovy.grails.web.mapping.reporting.AnsiConsoleUrlMappingsRenderer

import java.util.regex.Pattern

/**
 * Thanks to URL MAPPING files, build a map that helps to get path/verb for a specific controller action
 *
 * Created by lrollus on 1/10/14.
 */
class BuildPathMap extends AnsiConsoleUrlMappingsRenderer {

    /**
     * Build a MappingRules (map controller.action => path + verb) thanks to url mapping
     */
    MappingRules build(def grailsApplication) {

        def mappings = Holders.getGrailsApplication().getArtefacts(UrlMappingsArtefactHandler.TYPE)
        def evaluator = Holders.getGrailsApplication().classLoader.loadClass("org.codehaus.groovy.grails.web.mapping.DefaultUrlMappingEvaluator").newInstance(Holders.getGrailsApplication().classLoader.loadClass('org.springframework.mock.web.MockServletContext').newInstance())
        def allMappings = []

        for (m in mappings) {
            List grailsClassMappings
            if (Script.isAssignableFrom(m.getClazz())) {
                grailsClassMappings = evaluator.evaluateMappings(m.getClazz())
            } else {
                grailsClassMappings = evaluator.evaluateMappings(m.getMappingsClosure())
            }
            allMappings.addAll(grailsClassMappings)
        }
        return createUrlMappingMap(allMappings, grailsApplication)

    }

    private MappingRules createUrlMappingMap(List<UrlMapping> urlMappings, def grailsApplication) {

        MappingRules rules = new MappingRules()

        final mappingsByController = urlMappings.groupBy { UrlMapping mapping -> mapping.controllerName }
        def longestMapping = establishUrlPattern(urlMappings.max { UrlMapping mapping -> establishUrlPattern(mapping, false).length() }, false).length() + 5
        final controllerNames = mappingsByController.keySet().sort()

        for (controller in controllerNames) {
            final controllerUrlMappings = mappingsByController.get(controller)
            for (UrlMapping urlMapping in controllerUrlMappings) {
                def urlPattern = establishUrlPattern(urlMapping, isAnsiEnabled, longestMapping)

                if (urlMapping?.actionName) {
                    // urlMapping can be either a string or a closure that returns the result
                    if (urlMapping?.actionName instanceof String) {
                        rules.addRule(controller.toString(), urlMapping.actionName.toString(), cleanString(urlPattern), urlMapping.httpMethod, grailsApplication.mergedConfig.grails.plugins.restapidoc.defaultFormat)
                    } else {
                        urlMapping?.actionName.each { actName ->
                            urlPattern = urlPattern.replace("\${", "{") //replace ${format} with {format}
                            rules.addRule(controller.toString(), actName.value, cleanString(urlPattern), actName.key, grailsApplication.mergedConfig.grails.plugins.restapidoc.defaultFormat)
                        }
                    }
                }
            }

        }

        return rules
    }
    //string from url mapping are dirty (escape char,...)
    public static String cleanString(String dirtyString) {

        Pattern escapeCodePattern = Pattern.compile(
                "\u001B"        // escape code
                        + "\\["
                        + "\\d+"
                        + "(;\\d+)*"
                        + "[@-~]"
                        + "|\\\$" // Url mapping returns parameters formatted like this : ${parameter}.
        );
        escapeCodePattern.matcher(dirtyString).replaceAll("");

    }
}


<|start_filename|>src/groovy/org/restapidoc/JSONUtils.groovy<|end_filename|>
package org.restapidoc

import grails.converters.JSON
import org.jsondoc.core.pojo.ApiBodyObjectDoc
import org.jsondoc.core.pojo.ApiDoc
import org.jsondoc.core.pojo.ApiHeaderDoc
import org.jsondoc.core.pojo.ApiObjectDoc
import org.restapidoc.pojo.*

/**
 * Created by stevben on 16/12/13.
 */
class JSONUtils {

    static def registerMarshallers() {

        JSON.registerObjectMarshaller(ApiObjectDoc) {
            def returnArray = [:]
            println "ApiObjectDoc"
            returnArray['jsondocId'] = it.jsondocId
            returnArray['description'] = it.description
            returnArray['name'] = it.name
            returnArray['fields'] = it.fields
            return returnArray
        }
        JSON.registerObjectMarshaller(RestApiObjectDoc) {
            def returnArray = [:]
            returnArray['jsondocId'] = it.jsondocId
            returnArray['description'] = it.description
            returnArray['name'] = it.name
            returnArray['fields'] = it.fields
            return returnArray
        }

        JSON.registerObjectMarshaller(ApiDoc) {
            def returnArray = [:]
            returnArray['jsondocId'] = it.jsondocId
            returnArray['name'] = it.name
            returnArray['description'] = it.description
            returnArray['methods'] = it.methods
            return returnArray
        }


        JSON.registerObjectMarshaller(RestApiResponseObjectDoc) {
            def returnArray = [:]
            returnArray['jsondocId'] = it.jsondocId
            returnArray['mapKeyObject'] = it.mapKeyObject
            returnArray['mapValueObject'] = it.mapValueObject
            returnArray['object'] = it.object
            return returnArray
        }



        JSON.registerObjectMarshaller(RestApiParamDoc) {
            def returnArray = [:]
            returnArray['jsondocId'] = it.jsondocId
            returnArray['name'] = it.name
            returnArray['description'] = it.description
            returnArray['type'] = it.type
            returnArray['required'] = it.required
            returnArray['allowedvalues'] = it.allowedvalues
            returnArray['format'] = it.format
            return returnArray
        }




        JSON.registerObjectMarshaller(RestApiObjectFieldDoc) {
            def returnArray = [:]
            returnArray['jsondocId'] = it.jsondocId
            returnArray['name'] = it.name
            returnArray['description'] = it.description
            returnArray["type"] = it.type
            returnArray["multiple"] = it.multiple
            returnArray["description"] = it.description
            returnArray["format"] = it.format
            returnArray["allowedvalues"] = it.allowedvalues
            returnArray["mandatory"] = it.mandatory
            returnArray["useForCreation"] = it.useForCreation
            returnArray["defaultValue"] = it.defaultValue
            returnArray["presentInResponse"] = it.presentInResponse
            return returnArray
        }

        JSON.registerObjectMarshaller(ApiHeaderDoc) {
            def returnArray = [:]
            returnArray['jsondocId'] = it.jsondocId
            returnArray['name'] = it.name
            returnArray['description'] = it.description
            return returnArray
        }


        JSON.registerObjectMarshaller(RestApiMethodDoc) {
            def returnArray = [:]
            returnArray['jsondocId'] = it.jsondocId
            returnArray['path'] = it.path
            returnArray['description'] = it.description
            if (it.restVerb == RestApiVerb.GET)
                returnArray['verb'] = "GET"
            if (it.restVerb == RestApiVerb.PUT)
                returnArray['verb'] = "PUT"
            if (it.restVerb == RestApiVerb.POST)
                returnArray['verb'] = "POST"
            if (it.restVerb == RestApiVerb.DELETE)
                returnArray['verb'] = "DELETE"
            if (it.restVerb == RestApiVerb.PATCH)
                returnArray['verb'] = "PATCH"
            if (it.restVerb == RestApiVerb.ALL)
                returnArray['verb'] = "*"
            returnArray['produces'] = it.produces
            returnArray['consumes'] = it.consumes
            returnArray['headers'] = it.headers
            returnArray['pathparameters'] = it.pathparameters
            returnArray['queryparameters'] = it.queryparameters
            returnArray['bodyobject'] = it.bodyobject
            returnArray['response'] = it.response
            returnArray['apierrors'] = it.apierrors
            returnArray['methodName'] = it.methodName
            return returnArray
        }

        JSON.registerObjectMarshaller(RestApiErrorDoc) {
            def returnArray = [:]
            returnArray['jsondocId'] = it.jsondocId
            returnArray['code'] = it.code
            returnArray['description'] = it.description
            return returnArray
        }

        JSON.registerObjectMarshaller(ApiBodyObjectDoc) {
            def returnArray = [:]

            returnArray['jsondocId'] = it.jsondocId
            returnArray['object'] = it.getObject()
            returnArray['multiple'] = it.getMultiple()
            returnArray['mapKeyObject'] = it.getMapKeyObject()
            returnArray['mapValueObject'] = it.getMapValueObject()
            returnArray['map'] = it.getMap()

            return returnArray
        }


    }
}
