You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by lb...@apache.org on 2019/02/15 13:57:59 UTC

[camel-k] branch master updated: fix rest dsl generation

This is an automated email from the ASF dual-hosted git repository.

lburgazzoli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel-k.git


The following commit(s) were added to refs/heads/master by this push:
     new 0024079  fix rest dsl generation
0024079 is described below

commit 0024079cc514923bfb55d0001d0f2054d0ab460c
Author: lburgazzoli <lb...@gmail.com>
AuthorDate: Fri Feb 15 11:47:16 2019 +0100

    fix rest dsl generation
---
 deploy/resources.go                   |  54 ++++++++-------
 pkg/trait/catalog.go                  |  12 ++--
 pkg/trait/{rest.go => rest-dsl.go}    | 125 +++++++++++++++++++++++++++++-----
 pkg/util/maven/maven_project_types.go |  13 ++--
 pkg/util/maven/maven_test.go          |   3 +
 5 files changed, 156 insertions(+), 51 deletions(-)

diff --git a/deploy/resources.go b/deploy/resources.go
index dd46d97..b9094de 100644
--- a/deploy/resources.go
+++ b/deploy/resources.go
@@ -4178,29 +4178,6 @@ spec:
   version: 2.23.1
 
 `
-	Resources["cr-example.yaml"] =
-		`
-apiVersion: camel.apache.org/v1alpha1
-kind: Integration
-metadata:
-  name: example
-spec:
-  source:
-    content: |-
-      // This is Camel K Groovy example route
-
-      rnd = new Random()
-
-      from('timer:groovy?period=1s')
-          .routeId('groovy')
-          .setBody()
-              .constant('Hello Camel K!')
-          .process {
-              it.in.headers['RandomValue'] = rnd.nextInt()
-          }
-          .to('log:info?showHeaders=true')
-    name: routes.groovy
-`
 	Resources["crd-camel-catalog.yaml"] =
 		`
 apiVersion: apiextensions.k8s.io/v1beta1
@@ -4320,6 +4297,29 @@ spec:
       JSONPath: .status.context
 
 `
+	Resources["cr-example.yaml"] =
+		`
+apiVersion: camel.apache.org/v1alpha1
+kind: Integration
+metadata:
+  name: example
+spec:
+  source:
+    content: |-
+      // This is Camel K Groovy example route
+
+      rnd = new Random()
+
+      from('timer:groovy?period=1s')
+          .routeId('groovy')
+          .setBody()
+              .constant('Hello Camel K!')
+          .process {
+              it.in.headers['RandomValue'] = rnd.nextInt()
+          }
+          .to('log:info?showHeaders=true')
+    name: routes.groovy
+`
 	Resources["operator-deployment-kubernetes.yaml"] =
 		`
 apiVersion: apps/v1
@@ -4359,6 +4359,10 @@ spec:
                   fieldPath: metadata.namespace
             - name: OPERATOR_NAME
               value: "camel-k"
+            - name: POD_NAME
+              valueFrom:
+                fieldRef:
+                  fieldPath: metadata.name
           volumeMounts:
           - mountPath: /workspace
             name: camel-k-builder
@@ -4418,6 +4422,10 @@ spec:
                   fieldPath: metadata.namespace
             - name: OPERATOR_NAME
               value: "camel-k"
+            - name: POD_NAME
+              valueFrom:
+                fieldRef:
+                  fieldPath: metadata.name
 
 `
 	Resources["operator-role-binding-knative.yaml"] =
diff --git a/pkg/trait/catalog.go b/pkg/trait/catalog.go
index f38dc3b..82ca485 100644
--- a/pkg/trait/catalog.go
+++ b/pkg/trait/catalog.go
@@ -49,7 +49,7 @@ type Catalog struct {
 	tIstio            Trait
 	tEnvironment      Trait
 	tClasspath        Trait
-	tRest             Trait
+	tRestDsl          Trait
 }
 
 // NewCatalog creates a new trait Catalog
@@ -57,7 +57,7 @@ func NewCatalog(ctx context.Context, c client.Client) *Catalog {
 	catalog := Catalog{
 		L:                 log.Log.WithName("trait"),
 		tDebug:            newDebugTrait(),
-		tRest:             newRestTrait(),
+		tRestDsl:          newRestDslTrait(),
 		tKnative:          newKnativeTrait(),
 		tDependencies:     newDependenciesTrait(),
 		tDeployment:       newDeploymentTrait(),
@@ -91,7 +91,7 @@ func NewCatalog(ctx context.Context, c client.Client) *Catalog {
 func (c *Catalog) allTraits() []Trait {
 	return []Trait{
 		c.tDebug,
-		c.tRest,
+		c.tRestDsl,
 		c.tKnative,
 		c.tDependencies,
 		c.tDeployment,
@@ -120,7 +120,7 @@ func (c *Catalog) traitsFor(environment *Environment) []Trait {
 		return []Trait{
 			c.tGarbageCollector,
 			c.tDebug,
-			c.tRest,
+			c.tRestDsl,
 			c.tDependencies,
 			c.tImages,
 			c.tBuilder,
@@ -138,7 +138,7 @@ func (c *Catalog) traitsFor(environment *Environment) []Trait {
 		return []Trait{
 			c.tGarbageCollector,
 			c.tDebug,
-			c.tRest,
+			c.tRestDsl,
 			c.tDependencies,
 			c.tImages,
 			c.tBuilder,
@@ -156,7 +156,7 @@ func (c *Catalog) traitsFor(environment *Environment) []Trait {
 		return []Trait{
 			c.tGarbageCollector,
 			c.tDebug,
-			c.tRest,
+			c.tRestDsl,
 			c.tKnative,
 			c.tDependencies,
 			c.tImages,
diff --git a/pkg/trait/rest.go b/pkg/trait/rest-dsl.go
similarity index 52%
rename from pkg/trait/rest.go
rename to pkg/trait/rest-dsl.go
index 309c568..9d9e117 100644
--- a/pkg/trait/rest.go
+++ b/pkg/trait/rest-dsl.go
@@ -18,6 +18,8 @@ limitations under the License.
 package trait
 
 import (
+	"encoding/xml"
+	"errors"
 	"fmt"
 	"io/ioutil"
 	"os"
@@ -36,17 +38,17 @@ import (
 	"github.com/apache/camel-k/pkg/util/maven"
 )
 
-type restTrait struct {
+type restDslTrait struct {
 	BaseTrait `property:",squash"`
 }
 
-func newRestTrait() *restTrait {
-	return &restTrait{
-		BaseTrait: newBaseTrait("rest"),
+func newRestDslTrait() *restDslTrait {
+	return &restDslTrait{
+		BaseTrait: newBaseTrait("rest-dsl"),
 	}
 }
 
-func (t *restTrait) Configure(e *Environment) (bool, error) {
+func (t *restDslTrait) Configure(e *Environment) (bool, error) {
 	if t.Enabled != nil && !*t.Enabled {
 		return false, nil
 	}
@@ -64,7 +66,7 @@ func (t *restTrait) Configure(e *Environment) (bool, error) {
 	return false, nil
 }
 
-func (t *restTrait) Apply(e *Environment) error {
+func (t *restDslTrait) Apply(e *Environment) error {
 	if len(e.Integration.Spec.Resources) == 0 {
 		return nil
 	}
@@ -82,6 +84,12 @@ func (t *restTrait) Apply(e *Environment) error {
 			continue
 		}
 
+		tmpDir = path.Join(tmpDir, strconv.Itoa(i))
+		err := os.MkdirAll(tmpDir, os.ModePerm)
+		if err != nil {
+			return err
+		}
+
 		content := []byte(resource.Content)
 		if resource.Compression {
 			content, err = gzip.UncompressBase64(content)
@@ -93,21 +101,32 @@ func (t *restTrait) Apply(e *Environment) error {
 		in := path.Join(tmpDir, "openapi-spec.json")
 		out := path.Join(tmpDir, "openapi-dsl.xml")
 
-		if err := ioutil.WriteFile(in, content, 0644); err != nil {
+		err = ioutil.WriteFile(in, content, 0644)
+		if err != nil {
 			return err
 		}
 
 		opts := make([]string, 0, 4)
 		opts = append(opts, maven.ExtraOptions(e.Platform.Spec.Build.LocalRepository)...)
-		opts = append(opts, fmt.Sprintf("org.apache.camel.k:camel-k-maven-plugin:%s:generate-rest-xml", version.Version))
 		opts = append(opts, "-Dopenapi.spec="+in)
 		opts = append(opts, "-Ddsl.out="+out)
 
-		if err := maven.Run(tmpDir, opts...); err != nil {
+		project, err := t.generateProject(e)
+		if err != nil {
+			return err
+		}
+
+		err = maven.CreateStructure(tmpDir, project)
+		if err != nil {
+			return err
+		}
+
+		err = maven.Run(tmpDir, opts...)
+		if err != nil {
 			return err
 		}
 
-		content, err := ioutil.ReadFile(out)
+		content, err = ioutil.ReadFile(out)
 		if err != nil {
 			return err
 		}
@@ -121,16 +140,28 @@ func (t *restTrait) Apply(e *Environment) error {
 			content = c
 		}
 
-		name := fmt.Sprintf("%s-openapi-%03d", e.Integration.Name, i)
+		generatedContentName := fmt.Sprintf("%s-openapi-%03d", e.Integration.Name, i)
+		generatedSourceName := strings.TrimSuffix(resource.Name, filepath.Ext(resource.Name)) + ".xml"
+		generatedSources := make([]v1alpha1.SourceSpec, 0, len(e.Integration.Status.GeneratedSources))
+
+		if e.Integration.Status.GeneratedSources != nil {
+			//
+			// Filter out the previously generated source
+			//
+			for _, x := range e.Integration.Status.GeneratedSources {
+				if x.Name != generatedSourceName {
+					generatedSources = append(generatedSources, x)
+				}
+			}
+		}
 
 		//
-		// Add an additional source that references the previously
-		// created config map
+		// Add an additional source that references the config map
 		//
-		e.Integration.Status.GeneratedSources = append(e.Integration.Status.GeneratedSources, v1alpha1.SourceSpec{
+		generatedSources = append(generatedSources, v1alpha1.SourceSpec{
 			DataSpec: v1alpha1.DataSpec{
-				Name:        strings.TrimSuffix(resource.Name, filepath.Ext(resource.Name)) + ".xml",
-				ContentRef:  name,
+				Name:        generatedSourceName,
+				ContentRef:  generatedContentName,
 				Compression: resource.Compression,
 			},
 			Language: v1alpha1.LanguageXML,
@@ -146,7 +177,7 @@ func (t *restTrait) Apply(e *Environment) error {
 				APIVersion: "v1",
 			},
 			ObjectMeta: metav1.ObjectMeta{
-				Name:      name,
+				Name:      generatedContentName,
 				Namespace: e.Integration.Namespace,
 				Labels: map[string]string{
 					"camel.apache.org/integration": e.Integration.Name,
@@ -164,8 +195,68 @@ func (t *restTrait) Apply(e *Environment) error {
 			},
 		}
 
+		e.Integration.Status.GeneratedSources = generatedSources
 		e.Resources.Add(&cm)
 	}
 
 	return nil
 }
+
+func (t *restDslTrait) generateProject(e *Environment) (maven.Project, error) {
+	if e.CamelCatalog == nil {
+		return maven.Project{}, errors.New("unknown camel catalog")
+	}
+
+	p := maven.Project{
+		XMLName:           xml.Name{Local: "project"},
+		XMLNs:             "http://maven.apache.org/POM/4.0.0",
+		XMLNsXsi:          "http://www.w3.org/2001/XMLSchema-instance",
+		XsiSchemaLocation: "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd",
+		ModelVersion:      "4.0.0",
+		GroupID:           "org.apache.camel.k.integration",
+		ArtifactID:        "camel-k-red-dsl-generator",
+		Version:           version.Version,
+		Build: maven.Build{
+			DefaultGoal: "generate-resources",
+			Plugins: []maven.Plugin{
+				{
+					GroupID:    "org.apache.camel.k",
+					ArtifactID: "camel-k-maven-plugin",
+					Version:    version.Version,
+					Executions: []maven.Execution{
+						{
+							Phase: "generate-resources",
+							Goals: []string{
+								"generate-rest-xml",
+							},
+						},
+					},
+					Dependencies: []maven.Dependency{
+						{
+							GroupID:    "org.apache.camel",
+							ArtifactID: "camel-swagger-rest-dsl-generator",
+							Version:    e.CamelCatalog.Version,
+						},
+					},
+				},
+			},
+		},
+	}
+
+	//
+	// Repositories
+	//
+
+	p.Repositories = make([]maven.Repository, 0, len(e.Platform.Spec.Build.Repositories))
+
+	for i, r := range e.Platform.Spec.Build.Repositories {
+		repo := maven.NewRepository(r)
+		if repo.ID == "" {
+			repo.ID = fmt.Sprintf("repo-%03d", i)
+		}
+
+		p.Repositories = append(p.Repositories, repo)
+	}
+
+	return p, nil
+}
diff --git a/pkg/util/maven/maven_project_types.go b/pkg/util/maven/maven_project_types.go
index 74957b9..e95b484 100644
--- a/pkg/util/maven/maven_project_types.go
+++ b/pkg/util/maven/maven_project_types.go
@@ -36,6 +36,7 @@ type Project struct {
 	Dependencies         []Dependency         `xml:"dependencies>dependency,omitempty"`
 	Repositories         []Repository         `xml:"repositories>repository,omitempty"`
 	PluginRepositories   []Repository         `xml:"pluginRepositories>pluginRepository,omitempty"`
+	Build                Build                `xml:"build,omitempty"`
 }
 
 // Exclusion represent a maven's dependency exlucsion
@@ -77,15 +78,17 @@ type RepositoryPolicy struct {
 
 // Build --
 type Build struct {
-	Plugins []Plugin `xml:"plugins>plugin,omitempty"`
+	DefaultGoal string   `xml:"defaultGoal,omitempty"`
+	Plugins     []Plugin `xml:"plugins>plugin,omitempty"`
 }
 
 // Plugin --
 type Plugin struct {
-	GroupID    string      `xml:"groupId"`
-	ArtifactID string      `xml:"artifactId"`
-	Version    string      `xml:"version,omitempty"`
-	Executions []Execution `xml:"executions>execution,omitempty"`
+	GroupID      string       `xml:"groupId"`
+	ArtifactID   string       `xml:"artifactId"`
+	Version      string       `xml:"version,omitempty"`
+	Executions   []Execution  `xml:"executions>execution,omitempty"`
+	Dependencies []Dependency `xml:"dependencies>dependency,omitempty"`
 }
 
 // Execution --
diff --git a/pkg/util/maven/maven_test.go b/pkg/util/maven/maven_test.go
index ff2ce0d..3115f9e 100644
--- a/pkg/util/maven/maven_test.go
+++ b/pkg/util/maven/maven_test.go
@@ -75,6 +75,9 @@ const expectedPom = `<?xml version="1.0" encoding="UTF-8"?>
       </releases>
     </pluginRepository>
   </pluginRepositories>
+  <build>
+    <plugins></plugins>
+  </build>
 </project>`
 
 func TestPomGeneration(t *testing.T) {