diff --git a/.github/workflows/buildMain.yml b/.github/workflows/buildMain.yml index 027724b01..22b830531 100644 --- a/.github/workflows/buildMain.yml +++ b/.github/workflows/buildMain.yml @@ -3,6 +3,8 @@ name: CI on: push: branches: [ main ] + schedule: + - cron: "0 0 * * *" workflow_dispatch: inputs: @@ -46,7 +48,9 @@ jobs: repository: devonfw-tutorials/tutorials path: playbooks - - uses: actions/setup-node@v2-beta + - uses: actions/setup-node@v2 + with: + node-version: '12' - name: install TS run: npm install typescript @@ -55,12 +59,17 @@ jobs: run: npm install - name: run buildRun.sh ${{ github.event.inputs.logLevel }} + env: + # remove maven download logs as it might cause random build failures: https://stackoverflow.com/a/66801171 + MAVEN_ARGS: "-Djansi.force=true -Djansi.passthrough=true -B -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn" run: sh buildRun.sh -p ${{ matrix.tutorial }} ${{ github.event.inputs.logLevel }} - - name: Repository dispatch - uses: peter-evans/repository-dispatch@v1 + - name: Multiple Repositories Dispatcher + uses: guilouro/multiple-repositories-dispatch@v1.0.0 with: - token: ${{ secrets.REPO_ACCESS_TOKEN }} - repository: devonfw-tutorials/katacoda-scenarios - event-type: dispatch-katacoda-scenarios - client-payload: '{"tutorial": "${{ matrix.tutorial }}"}' + repo_token: ${{ secrets.REPO_ACCESS_TOKEN }} + event_type: dispatch-katacoda-scenarios + repositories: | + devonfw-tutorials/wiki-tutorials + devonfw-tutorials/katacoda-scenarios + client_payload: '{"tutorial": "${{ matrix.tutorial }}"}' diff --git a/.github/workflows/buildPullRequest.yml b/.github/workflows/buildPullRequest.yml index a378a4f5f..2d17f94f5 100644 --- a/.github/workflows/buildPullRequest.yml +++ b/.github/workflows/buildPullRequest.yml @@ -49,6 +49,8 @@ jobs: path: playbooks - uses: actions/setup-node@v2-beta + with: + node-version: '12' - name: install TS run: npm install typescript diff --git a/.github/workflows/checkCourseName.yml b/.github/workflows/checkCourseName.yml new file mode 100644 index 000000000..6e15d6fdc --- /dev/null +++ b/.github/workflows/checkCourseName.yml @@ -0,0 +1,45 @@ +name: Auto review course name + +on: + pull_request_target: + branches: [ main ] + + workflow_dispatch: +jobs: + auto_review: + runs-on: ubuntu-latest + env: + PR_NUMBER: ${{github.event.number}} + + steps: + - name: Checkout playbooks + uses: actions/checkout@v2 + + - name: Check name + id: check_name + run: | + playbook_list=() + for dir in */; do + playbook_list+=("${dir::-1}"); + done + message="" + for course_file in ./*; do + if [[ $course_file = *"pathway"* ]]; then + coursefile=${course_file/#.\/} + course_name=${coursefile/%-pathway.json} + if [[ " ${playbook_list[@]} " =~ " ${course_name} " ]]; then + message="${message} ${course_name} exist already. " + fi + fi + done + if [[ ! -z "$message" ]]; then + message="${message} The name of your course is already used on a playbook. Please change the name. " + fi + echo "::set-output name=message::$message" + - name: Request changes + if: ${{ steps.check_name.outputs.message != '' }} + uses: andrewmusgrave/automatic-pull-request-review@0.0.2 + with: + repo-token: '${{ secrets.GITHUB_TOKEN }}' + event: REQUEST_CHANGES + body: ${{ steps.check_name.outputs.message }} \ No newline at end of file diff --git a/.github/workflows/syntaxCheckPullRequest.yml b/.github/workflows/syntaxCheckPullRequest.yml index c0e67c892..a5367d136 100644 --- a/.github/workflows/syntaxCheckPullRequest.yml +++ b/.github/workflows/syntaxCheckPullRequest.yml @@ -1,41 +1,75 @@ name: Check PR Katacoda Syntax - +env: + PR_NUMBER: ${{github.event.number}} on: pull_request_target: branches: [ main ] jobs: - build: + setup-matrix: runs-on: ubuntu-latest + + steps: + - name: Checkout playbooks + uses: actions/checkout@v2 + - name: Install node environment + uses: actions/setup-node@v2-beta + with: + node-version: '12' + - name: npm install + run: npm install + - name: Select Changed Files + id: changedfiles + run: node selectChangedFiles.js + - name: Get Playbook Checkout + id: get_checkout + run: node getPlaybookCheckout.js + - name: Setup matrix combinations + id: setup-matrix-combinations + run: | + dirs=() + for changed_file in ${{ steps.changedfiles.outputs.changedFiles }}; do + dir="$(echo $changed_file | cut -d/ -f1)" + if [[ ! " ${dirs[@]} " =~ " ${dir} " ]]; then + MATRIX_PARAMS_COMBINATIONS=$MATRIX_PARAMS_COMBINATIONS'{"tutorial": "'$dir'"},' + fi + dirs+=($dir) + done + echo ::set-output name=matrix-combinations::{\"include\":[$MATRIX_PARAMS_COMBINATIONS]} + outputs: + matrix-combinations: ${{ steps.setup-matrix-combinations.outputs.matrix-combinations }} + checkout_ref: ${{ steps.get_checkout.outputs.ref}} + checkout_name: ${{ steps.get_checkout.outputs.name}} + build: + runs-on: ubuntu-latest + needs: setup-matrix + strategy: + matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix-combinations) }} steps: - name: Checkout tutorial-compiler uses: actions/checkout@v2 with: repository: devonfw-tutorials/tutorial-compiler - - name: Checkout playbooks uses: actions/checkout@v2 with: - repository: devonfw-tutorials/tutorials + repository: ${{needs.setup-matrix.outputs.checkout_name}}/tutorials + ref: ${{needs.setup-matrix.outputs.checkout_ref}} path: playbooks - - uses: actions/setup-node@v2-beta - + with: + node-version: '12' - name: install TS run: npm install typescript - - name: npm install run: npm install - - - name: run buildRun.sh --user ${{ github.actor }} --branch ${{ github.event.pull_request_target.head.ref }} --checkSyntax - run: sh buildRun.sh --user ${{ github.actor }} --branch ${{ github.event.pull_request_target.head.ref }} --checkSyntax -e test_console - + - name: run buildRun.sh --user ${{ github.actor }} --branch ${{needs.setup-matrix.outputs.checkout_ref}} --checkSyntax + run: sh buildRun.sh --user ${{ github.actor }} --branch ${{needs.setup-matrix.outputs.checkout_ref}} --checkSyntax -p ${{ matrix.tutorial }} -e test_console - name: Check error file existence id: check_files uses: andstor/file-existence-action@v1 with: files: "./build/errors/syntaxErrors.md" - - name: Get message id: get_message if: steps.check_files.outputs.files_exists == 'true' @@ -46,11 +80,10 @@ jobs: message="${message//$'\r'/'%0D'}" echo "${message}" echo "::set-output name=message::$message" - - name: Request changes if: ${{ steps.get_message.outputs.message != '' }} uses: andrewmusgrave/automatic-pull-request-review@0.0.2 with: repo-token: '${{ secrets.GITHUB_TOKEN }}' event: COMMENT - body: ${{ steps.get_message.outputs.message }} \ No newline at end of file + body: ${{ steps.get_message.outputs.message }} diff --git a/JumpTheQueue/index.asciidoc b/JumpTheQueue/index.asciidoc index 93b6c400f..34a8352ae 100644 --- a/JumpTheQueue/index.asciidoc +++ b/JumpTheQueue/index.asciidoc @@ -1,12 +1,21 @@ = Jump start an end-to-end devonfw sample application. + +[tags] +-- +technology=Angular +difficulty=beginner +topic=Jump The Queue;end-to-end;e2e +asset=devon4j;devon4ng +-- + ==== Jump The Queue is a small application based on the devonfw framework, which you can create yourself by following our simple step-by-step tutorial. By doing so, you will learn about the app development workflow and gain insight into the design of a professional business information system. -## Prerequisites +### Prerequisites * User should have Java, Angular development experience -## Learning goals -After completing this tutorial, you will have learned about a devonfw sample application Jump-The-Queue and its architecture. +### Learning goals +* After completing this tutorial, you will have learned about a devonfw sample application Jump-The-Queue and its architecture. More information about Jump The Queue on https://github.com/devonfw/jump-the-queue ==== diff --git a/README.adoc b/README.adoc index d994bb05c..299dee834 100644 --- a/README.adoc +++ b/README.adoc @@ -1,17 +1,19 @@ = devonfw Tutorials -Welcome to the devonfw repository for all devonfw assets. You can find all ready to use tutorials on https://katacoda.com/devonfw[Katacoda]. +Welcome to the devonfw repository for all devonfw assets. You can find all ready to use tutorials on https://killercoda.com/devonfw[Killercoda]. == How to Create Your Tutorial -Get to know how to write your first tutorial by running your first https://katacoda.com/devonfw/scenarios/tutorial-compiler[katacoda tutorial] on this topic! Additionally, You can find an detailed explanation as well in the wiki https://github.com/devonfw-tutorials/tutorials/wiki/Development[here]. +Get to know how to write your first tutorial by running your first https://killercoda.com/devonfw/scenario/create-your-own-tutorial[killercoda tutorial] on this topic! Additionally, You can find a detailed explanation as well in the wiki https://github.com/devonfw-tutorials/tutorials/wiki/Development[here]. An overview of the commands available for tutorial specification out of the box can be found in the https://github.com/devonfw-tutorials/tutorials/wiki/Functions[function reference]. -You can view compiled pull requests on our https://katacoda.com/devonfw-dev[development Katacoda space]. +You can view compiled pull requests on our https://katacoda.com/devonfw-dev[development Katacoda space] (not yet on killercoda). == Adapting the Tutorial Generation Process -In this repository, you write tutorials that are executed by the https://github.com/devonfw-tutorials/tutorial-compiler[tutorial compiler]. The tutorial compiler ensures that the tutorials are automatically tested end-to-end. Out of the tutorial specification maintained in this repsitory, it generates multiple outputs like Katacoda tutorials, website step-by-step tutorial documentation and possibly more. +In this repository, you write tutorials that are executed by the https://github.com/devonfw-tutorials/tutorial-compiler[tutorial compiler]. The tutorial compiler ensures that the tutorials are automatically tested end-to-end. Out of the tutorial specification maintained in this repsitory, it generates multiple outputs like Killercoda tutorials, website step-by-step tutorial documentation and possibly more. By adapting the https://github.com/devonfw-tutorials/tutorial-compiler[tutorial compiler], you could also create new commands, which can be cross-compiled to multiple output formats and which will implement its own e2e test execution and assertion. + + diff --git a/angular-mock-service/files/datatable.md b/angular-mock-service/files/datatable.md new file mode 100644 index 000000000..4217549b0 --- /dev/null +++ b/angular-mock-service/files/datatable.md @@ -0,0 +1,2 @@ +* A data table with all the elements +A data table with CRUD operations is very useful (in our case we only view details or delete an item, but they illustrate two important things: the details view shows how to navigate and consume a parametric route, the delete action shows how to invoke service operations over the loaded data - this means that the component is reusable and when the data comes with an API, only the service will need it’s implementation changed) \ No newline at end of file diff --git a/angular-mock-service/files/details.md b/angular-mock-service/files/details.md new file mode 100644 index 000000000..caec3dd06 --- /dev/null +++ b/angular-mock-service/files/details.md @@ -0,0 +1 @@ +* A details page that reads a route parameter and displays the details of the element. \ No newline at end of file diff --git a/angular-mock-service/files/leaderboard.md b/angular-mock-service/files/leaderboard.md new file mode 100644 index 000000000..8d63d078b --- /dev/null +++ b/angular-mock-service/files/leaderboard.md @@ -0,0 +1,4 @@ +The app presents 3 pages as follows: + +* A leader board with the top 3 elements +A leader board can be understood as "the most popular items in a set", "the latest updated items", "you favorite items" etc. \ No newline at end of file diff --git a/angular-mock-service/files/model.md b/angular-mock-service/files/model.md new file mode 100644 index 000000000..976159bfb --- /dev/null +++ b/angular-mock-service/files/model.md @@ -0,0 +1,3 @@ +Let’s consider a 'box of data' represented in JSON. Physically this means a folder with some JSON/TS files in it. They are located in the app/mock folder. The example uses only one mock data file. The file is typed according to our data model. + +The model is represented by the interfaces we make. These interfaces describe the data structures we will use in our application. In this example, there is one data model, corresponding with the 'type' of data that was mocked. In the models folder you will find the .ts script file that describes chemical elements. The corresponding mock file defines a set is chemical element objects, in accordance to our interface definition. \ No newline at end of file diff --git a/angular-mock-service/files/services.md b/angular-mock-service/files/services.md new file mode 100644 index 000000000..8cb018623 --- /dev/null +++ b/angular-mock-service/files/services.md @@ -0,0 +1,4 @@ +A service is an injectable logic that can be consumed by all the components that need it. It can carry manipulation functions and ,in our case, fetch data from a provider. +Inside the Angular App, an Injector gives access to each component to their required services. It’s good coding practice to use a distinct service to each data type you want to manipulate. The type is described in a interface. + +Here we simply fetch and display the data of elements and their details. \ No newline at end of file diff --git a/angular-mock-service/images/architecture.png b/angular-mock-service/images/architecture.png new file mode 100644 index 000000000..d21165e72 Binary files /dev/null and b/angular-mock-service/images/architecture.png differ diff --git a/angular-mock-service/images/data-box.jpg b/angular-mock-service/images/data-box.jpg new file mode 100644 index 000000000..6d38b8921 Binary files /dev/null and b/angular-mock-service/images/data-box.jpg differ diff --git a/angular-mock-service/images/data-table.png b/angular-mock-service/images/data-table.png new file mode 100644 index 000000000..55ce24d26 Binary files /dev/null and b/angular-mock-service/images/data-table.png differ diff --git a/angular-mock-service/images/detail.png b/angular-mock-service/images/detail.png new file mode 100644 index 000000000..2e53b5088 Binary files /dev/null and b/angular-mock-service/images/detail.png differ diff --git a/angular-mock-service/images/leaderboard.png b/angular-mock-service/images/leaderboard.png new file mode 100644 index 000000000..b0e46d5a5 Binary files /dev/null and b/angular-mock-service/images/leaderboard.png differ diff --git a/angular-mock-service/images/project-structure.png b/angular-mock-service/images/project-structure.png new file mode 100644 index 000000000..75f2c6170 Binary files /dev/null and b/angular-mock-service/images/project-structure.png differ diff --git a/angular-mock-service/index.asciidoc b/angular-mock-service/index.asciidoc new file mode 100644 index 000000000..9b204d2ba --- /dev/null +++ b/angular-mock-service/index.asciidoc @@ -0,0 +1,75 @@ += Angular Data Mocking and Service: A way to test the untestables + +[tags] +-- +technology=Angular +difficulty=beginner +topic=testing;mock;unit test;service +asset=devon4ng +-- + +==== +In this scenario, you will learn how to write a simple mock service that helps us by feeding data into our components. + +## Prerequisites +* GitHub account +* Basic Angular knowledge + +## Learning goals +* After completing this scenario, You will learn how to test classes which have dependencies in isolation by using Mocks. + +More information about Angular Mock Service on https://github.com/devonfw/devon4ng/wiki/guide-angular-mock-service +==== + +[step] +-- +restoreDevonfwIde(["ng", "npm", "vscode"]) +-- + + +## Mock Data +Mock data is fake data which is artificially inserted into a piece of software. Mocking is essentially simulating the behaviour of real data in controlled ways. So in order to use mock data effectively, it is essential to have a good understanding of the software under test and more importantly how it uses its data. As with most things, there are both advantages and disadvantages to doing this. + +One of the big advantages with mock data is that it makes it possible to simulate errors and circumstances that would otherwise be very difficult to create in a real world environment. A disadvantage however is that without good understanding of the software, it will be possible to manipulate data in ways which would never actually happen in the real world. + +## Mock Service + +Services are often the smoothest files to unit test. A mock service imitates a real REST or SOAP API – it contains definitions for operations that clients call, receives requests, and returns simulated responses. + +When testing a component with service dependencies, the best practice is mocking them, in order to test the component in an isolated environment. In fact, our purpose is testing the component, not the services, that can be trouble, especially if they try to interact with a server. + +Here, we will go through a angular-mock-service sample app. + + +[step] +-- +displayContent("What is mock data and service?", [{"image": "images/leaderboard.png"}, { "file": "files/leaderboard.md" }, {"image": "images/data-table.png"}, { "file": "files/datatable.md" }, {"image": "images/detail.png"}, { "file": "files/details.md" }]) + +-- + +First, we have to clone the Devon4ng repository to access Angular Mock Service Sample. +[step] +-- +cloneRepository("", "https://github.com/devonfw/devon4ng.git") + +openFile("devon4ng/samples/AngularMockService/src/app/models/periodicElement.ts") + +displayContent("Implementing Mock Data", [{ "file": "files/model.md" }, {"image": "images/data-box.jpg"}]) +-- + + +[step] +-- +openFile("devon4ng/samples/AngularMockService/src/app/services/chemical-elements.service.ts") + +displayContent("Implementing Mock Service", [{ "file": "files/services.md" }, {"image": "images/architecture.png"}]) +-- + + +==== +## Conclusion +To conclude, in this tutorial you learned +* the concepts of mock data and services +* the mock architecture with the help of sample app + +==== \ No newline at end of file diff --git a/autoReviewPullRequest.js b/autoReviewPullRequest.js index d3f863a66..65b8cc562 100644 --- a/autoReviewPullRequest.js +++ b/autoReviewPullRequest.js @@ -83,13 +83,13 @@ function parseFile(file, filename) { let description = parseResult[1][2].descriptionlines; let messageBody = ""; - if(!description.includes("## Prerequisites")) { - messageBody = "The description must describe the prerequisites of a tutorial. It must contain a '## Prerequisites' part."; + if(!description.includes("### Prerequisites")) { + messageBody = "The description must describe the prerequisites of a tutorial. It must contain a '### Prerequisites' part."; } - if(!description.includes("## Learning goals")) { + if(!description.includes("### Learning goals")) { messageBody = (messageBody == "") - ? "The description should describe what the user will learn in the tutorial. It must contain a '## Learning goals' part." + ? "The description should describe what the user will learn in the tutorial. It must contain a '### Learning goals' part." : messageBody + " The description should describe what the user will learn in the tutorial. It must contain a '## Learning goals' part."; } diff --git a/cobigen-setup/index.asciidoc b/cobigen-setup/index.asciidoc index fb6d1a8fc..db95e40f3 100644 --- a/cobigen-setup/index.asciidoc +++ b/cobigen-setup/index.asciidoc @@ -1,4 +1,13 @@ = Setting up devonfw Code Generator(i.e. CobiGen) + +[tags] +-- +technology=CobiGen;Eclipse +difficulty=beginner +topic=setup +asset=CobiGen +-- + ==== CobiGen is a generic incremental code generator. It allows you to generate application code based on the devonfw architecture including all software layers. There is also a CobiGen Command Line Interface(CLI) where you can start the setup following the generation of code. @@ -17,7 +26,7 @@ Here in this tutorial you will learn [step] -- -restoreDevonfwIde(["java","mvn"], "2020.08.001") +restoreDevonfwIde(["java","mvn"]) -- ==== @@ -25,7 +34,7 @@ devonfw IDE has been installed for you. [step] -- -nextKatacodaStep("CobiGen Setup", [{ "file": "files/cobiGenSetup.md" }]) +displayContent("CobiGen Setup", [{ "file": "files/cobiGenSetup.md" }]) -- In next step, you will learn about CobiGen CLI commands. @@ -38,7 +47,7 @@ In this step, you will learn CobiGen commands. [step] -- -nextKatacodaStep("CobiGen CLI Commands and Options", [{ "file": "files/commandsAndOptions.md" }]) +displayContent("CobiGen CLI Commands and Options", [{ "file": "files/commandsAndOptions.md" }]) -- In next step, you will learn about how to integrate CobiGen with Eclipse. @@ -57,7 +66,7 @@ Note: CobiGen comes preinstalled with devonfw IDE. menu bar → Help → Install new Software [step] -- -nextKatacodaStep("Integrate Eclipse with CobiGen", [{"image": "images/01-install-new-software.png"}]) +displayContent("Integrate Eclipse with CobiGen", [{"image": "images/01-install-new-software.png"}]) -- ==== @@ -66,7 +75,7 @@ Here you can select the updates. [step] -- -nextKatacodaStep("Select Update Site", [{"image": "images/02-select-update-site.png"}, { "file": "files/eclipseIntegration.md" }]) +displayContent("Select Update Site", [{"image": "images/02-select-update-site.png"}, { "file": "files/eclipseIntegration.md" }]) -- * Checkout (clone) your project’s templates folder or use the current templates released with CobiGen (https://github.com/devonfw/cobigen/tree/master/cobigen-templates) and then choose @@ -76,15 +85,15 @@ Import -> General -> Existing Projects into Workspace to import the templates in [step] -- -nextKatacodaStep("CobiGen Usage - Simple Mode", [{ "file": "files/simpleModeUsage.md" }, {"image": "images/03-simple-mode-usage.png"}]) +displayContent("CobiGen Usage - Simple Mode", [{ "file": "files/simpleModeUsage.md" }, {"image": "images/03-simple-mode-usage.png"}]) -- [step] -- -nextKatacodaStep("CobiGen Usage - Batch Mode", [{ "file": "files/batchModeUsage.md" }, {"image": "images/04-batch-mode-usage.png"}]) +displayContent("CobiGen Usage - Batch Mode", [{ "file": "files/batchModeUsage.md" }, {"image": "images/04-batch-mode-usage.png"}]) -- [step] -- -nextKatacodaStep(" ", [{ "file": "files/healthCheckTroubleshooting-Conclusion.md" }]) +displayContent(" ", [{ "file": "files/healthCheckTroubleshooting-Conclusion.md" }]) -- diff --git a/cobigen/files/CustomerEntity.java b/cobigen/files/CustomerEntity.java deleted file mode 100644 index f16846c68..000000000 --- a/cobigen/files/CustomerEntity.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.example.application.cobigenexample.customermanagement.dataaccess.api; - -import java.sql.Timestamp; - -import javax.persistence.Entity; -import javax.persistence.Table; - -@Entity -@Table(name = "Customer") -public class CustomerEntity { - - private String firstname; - - private String lastname; - - private int age; - - /** - * @return the firstname - */ - public String getFirstname() { - return firstname; - } - - /** - * @param firstname the firstname to set - */ - public void setFirstname(String firstname) { - this.firstname = firstname; - } - - /** - * @return the lastname - */ - public String getLastname() { - return lastname; - } - - /** - * @param lastname the lastname to set - */ - public void setLastname(String lastname) { - this.lastname = lastname; - } - - /** - * @return the age - */ - public int getAge() { - return age; - } - - /** - * @param age the age to set - */ - public void setAge(int age) { - this.age = age; - } - -} \ No newline at end of file diff --git a/cobigen/files/Placeholder.java b/cobigen/files/Placeholder.java deleted file mode 100644 index 9b5cedde7..000000000 --- a/cobigen/files/Placeholder.java +++ /dev/null @@ -1,9 +0,0 @@ -private int age; -private String company; - -public String getCompany() { - return company; -} -public void setCompany(String company) { - this.company = company; -} \ No newline at end of file diff --git a/cobigen/index.asciidoc b/cobigen/index.asciidoc deleted file mode 100644 index ab7296476..000000000 --- a/cobigen/index.asciidoc +++ /dev/null @@ -1,77 +0,0 @@ -= Generate your Java backend code with devonfw -==== -CobiGen is a generic incremental code generator for end to end code generation tasks. It allows you to build Java, Angular CRUD application code based on the devonfw architecture including all software layers. - -## Prerequisites -* User should have Java development experience - -## Learning goals -After completing this scenario, you will have learned how to generate an end-to-end Java CRUD application code using devonfw CobiGen. - -More information about CobiGen on https://devonfw.com/website/pages/docs/master-cobigen.asciidoc.html -==== - -[step] --- -restoreDevonfwIde(["java","mvn"]) --- -To begin you need to install CobiGen and create a Java Project. -[step] -== Install CobiGen and create Java Project --- -installCobiGen() -createDevon4jProject("com.example.application.cobigenexample") --- - -Create the entity class which will be passed to the cobigen cli generator later -[step] --- -createFile("cobigenexample/core/src/main/java/com/example/application/cobigenexample/customermanagement/dataaccess/api/CustomerEntity.java", "files/CustomerEntity.java") --- - -Now Build the java project -[step] --- -buildJava("cobigenexample", false) --- - -==== -CobiGen is integrated via plugin in the VS Code IDE. We will use it to generate code from one single java class based on existing templates. -[step] --- -adaptTemplatesCobiGen() -cobiGenJava("cobigenexample/core/src/main/java/com/example/application/cobigenexample/customermanagement/dataaccess/api/CustomerEntity.java",[1,3,5,6,8]) --- -The CobiGen code generator will generate some java classes for you. These contain code for basic CRUD operations, REST service handling and data access. - -For example, the following files are generated by CobiGen when using the specified templates: - -(1) CRUD logic: Generates the logic layer and implementations for some use cases. -- `devonfw/workspaces/main/cobigenexample/core/src/main/java/com/example/application/cobigenexample/customermanagement/logic/impl/CustomermanagementImpl.java`{{open}} -- `devonfw/workspaces/main/cobigenexample/core/src/main/java/com/example/application/cobigenexample/customermanagement/logic/impl/usecase/UcManageCustomerImpl.java`{{open}} -- `devonfw/workspaces/main/cobigenexample/core/src/main/java/com/example/application/cobigenexample/customermanagement/logic/impl/usecase/UcFindCustomerImpl.java`{{open}} -- `devonfw/workspaces/main/cobigenexample/api/src/main/java/com/example/application/cobigenexample/customermanagement/logic/api/Customermanagement.java`{{open}} - -(3) CRUD REST services: Generates the service layer with CRUD operations for using in REST services. -- `devonfw/workspaces/main/cobigenexample/api/src/main/java/com/example/application/cobigenexample/customermanagement/service/api/rest/CustomermanagementRestService.java`{{open}} -- `devonfw/workspaces/main/cobigenexample/core/src/main/java/com/example/application/cobigenexample/customermanagement/service/impl/rest/CustomermanagementRestServiceImpl.java`{{open}} - -(5) TO's: Generates the related Transfer Objects. -- `devonfw/workspaces/main/cobigenexample/api/src/main/java/com/example/application/cobigenexample/customermanagement/logic/api/to/CustomerEto.java`{{open}} -- `devonfw/workspaces/main/cobigenexample/api/src/main/java/com/example/application/cobigenexample/customermanagement/logic/api/to/CustomerSearchCriteriaTo.java`{{open}} - -(6) Entity infrastructure: Creates the entity main interface and edits (by a merge) the current entity to extend the newly generated classes. -- `devonfw/workspaces/main/cobigenexample/api/src/main/java/com/example/application/cobigenexample/customermanagement/common/api/Customer.java`{{open}} -- `devonfw/workspaces/main/cobigenexample/core/src/main/java/com/example/application/cobigenexample/customermanagement/dataaccess/api/CustomerEntity.java`{{open}} (changed) - -(8) CRUD SpringData Repository: Generates the entity repository (that contains the CRUD operations) in the data access layer. -- `devonfw/workspaces/main/cobigenexample/core/src/main/java/com/example/application/cobigenexample/customermanagement/dataaccess/api/repo/CustomerRepository.java`{{open}} -==== - -Furthermore, we can change the CustomerEntity afterwards and update our source files simply by running cobigen again. -[step] -== Change Entity and run cobigen again --- -changeFile("cobigenexample/core/src/main/java/com/example/application/cobigenexample/customermanagement/dataaccess/api/CustomerEntity.java", { "file": "files/Placeholder.java", "placeholder": "private int age;" }) -cobiGenJava("cobigenexample/core/src/main/java/com/example/application/cobigenexample/customermanagement/dataaccess/api/CustomerEntity.java",[1,3,5,6,8]) --- diff --git a/create-your-own-tutorial/index.asciidoc b/create-your-own-tutorial/index.asciidoc index 778e743db..15ae5dc8c 100644 --- a/create-your-own-tutorial/index.asciidoc +++ b/create-your-own-tutorial/index.asciidoc @@ -1,4 +1,12 @@ = Create your own tutorial + +[tags] +-- +technology=Tutorial Compiler +difficulty=beginner +topic=tutorial;documentation +-- + ==== In this scenario, you will learn how to create your own tutorial using the tutorial compiler. @@ -26,7 +34,7 @@ This will create a copy of the repository in your own GitHub account. You will f [step] -- -nextKatacodaStep("Fork the tutorials repository", [{"image": "images/fork.jpg"}, {"content": "\nOpen the forked repository in your GitHub account and copy the repository URL as shown in image below.\n"}, {"image": "images/clone_code.jpg"}]) +displayContent("Fork the tutorials repository", [{"image": "images/fork.jpg"}, {"content": "\nOpen the forked repository in your GitHub account and copy the repository URL as shown in image below.\n"}, {"image": "images/clone_code.jpg"}]) -- ==== @@ -43,7 +51,7 @@ cloneRepository("", "https://github.com/devonfw-tutorials/tutorials.git") ==== [step] -- -nextKatacodaStep("Create a new branch", [{ "file": "files/createNewBranch.md" }]) +displayContent("Create a new branch", [{ "file": "files/createNewBranch.md" }]) -- Now you can start to create the tutorial. This will be shown in the next steps. ==== @@ -60,7 +68,7 @@ createFile("tutorials/myTutorial/index.asciidoc") [step] -- -nextKatacodaStep("Create a pull request", [{ "file": "files/createPullRequest1.md" }, {"image": "images/pull_request.jpg"}, {"content": "\nYou might have to click on 'compare across forks'.\n"}, {"image": "images/compare.jpg"}, { "file": "files/createPullRequest2.md" }]) +displayContent("Create a pull request", [{ "file": "files/createPullRequest1.md" }, {"image": "images/pull_request.jpg"}, {"content": "\nYou might have to click on 'compare across forks'.\n"}, {"image": "images/compare.jpg"}, { "file": "files/createPullRequest2.md" }]) -- The syntax in which the tutorial is written can be found at https://github.com/devonfw-tutorials/tutorials/wiki/Development. @@ -99,15 +107,15 @@ This is the syntax without additional text after the step. There is an alternati [step] -- -nextKatacodaStep("Alternative syntax", [{ "file": "files/alternativeSyntax.md" }]) +displayContent("Alternative syntax", [{ "file": "files/alternativeSyntax.md" }]) -- [step] -- -nextKatacodaStep("Push tutorial", [{ "file": "files/pushTutorial.md" }]) +displayContent("Push tutorial", [{ "file": "files/pushTutorial.md" }]) -- [step] -- -nextKatacodaStep("Local testing", [{ "file": "files/localTesting.md" }]) +displayContent("Local testing", [{ "file": "files/localTesting.md" }]) -- diff --git a/devon4j-app/index.asciidoc b/devon4j-app/index.asciidoc index d6975945a..1310b030b 100644 --- a/devon4j-app/index.asciidoc +++ b/devon4j-app/index.asciidoc @@ -1,12 +1,21 @@ = Generate your Java application with devon4j + +[tags] +-- +technology=Maven +difficulty=beginner +topic=project generation;setup;architecture;first application +asset=devon4j +-- + ==== devon4j is the Java stack of devonfw. It allows you to build business applications (backends) using Java technology in a highly efficient and standardized way based on established best-practices. -## Prerequisites +# Prerequisites * User should have Java development experience -## Learning goals -After completing this scenario, you will have learned how to generate Java application using devon4j. +# Learning goals +* After completing this scenario, you will have learned how to generate Java application using devon4j. More information about devon4j on https://devonfw.com/website/pages/docs/devon4j.asciidoc.html @@ -17,13 +26,18 @@ More information about devon4j on https://devonfw.com/website/pages/docs/devon4j restoreDevonfwIde (["java","mvn","vscode"]) -- ==== -### Create devon4j sample application +### A devon4j Sample Application + +Note: Startup script will take some time for set up. After that you can proceed further. If you want to create devon4j application on your local machine there are two ways to do it: + * In eclipse as shown [here](https://devonfw.com/website/pages/docs/devon4j.asciidoc_tutorials.html#tutorial-newapp.asciidoc_from-eclipse) + * Using command line as shown [here](https://devonfw.com/website/pages/docs/devon4j.asciidoc_tutorials.html#tutorial-newapp.asciidoc_from-command-line) -Now, we will create sample devon4j application with name *sampleapp*. This step will guide you on how to do it. +Now, you will create sample devon4j application with name *sampleapp*. This step will guide you on how to do it. + [step] -- @@ -32,27 +46,30 @@ createDevon4jProject("com.example.application.sampleapp") Once sampleapp is created switch to next tab of IDE. In IDE explorer you can see folder structure like devonfw-> workspaces->main->sampleapp . -sampleapp contains 3 modules i.e api, core and server. +Sampleapp contains 3 modules i.e api, core and server. **api**: It contains API for sampleapp.The API contains the required artifacts to interact with your application via remote services. This can be REST service interfaces, transfer-objects with their interfaces and datatypes but also OpenAPI or gRPC contracts. **core**: It is the core of the application.In this module you can write actual business logic with service implementation, as well as entire logic layer and dataaccess layer. -**batch**: optional module for batch layer. In this example we have not created it. To add batch module while generating from commandline use -Dbatch=batch parameter. And to generate it from eclipse using mave archetype enter batch variable value as batch in project creation page. +**batch**: Optional module for batch layer. In this example we have not created it. To add batch module while generating from commandline use -Dbatch=batch parameter. And to generate it from eclipse using maven archetype, enter batch variable value as batch in project creation page. **server**: This module bundles the entire app (core with optional batch) typically as a bootified WAR file. -If you want to know more about modules and project structure refer [here](https://github.com/devonfw/devon4j/blob/master/documentation/guide-structure.asciidoc#project-structure). +If you want to know more about modules and project structure refer [here](#https://github.com/devonfw/devon4j/blob/master/documentation/guide-structure.asciidoc#project-structure). ==== + + ==== [step] -- -nextKatacodaStep("devon4j multilayer architecture", [{ "image": "images/devon4j_proj_structure1.jpg" }]) +displayContent("devon4j multilayer architecture", [{ "image": "images/devon4j_proj_structure1.jpg" }]) -- -As shown in above image,devon4j application follows [multilayered architecture](https://en.wikipedia.org/wiki/Multitier_architecture). +As shown in above image, devon4j application follows [multilayered architecture](https://en.wikipedia.org/wiki/Multitier_architecture). Each component is divided into following layers: + * [client layer](https://github.com/devonfw/devon4j/blob/master/documentation/guide-client-layer.asciidoc) for the front-end (GUI). * [service layer](https://github.com/devonfw/devon4j/blob/master/documentation/guide-service-layer.asciidoc) for the services used to expose functionality of the back-end to the client or other consumers. For example, in sampleapp we generated com.example.application.sampleapp..service.impl will have all rest service implementation. @@ -61,12 +78,12 @@ Each component is divided into following layers: * [logic layer](https://github.com/devonfw/devon4j/blob/master/documentation/guide-logic-layer.asciidoc) for the business logic. For example, in sampleapp we generated com.example.application.sampleapp..logic will contain business logic or usecase implementation. -* [data-access layer](https://github.com/devonfw/devon4j/blob/master/documentation/guide-dataaccess-layer.asciidoc) for the data access (esp. persistence).For example, in sampleapp we generated com.example.application.sampleapp..dataaccess will contain entity, repositories etc. -==== +* [data-access layer](https://github.com/devonfw/devon4j/blob/master/documentation/guide-dataaccess-layer.asciidoc) for the data access (esp. persistence).For example, in sampleapp we generated com.example.application.sampleapp..dataaccess will contain entity, repositories etc. ==== -### Build devon4j sample application -Build the java project + +==== +Now you have to build a devon4j sample application i.e. sampleapp. [step] -- @@ -76,14 +93,21 @@ buildJava("sampleapp", false) Once build is successful you will get bootified-war generated in server module target folder. In sampleapp check for path sampleapp/server/sampleapp-server-bootified.war ==== + + ==== ## Conclusion In this tutorial you have learnt how to create devon4j application using command line or via Eclipse. Next you can check for other tutorials such as: - * Java backend code generation using CobiGen (Code Generator) + * devon4j- contract first code generation + * devon4j-Kafka + * devon4j-security + * devon4j with Spring JPA + * devon4j rest services + ==== diff --git a/devon4j-architecture/index.asciidoc b/devon4j-architecture/index.asciidoc index e43133c7e..a91ed37ea 100644 --- a/devon4j-architecture/index.asciidoc +++ b/devon4j-architecture/index.asciidoc @@ -1,4 +1,12 @@ = devon4j architecture in practice + +[tags] +-- +difficulty=beginner +topic=architecture +asset=devon4j +-- + ==== ## Prerequisites @@ -37,7 +45,7 @@ Once project is cloned switch to next tab of IDE. In IDE explorer you will be ab ### devon4j application structure [step] -- -nextKatacodaStep("devon4j application architecture", [{ "image": "images/jtqj_app_structure.jpg" }]) +displayContent("devon4j application architecture", [{ "image": "images/jtqj_app_structure.jpg" }]) -- As shown above, jump-the-queue contains 3 modules i.e api, core and server. @@ -60,7 +68,7 @@ devon4j application follows [multilayered architecture](https://en.wikipedia.org [step] -- -nextKatacodaStep("devon4j application layers", [{ "image": "images/jtqj_detailed_app_structure.jpg" }]) +displayContent("devon4j application layers", [{ "image": "images/jtqj_detailed_app_structure.jpg" }]) -- Above image display detailed structure of devon4j application. As shown above jump-the-queue application contains different components like queuemanagement, visitormanagement etc @@ -83,7 +91,7 @@ For example, in jtqj-api->queuemangement->dataaccess->core contains entities, sp [step] -- -nextKatacodaStep("Understand devon4j application architecture", [{ "file": "devon4j-app-arch.md" }]) +displayContent("Understand devon4j application architecture", [{ "file": "devon4j-app-arch.md" }]) -- ==== diff --git a/devon4j-http-rest-client/files/BaseWebSecurityConfig.txt b/devon4j-http-rest-client/files/BaseWebSecurityConfig.txt new file mode 100644 index 000000000..ef15ae1c2 --- /dev/null +++ b/devon4j-http-rest-client/files/BaseWebSecurityConfig.txt @@ -0,0 +1,117 @@ +package com.example.application.httprestserver.general.service.impl.config; + +import javax.inject.Inject; +import javax.servlet.Filter; + +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; +import org.springframework.security.web.authentication.logout.LogoutFilter; +import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; + +import com.devonfw.module.security.common.api.config.WebSecurityConfigurer; +import com.devonfw.module.security.common.impl.rest.AuthenticationSuccessHandlerSendingOkHttpStatusCode; +import com.devonfw.module.security.common.impl.rest.JsonUsernamePasswordAuthenticationFilter; +import com.devonfw.module.security.common.impl.rest.LogoutSuccessHandlerReturningOkHttpStatusCode; + +/** + * This type serves as a base class for extensions of the {@code WebSecurityConfigurerAdapter} and provides a default + * configuration.
+ * Security configuration is based on {@link WebSecurityConfigurerAdapter}. This configuration is by purpose designed + * most simple for two channels of authentication: simple login form and rest-url. + */ +public abstract class BaseWebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Inject + private UserDetailsService userDetailsService; + + @Inject + private PasswordEncoder passwordEncoder; + + @Inject + private WebSecurityConfigurer webSecurityConfigurer; + + + + /** + * Configure spring security to enable a simple webform-login + a simple rest login. + */ + @Override + public void configure(HttpSecurity http) throws Exception { + + String[] unsecuredResources = new String[] { "/login", "/security/**", "/services/rest/login", + "/services/rest/logout" }; + + // disable CSRF protection by default, use csrf starter to override. + http = http.httpBasic().and().csrf().disable(); + // load starters as pluggins. + http = this.webSecurityConfigurer.configure(http); + + http + // + .userDetailsService(this.userDetailsService) + // define all urls that are not to be secured + .authorizeRequests().antMatchers(unsecuredResources).permitAll().anyRequest().authenticated().and() + // configure parameters for simple form login (and logout) + .formLogin().successHandler(new SimpleUrlAuthenticationSuccessHandler()).defaultSuccessUrl("/") + .failureUrl("/login.html?error").loginProcessingUrl("/j_spring_security_login").usernameParameter("username") + .passwordParameter("password").and() + // logout via POST is possible + .logout().logoutSuccessUrl("/login.html").and() + // register login and logout filter that handles rest logins + .addFilterAfter(getSimpleRestAuthenticationFilter(), BasicAuthenticationFilter.class) + .addFilterAfter(getSimpleRestLogoutFilter(), LogoutFilter.class); + } + + /** + * Create a simple filter that allows logout on a REST Url /services/rest/logout and returns a simple HTTP status 200 + * ok. + * + * @return the filter. + */ + protected Filter getSimpleRestLogoutFilter() { + + LogoutFilter logoutFilter = new LogoutFilter(new LogoutSuccessHandlerReturningOkHttpStatusCode(), + new SecurityContextLogoutHandler()); + + // configure logout for rest logouts + logoutFilter.setLogoutRequestMatcher(new AntPathRequestMatcher("/services/rest/logout")); + + return logoutFilter; + } + + /** + * Create a simple authentication filter for REST logins that reads user-credentials from a json-parameter and returns + * status 200 instead of redirect after login. + * + * @return the {@link JsonUsernamePasswordAuthenticationFilter}. + * @throws Exception if something goes wrong. + */ + protected JsonUsernamePasswordAuthenticationFilter getSimpleRestAuthenticationFilter() throws Exception { + + JsonUsernamePasswordAuthenticationFilter jsonFilter = new JsonUsernamePasswordAuthenticationFilter( + new AntPathRequestMatcher("/services/rest/login")); + jsonFilter.setPasswordParameter("j_password"); + jsonFilter.setUsernameParameter("j_username"); + jsonFilter.setAuthenticationManager(authenticationManager()); + // set failurehandler that uses no redirect in case of login failure; just HTTP-status: 401 + jsonFilter.setAuthenticationManager(authenticationManagerBean()); + jsonFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler()); + // set successhandler that uses no redirect in case of login success; just HTTP-status: 200 + jsonFilter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandlerSendingOkHttpStatusCode()); + return jsonFilter; + } + + @SuppressWarnings("javadoc") + @Inject + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication().withUser("admin").password(this.passwordEncoder.encode("admin")).authorities("Admin"); + } + +} diff --git a/devon4j-http-rest-client/files/TestRestService.java b/devon4j-http-rest-client/files/TestRestService.java new file mode 100644 index 000000000..99cdc05c2 --- /dev/null +++ b/devon4j-http-rest-client/files/TestRestService.java @@ -0,0 +1,21 @@ +package com.example.application.httprestclient.general.service.api.rest; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("/testrest/v1") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface TestRestService { + + @GET + @Path("/response/") + public String showResponse(); + + @GET + @Path("/verify/") + public String verifyServiceWork(); +} diff --git a/devon4j-http-rest-client/files/TestRestServiceImpl.java b/devon4j-http-rest-client/files/TestRestServiceImpl.java new file mode 100644 index 000000000..b8b9e1421 --- /dev/null +++ b/devon4j-http-rest-client/files/TestRestServiceImpl.java @@ -0,0 +1,46 @@ +package com.example.application.httprestclient.general.service.impl.rest; + +import javax.inject.Inject; +import javax.inject.Named; + +import com.devonfw.module.service.common.api.client.ServiceClientFactory; +import com.devonfw.module.service.common.api.client.config.ServiceClientConfigBuilder; +import com.example.application.httprestclient.general.service.api.rest.TestRestService; +import com.example.application.httprestclient.general.service.api.rest.VisitormanagementRestService; + +@Named("TestRestService") +public class TestRestServiceImpl implements TestRestService { + + @Inject + private ServiceClientFactory serviceClientFactory; + + @Override + public String showResponse() { + + String result = callSynchronous(); + System.out.println("**********inside client method***********"); + System.out.println(result); + System.out.println("************Thank you for choosing devon4j ****************"); + return result; + + } + + private String callSynchronous() { + + System.out.println("***********inside synchronous call************"); + VisitormanagementRestService visitormanagementRestService = this.serviceClientFactory.create( + VisitormanagementRestService.class, + new ServiceClientConfigBuilder().authBasic().userLogin("admin").userPassword("admin").buildMap()); + // call of service over the wire, synchronously blocking until result is received or error occurred + String resultFromAPICall = visitormanagementRestService.returnResponseToClient(); + System.out.println("************************got result from api" + resultFromAPICall + "***************"); + return resultFromAPICall; + } + + @Override + public String verifyServiceWork() { + + return "Verified... service is working"; + } + +} diff --git a/devon4j-http-rest-client/files/VisitorManagementRestServiceClient.txt b/devon4j-http-rest-client/files/VisitorManagementRestServiceClient.txt new file mode 100644 index 000000000..abd4f05cc --- /dev/null +++ b/devon4j-http-rest-client/files/VisitorManagementRestServiceClient.txt @@ -0,0 +1,20 @@ +package com.example.application.httprestclient.general.service.api.rest; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("/visitormanagement/v1") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface VisitormanagementRestService { + + @GET + @Path("/clientrequest/") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String returnResponseToClient(); + +} \ No newline at end of file diff --git a/devon4j-http-rest-client/files/VisitormanagementRestService.java b/devon4j-http-rest-client/files/VisitormanagementRestService.java new file mode 100644 index 000000000..f61768500 --- /dev/null +++ b/devon4j-http-rest-client/files/VisitormanagementRestService.java @@ -0,0 +1,20 @@ +package com.example.application.httprestserver.visitormanagement.service.api.rest; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("/visitormanagement/v1") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface VisitormanagementRestService { + + @GET + @Path("/clientrequest/") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String returnResponseToClient(); + +} \ No newline at end of file diff --git a/devon4j-http-rest-client/files/VisitormanagementRestServiceImpl.java b/devon4j-http-rest-client/files/VisitormanagementRestServiceImpl.java new file mode 100644 index 000000000..31c78ce85 --- /dev/null +++ b/devon4j-http-rest-client/files/VisitormanagementRestServiceImpl.java @@ -0,0 +1,16 @@ +package com.example.application.httprestserver.visitormanagement.service.impl.rest; + +import javax.inject.Named; + +import com.example.application.httprestserver.visitormanagement.service.api.rest.VisitormanagementRestService; + +@Named("VisitormanagementRestService") +public class VisitormanagementRestServiceImpl implements VisitormanagementRestService { + + @Override + public String returnResponseToClient() { + + return "Welcome to REST API world"; + } + +} diff --git a/devon4j-http-rest-client/files/client_application.txt b/devon4j-http-rest-client/files/client_application.txt new file mode 100644 index 000000000..ce01be013 --- /dev/null +++ b/devon4j-http-rest-client/files/client_application.txt @@ -0,0 +1,44 @@ +# This is the configuration file shipped with the application that contains reasonable defaults. +# Environment specific configurations are configured in config/application.properties. +# If you are running in a servlet container you may add this to lib/config/application.properties in case you do not +# want to touch the WAR file. + +server.port=8080 +spring.application.name=httprestclient +server.servlet.context-path=/httprestclient + +security.expose.error.details=false + +spring.jpa.hibernate.ddl-auto=validate + +# Datasource for accessing the database +# https://github.com/spring-projects/spring-boot/blob/d3c34ee3d1bfd3db4a98678c524e145ef9bca51c/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java +spring.jpa.database=h2 +# spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +# spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa + +# Hibernate NamingStrategy has been deprecated and then removed in favor of two step naming strategy ImplicitNamingStrategy and PhysicalNamingStrategy +spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl +spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl + +# https://github.com/devonfw/devon4j/issues/65 +# https://vladmihalcea.com/the-open-session-in-view-anti-pattern/ +spring.jpa.open-in-view=false + +# to prevent that Spring Boot launches batch jobs on startup +# might otherwise lead to errors if job parameters are needed (or lead to unwanted modifications and longer startup times) +# see http://stackoverflow.com/questions/22318907/how-to-stop-spring-batch-scheduled-jobs-from-running-at-first-time-when-executin +spring.batch.job.enabled=false + +# Flyway for Database Setup and Migrations +spring.flyway.locations=classpath:db/migration + +# rest client setup +service.client.default.url=https://[[HOST_SUBDOMAIN]]-8081-[[KATACODA_HOST]].environments.katacoda.com/httprestserver/services/rest +service.client.app.httprestserver.url=https://[[HOST_SUBDOMAIN]]-8081-[[KATACODA_HOST]].environments.katacoda.com/httprestserver/services/rest +service.client.default.timeout.connection=120 +service.client.default.timeout.response=3600 +service.client.app.httprestserver.auth=basic +service.client.app.httprestserver.user.login=admin +service.client.app.httprestserver.user.password=admin \ No newline at end of file diff --git a/devon4j-http-rest-client/files/client_config_application.txt b/devon4j-http-rest-client/files/client_config_application.txt new file mode 100644 index 000000000..46c5aaee5 --- /dev/null +++ b/devon4j-http-rest-client/files/client_config_application.txt @@ -0,0 +1,36 @@ +# This is the spring boot configuration file for development. It will not be included into the application. +# In order to set specific configurations in a regular installed environment create an according file +# config/application.properties in the server. If you are deploying the application to a servlet container as untouched +# WAR file you can locate this config folder in ${symbol_dollar}{CATALINA_BASE}/lib. If you want to deploy multiple applications to +# the same container (not recommended by default) you need to ensure the WARs are extracted in webapps folder and locate +# the config folder inside the WEB-INF/classes folder of the webapplication. + +server.port=8080 +server.servlet.context-path=/httprestclient + +# Datasource for accessing the database +# See https://github.com/devonfw/devon4j/blob/develop/documentation/guide-configuration.asciidoc#security-configuration +#jasypt.encryptor.password=none +#spring.datasource.password=ENC(7CnHiadYc0Wh2FnWADNjJg==) +spring.datasource.password= +spring.datasource.url=jdbc:h2:./.httprestclient; + +# print SQL to console for debugging (e.g. detect N+1 issues) +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true + +# Enable JSON pretty printing +spring.jackson.serialization.INDENT_OUTPUT=true + +# Flyway for Database Setup and Migrations +spring.flyway.enabled=true +spring.flyway.clean-on-validation-error=true + +# rest client setup +service.client.default.url=https://[[HOST_SUBDOMAIN]]-8081-[[KATACODA_HOST]].environments.katacoda.com/httprestserver/services/rest +service.client.app.httprestserver.url=https://[[HOST_SUBDOMAIN]]-8081-[[KATACODA_HOST]].environments.katacoda.com/httprestserver/services/rest +service.client.default.timeout.connection=120 +service.client.default.timeout.response=3600 +service.client.app.httprestserver.auth=basic +service.client.app.httprestserver.user.login=admin +service.client.app.httprestserver.user.password=admin diff --git a/devon4j-http-rest-client/files/dependency.txt b/devon4j-http-rest-client/files/dependency.txt new file mode 100644 index 000000000..1f6843baf --- /dev/null +++ b/devon4j-http-rest-client/files/dependency.txt @@ -0,0 +1,5 @@ + + + com.devonfw.java.starters + devon4j-starter-cxf-client-rest + diff --git a/devon4j-http-rest-client/files/server_application.txt b/devon4j-http-rest-client/files/server_application.txt new file mode 100644 index 000000000..59fea029c --- /dev/null +++ b/devon4j-http-rest-client/files/server_application.txt @@ -0,0 +1,36 @@ +# This is the configuration file shipped with the application that contains reasonable defaults. +# Environment specific configurations are configured in config/application.properties. +# If you are running in a servlet container you may add this to lib/config/application.properties in case you do not +# want to touch the WAR file. + +server.port=8081 +server.servlet.context-path=/httprestserver +spring.application.name=httprestserver + +security.expose.error.details=false + +spring.jpa.hibernate.ddl-auto=validate + +# Datasource for accessing the database +# https://github.com/spring-projects/spring-boot/blob/d3c34ee3d1bfd3db4a98678c524e145ef9bca51c/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java +spring.jpa.database=h2 +# spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +# spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa + +# Hibernate NamingStrategy has been deprecated and then removed in favor of two step naming strategy ImplicitNamingStrategy and PhysicalNamingStrategy +spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl +spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl + +# https://github.com/devonfw/devon4j/issues/65 +# https://vladmihalcea.com/the-open-session-in-view-anti-pattern/ +spring.jpa.open-in-view=false + +# to prevent that Spring Boot launches batch jobs on startup +# might otherwise lead to errors if job parameters are needed (or lead to unwanted modifications and longer startup times) +# see http://stackoverflow.com/questions/22318907/how-to-stop-spring-batch-scheduled-jobs-from-running-at-first-time-when-executin +spring.batch.job.enabled=false + +# Flyway for Database Setup and Migrations +spring.flyway.locations=classpath:db/migration + diff --git a/devon4j-http-rest-client/files/server_config_application.txt b/devon4j-http-rest-client/files/server_config_application.txt new file mode 100644 index 000000000..3a893a4b1 --- /dev/null +++ b/devon4j-http-rest-client/files/server_config_application.txt @@ -0,0 +1,27 @@ +# This is the spring boot configuration file for development. It will not be included into the application. +# In order to set specific configurations in a regular installed environment create an according file +# config/application.properties in the server. If you are deploying the application to a servlet container as untouched +# WAR file you can locate this config folder in ${symbol_dollar}{CATALINA_BASE}/lib. If you want to deploy multiple applications to +# the same container (not recommended by default) you need to ensure the WARs are extracted in webapps folder and locate +# the config folder inside the WEB-INF/classes folder of the webapplication. + +server.port=8081 +server.servlet.context-path=/httprestserver + +# Datasource for accessing the database +# See https://github.com/devonfw/devon4j/blob/develop/documentation/guide-configuration.asciidoc#security-configuration +#jasypt.encryptor.password=none +#spring.datasource.password=ENC(7CnHiadYc0Wh2FnWADNjJg==) +spring.datasource.password= +spring.datasource.url=jdbc:h2:./.httprestserver; + +# print SQL to console for debugging (e.g. detect N+1 issues) +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true + +# Enable JSON pretty printing +spring.jackson.serialization.INDENT_OUTPUT=true + +# Flyway for Database Setup and Migrations +spring.flyway.enabled=true +spring.flyway.clean-on-validation-error=true diff --git a/devon4j-http-rest-client/index.asciidoc b/devon4j-http-rest-client/index.asciidoc new file mode 100644 index 000000000..b76f63efb --- /dev/null +++ b/devon4j-http-rest-client/index.asciidoc @@ -0,0 +1,229 @@ += Develop a devon4j CXF REST Client using Synchronous call + +[tags] +-- +technology=Spring JPA;Flyway;Apache CXF;JAX-RS +difficulty=intermediate +topic=Rest;Rest API;authentication;API;client +asset=devon4j +-- +==== +REST (REpresentational State Transfer) is an inter-operable protocol for services that is more lightweight than SOAP. We give best practices that lead to simple, easy and pragmatic "HTTP APIs". + +## Prerequisites +* User should have development experience in JAVA. +* Basic knowledge of REST. + +## Learning Goal +Here in this tutorial you will learn the following things: +* JAX-RS standard for REST service implementation proposed by devonfw. +* How to create REST client with devon4j using Synchronous call. + +Let's get started!! +==== + +[step] +-- +restoreDevonfwIde(["java", "vscode"]) +-- + +==== +REST (REpresentational State Transfer) is an inter-operable protocol for services that is more lightweight than SOAP. + +For implementing REST services we use the JAX-RS standard. As an implementation we recommend CXF. For JSON bindings we use Jackson while XML binding works out-of-the-box with JAXB. To implement a service you write an interface with JAX-RS annotations for the API and a regular implementation class annotated with @Named to make it a spring-bean. + +The REST service implementation is a regular CDI bean that can use dependency injection. The separation of the API as a Java interface allows to use it for service client calls. + +**Why** **Should** **you** **prefer** **devon4j** **client** **over** **other** **clients?** + +devon4j supports flexible configuration, adding headers for authentication, mapping of errors from server, logging success/errors with duration for performance analysis, support for synchronous and asynchronous invocations. Easy invocation of service inside a micro-service. +For more details on REST visit https://devonfw.com/website/pages/docs/devon4j.asciidoc_guides.html#guide-rest.asciidoc + +For more details on devon4j Service Client https://devonfw.com/website/pages/docs/devon4j.asciidoc_guides.html#guide-service-client.asciidoc + +## Create the devon4j REST SERVER +As explained in REST document, With JAX-RS it is important to make sure that each service method is annotated with the proper HTTP annotation(@GET, @POST, etc). +Let's create devon4j server. +[step] +== REST +-- +createDevon4jProject("com.example.application.httprestserver") +-- +In next step, you will add configuration to allow basic authentication. +==== + + +Now, You have to modify BaseWebSecurityConfig file to allow application for basic authentication. +[step] +== Add configuration to allow basic authentication +-- +changeFile("httprestserver/core/src/main/java/com/example/application/httprestserver/general/service/impl/config/BaseWebSecurityConfig.java", { "file": "files/BaseWebSecurityConfig.txt" }) +-- + + +Now, you will create VisitormanagementRestService to provide functionality using JAX-RS standard. +[step] +== Create service for REST server +-- +createFile("httprestserver/api/src/main/java/com/example/application/httprestserver/visitormanagement/service/api/rest/VisitormanagementRestService.java", "files/VisitormanagementRestService.java") +-- + + +==== +Now, you will create VisitormanagementRestServiceImpl, the implementation class of VisitormanagementRestService using JAX-RS standard. +[step] +== Create implementation class for Service +-- +createFile("httprestserver/core/src/main/java/com/example/application/httprestserver/visitormanagement/service/impl/rest/VisitormanagementRestServiceImpl.java", "files/VisitormanagementRestServiceImpl.java") +-- +Here , you can see "VisitormanagementRestServiceImpl.java" is annotated with @Named to make it a spring-bean. To get return response to client "returnResponseToClient()" can be accessed via HTTP GET under the URL path "/visitormanagement/v1/clientrequest". It will return its result (String) as JSON (see @Produces in VisitormanagementRestService). +==== + + +Now, you will configure port in application properties. +[step] +== Modify properties files +-- +changeFile("httprestserver/core/src/main/resources/application.properties", { "file": "files/server_application.txt" }) +changeFile("httprestserver/core/src/main/resources/config/application.properties", { "file": "files/server_config_application.txt" }) +-- + + + +==== +You have successfully built the REST-server. Now, you have to start the build and then, start the server as mentioned below. +[step] +== Build and Start devon4j REST Server +-- +buildJava("httprestserver", false) +runServerJava("httprestserver/server", { "startupTime": 1000, "port": 8081, "path": "httprestserver" }) +-- +Once, Java server starts running. To test REST-server follow below steps: +* Click on "+" next to terminal tab +* Select "select port to view host" +* Enter the port number "8081" +* In the url, append "/httprestserver/services/rest/visitormanagement/v1/clientrequest/" +* Enter username as "admin" and password as "admin" +* You will be able to see response "Welcome to REST API world" +In next step, You have to create devon4j service Client. +==== + + +==== +To create devon4j service Client. First, You need to create a sample devon4j project. + +[step] +== Create devon4j REST Client +-- +createDevon4jProject("com.example.application.httprestclient") +-- +Then, You need to add required dependency to your application. + +Since in this tutorial you will build client on Synchronous call so, you have to add dependency for synchronous consuming REST services via Apache CXF (Java8+) +You will add below dependency in core folder pom.xml + +---- + + com.devonfw.java.starters + devon4j-starter-cxf-client-rest + + +---- +==== + +Modify pom.xml as below: +[step] +== Modify POM file +-- +changeFile("httprestclient/core/pom.xml", { "file": "files/dependency.txt", "placeholder": "" }) +-- + +Now, You will create a Java interface VisitormanagementRestService to invoke inside client. +[step] +== Create service to invoke server +-- +createFile("httprestclient/api/src/main/java/com/example/application/httprestclient/general/service/api/rest/VisitormanagementRestService.java", "files/VisitorManagementRestServiceClient.txt") +-- + + +Now, you will create service for client i.e. TestRestService.java to provide functionality using JAX-RS standard. +[step] +== Create service for CXF REST Client +-- +createFile("httprestclient/api/src/main/java/com/example/application/httprestclient/general/service/api/rest/TestRestService.java", "files/TestRestService.java") +-- + + +==== +Now, you will create TestRestServiceImpl, the implementation class of TestRestService using JAX-RS standard. + +[step] +== Create implementation class for client's service +-- +createFile("httprestclient/core/src/main/java/com/example/application/httprestclient/general/service/impl/rest/TestRestServiceImpl.java", "files/TestRestServiceImpl.java") +-- + +As you can see synchronous invocation of a service is very simple and type-safe. The actual call of showResponse will technically call the remote service(i.e. VisitormanagementRestService) over the wire ( via HTTP) including marshaling the arguments (converting String to JSON) and un-marshalling the result (e.g. converting the received JSON to String). +Here in TestRestServiceImpl, there is a method "callSynchronous" which will call the VisitormanagementRestService and return the object of VisitormanagementRestService to visitormanagementRestService. +With visitormanagementRestService, it is calling the method "returnResponseToClient()" of server. +The response from server will be stored in "resultFromAPICall" as the return type of result is String. +After getting response, you can handle the response further in your implementation. Here, you can see that response is getting handled in "showResponse" method. +==== + + +==== +An application needs to be configurable in order to allow internal setup but also to allow externalized configuration of a deployed package (e.g. integration into runtime environment). +Now, You need to modify the content of existing properties files and add configuration for Server. +[step] +== Modify properties for server configuration +-- +changeFile("httprestclient/core/src/main/resources/application.properties", { "file": "files/client_application.txt" }) +changeFile("httprestclient/core/src/main/resources/config/application.properties", { "file": "files/client_config_application.txt" }) +-- +## Service Discovery +**service.client.default.url** :- It is used to set the default url of server and it is added for service discovery. + +**service.client.app.httprestserver.url** :- This property provide base url of REST in your application. It follows format such as "service.client.app.«application».url". Here, «application» refers to the technical name of the application providing the service. + +## Timeouts +**service.client.default.timeout.connection** :- It is used to set the default timeout for particular connection. + +**service.client.default.timeout.response** :- It is used to set the default timeout for particular response. + +## Headers +**service.client.app.httprestserver.auth** :- It is used for customization of Service Header. Here it is used for basic authentication. + +## Authentication +**service.client.app.httprestserver.user.login** :- It is used to set username of server for authentication. + +**service.client.app.httprestserver.user.password** :- It is used to set password. +==== + +==== +Now, Let's build and start the service client application. +This might take some time for application to start. +[step] +== Build devon4j CXF REST Client +-- +buildJava("httprestclient", false) +-- + +* Once, application builds successfully. Open new terminal by clicking "+" and wait for it to load. +* Now, Copy and execute below command to navigate into client server. + `cd devonfw/workspaces/main/httprestclient/server` +* Now, Copy and execute below command to start the application. + `devon mvn spring-boot:run` + +To test Synchronous method, follow below steps. +* Click on "+" next to terminal tab +* Select "select port to view host" +* Enter the port number "8080" +* In the url, append "/httprestclient/services/rest/testrest/v1/response/" +* Enter username as "admin" and password as "admin" +* You will be able to see response "Welcome to REST API world" +==== + +==== +You have successfully created devon4j CXF REST Client. +For more details on devon4j follow https://devonfw.com/website/pages/docs/devon4j.asciidoc.html +==== \ No newline at end of file diff --git a/devon4j-migrate/index.asciidoc b/devon4j-migrate/index.asciidoc new file mode 100644 index 000000000..1192f57fc --- /dev/null +++ b/devon4j-migrate/index.asciidoc @@ -0,0 +1,59 @@ += Migrate a devon4j project to the latest version + +[tags] +-- +difficulty=beginner +topic=migration;version +asset=devon4j +-- + +==== +This tutorial mainly focuses on migrating an older version of devon4j project to the latest version using devon4j migrate command. + + +## Prerequisites +* devonfw IDE + +## Learning goals. +Here in this tutorial you will learn +* How to migrate an older version of devon4j project to the latest version. +==== + +[step] +-- +restoreDevonfwIde(["java","vscode"]) +-- + + +[step] +-- +restoreWorkspace({"workspace": "devon4j-migrate"}) +-- + +==== +To demonstrate devon4j migrate you would need a sample devon4j project with any older version. Here, we have already created a project with an older version i.e. 2020.08.001 for you. + +It is already cloned in workspace. + +Execute below command for project migration from an older version to the latest version. +[step] +== Execute Migrate Command +-- +executeCommand("devon java migrate", "devon java migrate", {"dir" : "devon4j-app-4tutorial"}) +-- +You will see the message similar to the one below, if project migrated successfully. +`Successfully applied 4 migrations to migrate project from version devon4j:2020.08.001 to devon4j:2021.04.002.` + +Here, 2020.08.001 is the devon4j's older version and 2021.04.002 is devon4j's latest version. + +==== + + + +==== +## Conclusion +You have successfully migrated the sample project from an older version to the latest version using command line!! + +For more details on devon4j java commands for various functionalities and the arguments (devon java «args») follow +https://devonfw.com/website/pages/docs/devonfw-ide-usage.asciidoc.html#java.asciidoc +==== diff --git a/devon4ng-architecture/files/layers-explained.md b/devon4ng-architecture/files/layers-explained.md index f8e729d97..431bc5a40 100644 --- a/devon4ng-architecture/files/layers-explained.md +++ b/devon4ng-architecture/files/layers-explained.md @@ -1,5 +1,5 @@ -The applciation you see here is a clone of devon4ng-application-template. You can find it here [here](https://github.com/devonfw/devon4ng-application-template) +The application you see here is a clone of devon4ng-application-template. You can find it [here](https://github.com/devonfw/devon4ng-application-template) -The `SampleDataModule` is a nice exmple of the different layers explained. It holds some components (representing the *components* layer) and also has a `SampleDataService` (representing the *service* layer) which is imported in the required components. +The `SampleDataModule` is a nice example of the different layers explained. It holds some components (representing the *components* layer) and also has a `SampleDataService` (representing the *service* layer) which is imported in the required components. The service acts as the adapter element explained earlier (used to make XHR calls). \ No newline at end of file diff --git a/devon4ng-architecture/index.asciidoc b/devon4ng-architecture/index.asciidoc index dc9a8fe3c..bc0968b00 100644 --- a/devon4ng-architecture/index.asciidoc +++ b/devon4ng-architecture/index.asciidoc @@ -1,5 +1,14 @@ = devon4ng architecture == Understand the architecture principles followed by devon4ng (the angular asset of devonfw) + +[tags] +-- +technology=Angular +difficulty=beginner +topic=architecture;module +asset=devon4ng +-- + ==== ## Prerequisites @@ -27,35 +36,35 @@ addSetupScript("files/cloneProject.sh", "files/cloneProject.ps1") [step] -- -nextKatacodaStep("Overview", [{ "file": "files/overview.md" }]) +displayContent("Overview", [{ "file": "files/overview.md" }]) -- [step] -- -nextKatacodaStep("Architectural Layers", [{ "image": "images/architecture-layers.png" }, { "file": "files/layers.md" }]) +displayContent("Architectural Layers", [{ "image": "images/architecture-layers.png" }, { "file": "files/layers.md" }]) -- [step] -- openFile("devon4ng-application-template/src/app/sampledata/sampledata.module.ts") -nextKatacodaStep("Architectural Layers explained", [{ "file": "files/layers-explained.md" }]) +displayContent("Architectural Layers explained", [{ "file": "files/layers-explained.md" }]) openFile("devon4ng-application-template/src/app/sampledata/services/sampledata.service.ts") -- [step] -- -nextKatacodaStep("Modules", [{ "image": "images/architecture-modules.png" }, { "file": "files/modules.md" }]) +displayContent("Modules", [{ "image": "images/architecture-modules.png" }, { "file": "files/modules.md" }]) -- [step] -- -nextKatacodaStep("Core module", [{ "file": "files/core-shared-modules.md" }]) +displayContent("Core module", [{ "file": "files/core-shared-modules.md" }]) openFile("devon4ng-application-template/src/app/core/core.module.ts") -- [step] -- -nextKatacodaStep("Shared module", [{ "file": "files/core-shared-modules2.md" }]) +displayContent("Shared module", [{ "file": "files/core-shared-modules2.md" }]) openFile("devon4ng-application-template/src/app/layout/layout.module.ts") -- @@ -68,4 +77,6 @@ To conclude, in this tutorial you learned * the different types of modules - core, shared and feature Then we referred a devon4ng application by cloning it and traversing through its files. You can study in more detail about Angular architecture by following [this document](https://devonfw.com/website/pages/docs/master-devon4ng.asciidoc_architecture.html#meta-architecture.asciidoc_devonfw-reference-client-architecture). + +The idea with devon4ng is to define an architecture which is a compromise between, on the one hand, leveraging the best practices and latest trends like reactive style development, on the other hand, providing a short onboarding time while still using an architecture that helps us scale and be productive at the same time. ==== \ No newline at end of file diff --git a/devon4ng-lazy-loading/files/app-routing.module.ts.txt b/devon4ng-lazy-loading/files/app-routing.module.ts.txt new file mode 100644 index 000000000..ca1b26d6f --- /dev/null +++ b/devon4ng-lazy-loading/files/app-routing.module.ts.txt @@ -0,0 +1,21 @@ +import { NgModule } from '@angular/core'; +import { Routes, RouterModule } from '@angular/router'; +import { FirstComponent } from './first/first/first.component'; + +const routes: Routes = [ + { + path: 'first', + component: FirstComponent + }, + { + path: '', + redirectTo: 'first', + pathMatch: 'full', + }, +]; + +@NgModule({ + imports: [RouterModule.forRoot(routes)], + exports: [RouterModule] +}) +export class AppRoutingModule { } diff --git a/devon4ng-lazy-loading/files/app-routing.module.update2.ts.txt b/devon4ng-lazy-loading/files/app-routing.module.update2.ts.txt new file mode 100644 index 000000000..66b1993f2 --- /dev/null +++ b/devon4ng-lazy-loading/files/app-routing.module.update2.ts.txt @@ -0,0 +1,20 @@ +import { NgModule } from '@angular/core'; +import { Routes, RouterModule } from '@angular/router'; + +const routes: Routes = [ + { + path: 'first', + loadChildren: () => import('./first/first.module').then(m => m.FirstModule), + }, + { + path: '', + redirectTo: 'first', + pathMatch: 'full', + }, +]; + +@NgModule({ + imports: [RouterModule.forRoot(routes)], + exports: [RouterModule] +}) +export class AppRoutingModule { } diff --git a/devon4ng-lazy-loading/files/app.component.html.txt b/devon4ng-lazy-loading/files/app.component.html.txt new file mode 100644 index 000000000..90c6b6463 --- /dev/null +++ b/devon4ng-lazy-loading/files/app.component.html.txt @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/devon4ng-lazy-loading/files/app.module.ts.txt b/devon4ng-lazy-loading/files/app.module.ts.txt new file mode 100644 index 000000000..ec57d1d3b --- /dev/null +++ b/devon4ng-lazy-loading/files/app.module.ts.txt @@ -0,0 +1,20 @@ +import { BrowserModule } from '@angular/platform-browser'; +import { NgModule } from '@angular/core'; + +import { AppRoutingModule } from './app-routing.module'; +import { AppComponent } from './app.component'; +import { FirstModule } from './first/first.module'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ + BrowserModule, + AppRoutingModule, + FirstModule + ], + providers: [], + bootstrap: [AppComponent] +}) +export class AppModule { } diff --git a/devon4ng-lazy-loading/files/app.module.ts.update2.txt b/devon4ng-lazy-loading/files/app.module.ts.update2.txt new file mode 100644 index 000000000..d718d9ba2 --- /dev/null +++ b/devon4ng-lazy-loading/files/app.module.ts.update2.txt @@ -0,0 +1,18 @@ +import { BrowserModule } from '@angular/platform-browser'; +import { NgModule } from '@angular/core'; + +import { AppRoutingModule } from './app-routing.module'; +import { AppComponent } from './app.component'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ + BrowserModule, + AppRoutingModule, + ], + providers: [], + bootstrap: [AppComponent] +}) +export class AppModule { } diff --git a/devon4ng-lazy-loading/files/content-right.component.html.txt b/devon4ng-lazy-loading/files/content-right.component.html.txt new file mode 100644 index 000000000..0d2605158 --- /dev/null +++ b/devon4ng-lazy-loading/files/content-right.component.html.txt @@ -0,0 +1,11 @@ +
+

Welcome to 2nd level module (right)

+ Angular Logo +
+
+ +
diff --git a/devon4ng-lazy-loading/files/content.component.html.txt b/devon4ng-lazy-loading/files/content.component.html.txt new file mode 100644 index 000000000..c32b105f0 --- /dev/null +++ b/devon4ng-lazy-loading/files/content.component.html.txt @@ -0,0 +1,13 @@ +
+

+ Welcome to 2nd level module (left) +

+ Angular Logo +
+
+ +
\ No newline at end of file diff --git a/devon4ng-lazy-loading/files/content.component.ts.txt b/devon4ng-lazy-loading/files/content.component.ts.txt new file mode 100644 index 000000000..bafad404f --- /dev/null +++ b/devon4ng-lazy-loading/files/content.component.ts.txt @@ -0,0 +1,15 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'app-content', + templateUrl: './content.component.html', + styleUrls: ['./content.component.scss'] +}) +export class ContentComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devon4ng-lazy-loading/files/empty-file.txt b/devon4ng-lazy-loading/files/empty-file.txt new file mode 100644 index 000000000..0519ecba6 --- /dev/null +++ b/devon4ng-lazy-loading/files/empty-file.txt @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/devon4ng-lazy-loading/files/first-routing.module.ts.txt b/devon4ng-lazy-loading/files/first-routing.module.ts.txt new file mode 100644 index 000000000..267407558 --- /dev/null +++ b/devon4ng-lazy-loading/files/first-routing.module.ts.txt @@ -0,0 +1,10 @@ +import { NgModule } from '@angular/core'; +import { Routes, RouterModule } from '@angular/router'; + +const routes: Routes = []; + +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule] +}) +export class FirstRoutingModule { } diff --git a/devon4ng-lazy-loading/files/first-routing.module.update1.ts.txt b/devon4ng-lazy-loading/files/first-routing.module.update1.ts.txt new file mode 100644 index 000000000..ebaa1e461 --- /dev/null +++ b/devon4ng-lazy-loading/files/first-routing.module.update1.ts.txt @@ -0,0 +1,26 @@ +import { NgModule } from '@angular/core'; +import { Routes, RouterModule } from '@angular/router'; +import { ContentComponent as ContentLeft} from './second-left/content/content.component'; +import { ContentComponent as ContentRight} from './second-right/content/content.component'; +import { FirstComponent } from './first/first.component'; + +const routes: Routes = [ + { + path: '', + component: FirstComponent + }, + { + path: 'first/second-left', + component: ContentLeft + }, + { + path: 'first/second-right', + component: ContentRight + } +]; + +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule] +}) +export class FirstRoutingModule { } diff --git a/devon4ng-lazy-loading/files/first-routing.module.update2.ts.txt b/devon4ng-lazy-loading/files/first-routing.module.update2.ts.txt new file mode 100644 index 000000000..cb4a17c8a --- /dev/null +++ b/devon4ng-lazy-loading/files/first-routing.module.update2.ts.txt @@ -0,0 +1,26 @@ +import { NgModule } from '@angular/core'; +import { Routes, RouterModule } from '@angular/router'; +import { ContentComponent as ContentLeft} from './second-left/content/content.component'; +import { ContentComponent as ContentRight} from './second-right/content/content.component'; +import { FirstComponent } from './first/first.component'; + +const routes: Routes = [ + { + path: '', + component: FirstComponent + }, + { + path: 'second-left', + component: ContentLeft + }, + { + path: 'second-right', + component: ContentRight + } +]; + +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule] +}) +export class FirstRoutingModule { } diff --git a/devon4ng-lazy-loading/files/first-routing.module.update3.ts.txt b/devon4ng-lazy-loading/files/first-routing.module.update3.ts.txt new file mode 100644 index 000000000..b73fc0da6 --- /dev/null +++ b/devon4ng-lazy-loading/files/first-routing.module.update3.ts.txt @@ -0,0 +1,26 @@ +import { NgModule } from '@angular/core'; +import { Routes, RouterModule } from '@angular/router'; +import { ContentComponent as ContentLeft} from './second-left/content/content.component'; +import { ContentComponent as ContentRight} from './second-right/content/content.component'; +import { FirstComponent } from './first/first.component'; + +const routes: Routes = [ + { + path: '', + component: FirstComponent + }, + { + path: 'second-left', + loadChildren: () => import('./second-left/second-left.module').then(m => m.SecondLeftModule), + }, + { + path: 'second-right', + component: ContentRight + } +]; + +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule] +}) +export class FirstRoutingModule { } diff --git a/devon4ng-lazy-loading/files/first.component.html.txt b/devon4ng-lazy-loading/files/first.component.html.txt new file mode 100644 index 000000000..94ff7ada2 --- /dev/null +++ b/devon4ng-lazy-loading/files/first.component.html.txt @@ -0,0 +1,14 @@ +
+

+ Welcome to 1st level module +

+ Angular Logo +
+
+ + +
\ No newline at end of file diff --git a/devon4ng-lazy-loading/files/first.component.ts.txt b/devon4ng-lazy-loading/files/first.component.ts.txt new file mode 100644 index 000000000..1d152df8d --- /dev/null +++ b/devon4ng-lazy-loading/files/first.component.ts.txt @@ -0,0 +1,15 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'app-first', + templateUrl: './first.component.html', + styleUrls: ['./first.component.scss'] +}) +export class FirstComponent implements OnInit { + + constructor() { } + + ngOnInit(): void { + } + +} diff --git a/devon4ng-lazy-loading/files/first.module.ts.txt b/devon4ng-lazy-loading/files/first.module.ts.txt new file mode 100644 index 000000000..c33df7b0a --- /dev/null +++ b/devon4ng-lazy-loading/files/first.module.ts.txt @@ -0,0 +1,14 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; + +import { FirstRoutingModule } from './first-routing.module'; + + +@NgModule({ + declarations: [], + imports: [ + CommonModule, + FirstRoutingModule + ] +}) +export class FirstModule { } diff --git a/devon4ng-lazy-loading/files/first.module.ts.update1.ts.txt b/devon4ng-lazy-loading/files/first.module.ts.update1.ts.txt new file mode 100644 index 000000000..9f72da94b --- /dev/null +++ b/devon4ng-lazy-loading/files/first.module.ts.update1.ts.txt @@ -0,0 +1,19 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; + +import { FirstRoutingModule } from './first-routing.module'; +import { FirstComponent } from './first/first.component'; + +import { SecondLeftModule } from './second-left/second-left.module'; +import { SecondRightModule } from './second-right/second-right.module'; + +@NgModule({ + declarations: [FirstComponent], + imports: [ + CommonModule, + FirstRoutingModule, + SecondLeftModule, + SecondRightModule, + ] +}) +export class FirstModule { } diff --git a/devon4ng-lazy-loading/files/first.module.update3.ts.txt b/devon4ng-lazy-loading/files/first.module.update3.ts.txt new file mode 100644 index 000000000..e1c763053 --- /dev/null +++ b/devon4ng-lazy-loading/files/first.module.update3.ts.txt @@ -0,0 +1,17 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; + +import { FirstRoutingModule } from './first-routing.module'; +import { FirstComponent } from './first/first.component'; + +import { SecondRightModule } from './second-right/second-right.module'; + +@NgModule({ + declarations: [FirstComponent], + imports: [ + CommonModule, + FirstRoutingModule, + SecondRightModule, + ] +}) +export class FirstModule { } diff --git a/devon4ng-lazy-loading/files/second-left-routing.module.ts.txt b/devon4ng-lazy-loading/files/second-left-routing.module.ts.txt new file mode 100644 index 000000000..3b8fac1e1 --- /dev/null +++ b/devon4ng-lazy-loading/files/second-left-routing.module.ts.txt @@ -0,0 +1,10 @@ +import { NgModule } from '@angular/core'; +import { Routes, RouterModule } from '@angular/router'; + +const routes: Routes = []; + +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule] +}) +export class SecondLeftRoutingModule { } diff --git a/devon4ng-lazy-loading/files/second-left-routing.module.update3.ts.txt b/devon4ng-lazy-loading/files/second-left-routing.module.update3.ts.txt new file mode 100644 index 000000000..8b704a899 --- /dev/null +++ b/devon4ng-lazy-loading/files/second-left-routing.module.update3.ts.txt @@ -0,0 +1,16 @@ +import { NgModule } from '@angular/core'; +import { Routes, RouterModule } from '@angular/router'; +import { ContentComponent } from './content/content.component'; + +const routes: Routes = [ + { + path: '', + component: ContentComponent + } +]; + +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule] +}) +export class SecondLeftRoutingModule { } diff --git a/devon4ng-lazy-loading/files/second-left.module.ts.txt b/devon4ng-lazy-loading/files/second-left.module.ts.txt new file mode 100644 index 000000000..0eb395b69 --- /dev/null +++ b/devon4ng-lazy-loading/files/second-left.module.ts.txt @@ -0,0 +1,15 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; + +import { SecondLeftRoutingModule } from './second-left-routing.module'; +import { ContentComponent } from './content/content.component'; + + +@NgModule({ + declarations: [ContentComponent], + imports: [ + CommonModule, + SecondLeftRoutingModule + ] +}) +export class SecondLeftModule { } diff --git a/devon4ng-lazy-loading/files/second-right-routing.module.ts.txt b/devon4ng-lazy-loading/files/second-right-routing.module.ts.txt new file mode 100644 index 000000000..20c8b6228 --- /dev/null +++ b/devon4ng-lazy-loading/files/second-right-routing.module.ts.txt @@ -0,0 +1,10 @@ +import { NgModule } from '@angular/core'; +import { Routes, RouterModule } from '@angular/router'; + +const routes: Routes = []; + +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule] +}) +export class SecondRightRoutingModule { } diff --git a/devon4ng-lazy-loading/files/second-right.module.ts.txt b/devon4ng-lazy-loading/files/second-right.module.ts.txt new file mode 100644 index 000000000..8ab855b68 --- /dev/null +++ b/devon4ng-lazy-loading/files/second-right.module.ts.txt @@ -0,0 +1,15 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; + +import { SecondRightRoutingModule } from './second-right-routing.module'; +import { ContentComponent } from './content/content.component'; + + +@NgModule({ + declarations: [ContentComponent], + imports: [ + CommonModule, + SecondRightRoutingModule + ] +}) +export class SecondRightModule { } diff --git a/devon4ng-lazy-loading/images/compile-eager.png b/devon4ng-lazy-loading/images/compile-eager.png new file mode 100644 index 000000000..ffce0d19d Binary files /dev/null and b/devon4ng-lazy-loading/images/compile-eager.png differ diff --git a/devon4ng-lazy-loading/images/compile-first-lazy.png b/devon4ng-lazy-loading/images/compile-first-lazy.png new file mode 100644 index 000000000..8bd56e5d3 Binary files /dev/null and b/devon4ng-lazy-loading/images/compile-first-lazy.png differ diff --git a/devon4ng-lazy-loading/images/first-lvl-lazy.png b/devon4ng-lazy-loading/images/first-lvl-lazy.png new file mode 100644 index 000000000..7f89915db Binary files /dev/null and b/devon4ng-lazy-loading/images/first-lvl-lazy.png differ diff --git a/devon4ng-lazy-loading/images/levels-app.png b/devon4ng-lazy-loading/images/levels-app.png new file mode 100644 index 000000000..0a147442d Binary files /dev/null and b/devon4ng-lazy-loading/images/levels-app.png differ diff --git a/devon4ng-lazy-loading/images/second-lvl-lazy.png b/devon4ng-lazy-loading/images/second-lvl-lazy.png new file mode 100644 index 000000000..0afe2f5a6 Binary files /dev/null and b/devon4ng-lazy-loading/images/second-lvl-lazy.png differ diff --git a/devon4ng-lazy-loading/images/second-lvl-left-lazy.png b/devon4ng-lazy-loading/images/second-lvl-left-lazy.png new file mode 100644 index 000000000..b2005351b Binary files /dev/null and b/devon4ng-lazy-loading/images/second-lvl-left-lazy.png differ diff --git a/devon4ng-lazy-loading/images/second-lvl-right-eager.png b/devon4ng-lazy-loading/images/second-lvl-right-eager.png new file mode 100644 index 000000000..c55c77e20 Binary files /dev/null and b/devon4ng-lazy-loading/images/second-lvl-right-eager.png differ diff --git a/devon4ng-lazy-loading/index.asciidoc b/devon4ng-lazy-loading/index.asciidoc new file mode 100644 index 000000000..db982107e --- /dev/null +++ b/devon4ng-lazy-loading/index.asciidoc @@ -0,0 +1,127 @@ += Boost Angular’s Performance by Lazy Loading your Modules with devon4ng +== Learn how to defer initialization of modules in Angular until it is needed + +[tags] +-- +technology=Angular +difficulty=intermediate +topic=architecture;lazy loading;module;design pattern +asset=devon4ng +-- + +==== +In single-page-applications as the application size increases its loading speed decreases (since typically the entire application is loaded at once). Lazy loading is a design pattern that defers initialization of objects until it is needed. Angular handles lazy loading through the routing module which redirects to requested pages. Those pages can be loaded at start or on demand. In this tutorial you will build a simple app to understand how lazyloading is implemented in Angular. + +## Prerequisites +* Basic Angular knowledge + +## Learning goals +In this tutorial you will learn how to: +* create an Angular application using the devon command +* look how all modules are loaded by an application at the begining (eager loading) +* implement lazy loading and understand its concept and advantages +==== + +[step] +-- +restoreDevonfwIde(["npm", "ng", "vscode"]) +-- + +To explain how lazy loading is implemented using angular, a basic sample app is going to be developed. This app will consist in a window named "level 1" that contains two buttons that redirects to other windows in a "second level". It is a simple example, but useful to understand the relation between angular modules and lazy loading. + +![levels-app](./assets/levels-app.png) + +This graphic shows that modules acts as gates to access components "inside" them. + +Because the objective of this guide is related mainly with logic, the html structure and scss styles are less relevant. + +Before creating a devon4ng application, you first have to install the devonfw ide. You will find more information about devonfw on https://devonfw.com/website/pages/welcome/welcome.html. +Once you have setup devonfw ide, you are ready to create your devon4ng application. (Please wait until the devon setup completes and the command prompt appears in the integrated terminal here). +[step] +== Introduction +-- +createDevon4ngProject("level-app", "", ["--style=scss", "--routing=true", "--strict=false", "--skip-git=true"]) +-- + +In the file app.component.html delete all the content and put in the `router-outlet` tag. +[step] +== Enable routing with router-outlet +-- +changeFile("level-app/src/app/app.component.html", { "file": "files/app.component.html.txt" }) +-- + +Next you will create the feature modules and components for the app. You will follow the structure shown in the image in the first step. You can use the CLI command `devon ng generate module` along with the `--routing` flag to generate the modules, and `devon ng generate component` command to generate the components. +[step] +== Create the modules and their components +-- +createFile("level-app/src/app/first/first-routing.module.ts", "files/first-routing.module.ts.txt") +createFile("level-app/src/app/first/first.module.ts", "files/first.module.ts.txt") +createFile("level-app/src/app/first/second-left/second-left-routing.module.ts", "files/second-left-routing.module.ts.txt") +createFile("level-app/src/app/first/second-left/second-left.module.ts", "files/second-left.module.ts.txt") +createFile("level-app/src/app/first/second-right/second-right-routing.module.ts", "files/second-right-routing.module.ts.txt") +createFile("level-app/src/app/first/second-right/second-right.module.ts", "files/second-right.module.ts.txt") +createFile("level-app/src/app/first/first/first.component.html", "files/first.component.html.txt") +createFile("level-app/src/app/first/first/first.component.scss", "files/empty-file.txt") +createFile("level-app/src/app/first/first/first.component.ts", "files/first.component.ts.txt") +createFile("level-app/src/app/first/second-left/content/content.component.html", "files/content.component.html.txt") +createFile("level-app/src/app/first/second-left/content/content.component.scss", "files/empty-file.txt") +createFile("level-app/src/app/first/second-left/content/content.component.ts", "files/content.component.ts.txt") +createFile("level-app/src/app/first/second-right/content/content.component.html", "files/content-right.component.html.txt") +createFile("level-app/src/app/first/second-right/content/content.component.scss", "files/empty-file.txt") +createFile("level-app/src/app/first/second-right/content/content.component.ts", "files/content.component.ts.txt") +-- + +To move between the components you will now configure the routes. You can refer the image in the first step to understand how you will configure the routes. +In `app-routing.module.ts` you will add a path 'first' to `FirstComponent` and a redirection from '' to 'first'. And then import the `FirstModule` in the main `app.module.ts` + +Next, for the feature modules, you will add the routes 'first/second-left' and 'first/second-right' pointing to their respective `ContentComponent` in `first-routing.module.ts`. And then import `SecondLeftModule` and `SecondRightModule` in `first.module.ts` +[step] +== Configure routing +-- +changeFile("level-app/src/app/app-routing.module.ts", { "file": "files/app-routing.module.ts.txt" }) +changeFile("level-app/src/app/app.module.ts", { "file": "files/app.module.ts.txt" }) +changeFile("level-app/src/app/first/first-routing.module.ts", { "file": "files/first-routing.module.update1.ts.txt" }) +changeFile("level-app/src/app/first/first.module.ts", { "file": "files/first.module.ts.update1.ts.txt" }) +runClientNg("level-app", { "startupTime": 200, "port": 4200, "path": "" }) +-- + +If you run the project at this point you can see in the terminal that just the main file is built. +![compile-eager](./assets/compile-eager.png) + +Go to port 4200 and check the Network tab in the Developer Tools. We can see a document named "first" is loaded. If you click on [Go to right module] a second level module opens, but there is no 'second-right' document. +![second-lvl-right-eager](./assets/second-lvl-right-eager.png) + +Now we will modify the app to lazily load the modules. Modifying an angular application to load its modules lazily is easy, you have to change the routing configuration of the desired module (for example `FirstModule`). Instead of loading a component, you dynamically import it in a `loadChildren` attribute because modules acts as gates to access components "inside" them. Updating this app to load lazily has four consecuences: no component attribute, no import of `FirstComponent`, `FirstModule` import has to be removed from the imports array at `app.module.ts`, and change of context. + +Also, in `first-routing.module.ts` you can change the path for the `ContentComponent`s from `first/second-left` and `first/second-right` to simply `second-left` and `second-right` respectively, because it aquires the context set by AppRoutingModule. +[step] +== Eager loading vs Lazy Loading +-- +changeFile("level-app/src/app/app-routing.module.ts", { "file": "files/app-routing.module.update2.ts.txt" }) +changeFile("level-app/src/app/app.module.ts", { "file": "files/app.module.ts.update2.txt" }) +changeFile("level-app/src/app/first/first-routing.module.ts", { "file": "files/first-routing.module.update2.ts.txt" }) +-- + +==== +Now when you check the terminal running the app, you could see the lazy loaded modules getting generated along with the main bundle. Also, if you check the Network tab in the developer tools, you could see the (lazy) modules getting loaded when needed. Since, `FirstModule` is the first path we visit, it is getting loaded at first only. +![compile-first-lazy](./assets/compile-first-lazy.png) +![first-lvl-lazy](./assets/first-lvl-lazy.png) + +Now, lets make the SecondLeftModule load lazily. For this, you need to change `component` to `loadChildren` and refer `SecondLeftModule` in the file `first-routing.module.ts`. Next, you need to remove `SecondLeftModule` from the `imports` array of `first.module.ts`. After that you need to route the `ContentComponent` within the `second-left-routing.module.ts`. +[step] +== Lazily load the second left module +-- +changeFile("level-app/src/app/first/first-routing.module.ts", { "file": "files/first-routing.module.update3.ts.txt" }) +changeFile("level-app/src/app/first/first.module.ts", { "file": "files/first.module.update3.ts.txt" }) +changeFile("level-app/src/app/first/second-left/second-left-routing.module.ts", { "file": "files/second-left-routing.module.update3.ts.txt" }) +-- +If you now check the terminal, you could also see `second-left-second-left-module` along with the `first-first-module` and the `main` bundle getting generated. +![second-lvl-lazy](./assets/second-lvl-lazy.png) + +Also, in the Network tab of the developer tools, you could see the `second-left-second-left-module.js` is only loading when we click on the [Go to left module] button +![second-lvl-left-lazy](./assets/second-lvl-left-lazy.png) +==== + +==== +Lazy loading is a pattern useful when new features are added, these features are usually identified as modules which can be loaded only if needed as shown in this tutorial, reducing the time spent loading an application. +==== \ No newline at end of file diff --git a/devon4ng-mat-layout/index.asciidoc b/devon4ng-mat-layout/index.asciidoc index 504a1495f..298c6e0e4 100644 --- a/devon4ng-mat-layout/index.asciidoc +++ b/devon4ng-mat-layout/index.asciidoc @@ -1,76 +1,91 @@ = Create an Angular application with Angular Material components using devon4ng + +[tags] +-- +technology=Angular +difficulty=beginner +topic=style;UI component library;component;animation;layout +asset=devon4ng +-- + ==== -The purpose of this tutorial is to get a basic understanding of creating layouts using Angular Material in a devon4ng application. We will create an application with a header containing some menu links and a sidenav with some navigation links. +The purpose of this tutorial is to get a basic understanding of creating layouts using Angular Material in a devon4ng application. You will create an application with a header containing some menu links and a sidenav with some navigation links. -## Prerequisites -* devonfw-ide installed +### Prerequisites * Basic Angular knowledge -## Learning goals -In this tutorial we will learn how to: +### Learning goals +In this tutorial you will learn how to: * create an Angular application using the devon command * add Angular Material to the application -* import Angular Material components into our modules +* import Angular Material components into your modules * use Material icons in the application * use a prebulit theme to style the application -* create layout (conataining a header with menu along with a sidenav with navigational links) with the Angular Material components +* create layout (containing a header with menu along with a sidenav with navigational links) with the Angular Material components ==== [step] -- -restoreDevonfwIde(["java","mvn", "npm", "ng"]) +restoreDevonfwIde(["npm", "ng", "vscode"]) -- Before creating a devon4ng application, you first have to install the devonfw ide. You will find more information about devonfw on https://devonfw.com/website/pages/welcome/welcome.html. -Once you have setup devonfw ide, you are ready to create your first devon4ng project. +Once you have setup devonfw ide, you are ready to create your first devon4ng project.(Please wait until the devon setup completes and the command prompt becomes ready for writing commands in the integrated terminal here). [step] -- createDevon4ngProject("devon4ng-mat-layout", "", ["--style=scss", "--routing=true", "--strict=false"]) runClientNg("devon4ng-mat-layout", { "startupTime": 200, "port": 4200, "path": "" }) -- -Next we will add Angular Material to our application. +Next you will add Angular Material to your application. [step] +== Add Angular Material -- npmInstall("devon4ng-mat-layout", {"name": "@angular/material @angular/cdk @angular/animations", "args": ["--save"]}) -- -Once the dependencies are installed, we need to import the BrowserAnimationsModule in our AppModule for animations support. -Also, Angular Material provides a host of components for designing our application. All the components are well structured into NgModules. For each component from the Angular Material library that we want to use, we have to import the respective NgModule. +Once the dependencies are installed, you need to import the BrowserAnimationsModule in your AppModule for animations support. +Also, Angular Material provides a host of components for designing your application. All the components are well structured into NgModules. For each component from the Angular Material library that you want to use, you have to import the respective NgModule. [step] +== Import Material components -- changeFile("devon4ng-mat-layout/src/app/app.module.ts", { "file": "files/app.module.txt" }) -- -To use Material Design Icons along with the mat-icon component, we will load the Material Icons library in our `src/index.html` file. +To use Material Design Icons along with the mat-icon component, you will load the Material Icons library in your `src/index.html` file. [step] +== Load Material icons -- changeFile("devon4ng-mat-layout/src/index.html", { "file": "files/index.txt" }) -- -Now that we have all the Angular Material related dependencies set up in our project, we can start coding. Let’s begin by adding a suitable `margin` and `font` to the body element of our single page application. We will add it in the `src/styles.scss` file to apply it globally. +Now that you have all the Angular Material related dependencies set up in your project, you can start coding. Let’s begin by adding a suitable `margin` and `font` to the body element of your single page application. You will add it in the `src/styles.scss` file to apply it globally. [step] +== Add global styles -- changeFile("devon4ng-mat-layout/src/styles.scss", { "file": "files/styles.txt" }) -- ==== -We will clear the `app.component.html` file and setup a header with a menu button and some navigational links. We will use `mat-toolbar`, `mat-button`, `mat-menu`, `mat-icon` and `mat-icon-button` for this: +Clear the `app.component.html` file and setup a header with a menu button and some navigational links. You will use `mat-toolbar`, `mat-button`, `mat-menu`, `mat-icon` and `mat-icon-button` for this: [step] +== Add a header -- changeFile("devon4ng-mat-layout/src/app/app.component.html", { "file": "files/app.component.txt" }) -- -The color attribute on the mat-toolbar element will give it the primary (indigo) color as defined by our theme. The color attribute works with most Angular Material components; the possible values are `primary`, `accent` and `warn`. The `mat-toolbar` is a suitable component to represent a header. It serves as a placeholder for elements we want in our header. Inside the `mat-toolbar`, we start with a button having `mat-icon-button` attribute, which itself contains a `mat-icon` element having the value `menu`. This will serve as a menu button which we can use to toggle the `sidenav`. We follow it with some sample buttons having the `mat-button` attribute. Notice the first button has a property `matMenuTriggerFor` binded to a local reference submenu. As the property name suggests, the click of this button will display the mat-menu element with the specified local reference as a drop-down menu. The rest of the code is self explanatory. +The color attribute on the mat-toolbar element will give it the primary (indigo) color as defined by your theme. The color attribute works with most Angular Material components; the possible values are `primary`, `accent` and `warn`. The `mat-toolbar` is a suitable component to represent a header. It serves as a placeholder for elements you want in your header. Inside the `mat-toolbar`, you start with a button having `mat-icon-button` attribute, which itself contains a `mat-icon` element having the value `menu`. This will serve as a menu button which you can use to toggle the `sidenav`. You follow it with some sample buttons having the `mat-button` attribute. Notice the first button has a property `matMenuTriggerFor` binded to a local reference submenu. As the property name suggests, the click of this button will display the mat-menu element with the specified local reference as a drop-down menu. The rest of the code is self explanatory. ==== -We want to keep the sidenav toggling menu button on the left and move the rest to the right to make it look better. To do this lets add the following style to the `menu` class in `app.component.scss`: +You want to keep the sidenav toggling menu button on the left and move the rest to the right to make it look better. To do this add the following style to the `menu` class in `app.component.scss`: [step] +== Shift header menu buttons to right -- changeFile("devon4ng-mat-layout/src/app/app.component.scss", { "file": "files/app.component.scss.txt" }) -- -Next, we will create a sidenav. But before that lets create a couple of components to navigate between, the links of which we will add to the sidenav. You can use the `ng generate component` (or `ng g c` command for short) to create Home and Data components. But here, we will create them manually. We nest them in the `pages` sub-directory since they represent our pages. And we will also add the new components to our AppModule. +Next, you will create a sidenav. But before that lets create a couple of components to navigate between, the links of which you will add to the sidenav. You can use the `ng generate component` (or `ng g c` command for short) to create Home and Data components. But here, you will create them manually. You nest them in the `pages` sub-directory since they represent your pages. And you will also add the new components to your AppModule. [step] +== Create navigatable pages -- createFile("devon4ng-mat-layout/src/app/pages/home/home.component.html", "files/home.component.txt") createFile("devon4ng-mat-layout/src/app/pages/home/home.component.scss", "files/home.component.scss.txt") @@ -81,28 +96,35 @@ createFile("devon4ng-mat-layout/src/app/pages/data/data.component.ts", "files/da changeFile("devon4ng-mat-layout/src/app/app.module.ts", { "file": "files/app.module-components.txt" }) -- -Let us set up the routing such that when we visit the root url we see the `HomeComponent` and when we visit `/data` url we see the `DataComponent`. We had opted for routing while creating the application, so we have the routing module `app-routing.module.ts` setup for us. In this file, we have the empty routes array where we set up our routes: +Let us set up the routing such that when you visit the root url you see the `HomeComponent` and when you visit `/data` url you see the `DataComponent`. You had opted for routing while creating the application, so you have the routing module `app-routing.module.ts` setup for us. In this file, you have the empty routes array where you set up your routes: [step] +== Add routing -- changeFile("devon4ng-mat-layout/src/app/app-routing.module.ts", { "file": "files/app-routing.module.txt" }) -- -We need to provide a hook where the components will be loaded when their respective URLs are loaded. We do that by using the `router-outlet` directive in the `app.component.html`: +You need to provide a hook where the components will be loaded when their respective URLs are loaded. You do that by using the `router-outlet` directive in the `app.component.html`: [step] -- changeFile("devon4ng-mat-layout/src/app/app.component.html", { "file": "files/app.component-routing.txt" }) -- -Let us finally create the sidenav. To implement the sidenav we need to use 3 Angular Material components: `mat-sidenav-container`, `mat-sidenav` and `mat-sidenav-content`. The `mat-sidenav-container`, as the name suggests, acts as a container for the `sidenav` and the associated content. So it is the parent element, and `mat-sidenav` and `mat-sidenav-content` are the children sibling elements. `mat-sidenav` represents the sidenav. We can put any content we want, though it is usually used to conatain a list of navigational links. The `mat-sidenav-content` element is for conataining our main page content. Since we need the `sidenav` application-wide, we will put it in the `app.component.html` +Let us finally create the sidenav. To implement the sidenav you need to use 3 Angular Material components: `mat-sidenav-container`, `mat-sidenav` and `mat-sidenav-content`. The `mat-sidenav-container`, as the name suggests, acts as a container for the `sidenav` and the associated content. So it is the parent element, and `mat-sidenav` and `mat-sidenav-content` are the children sibling elements. `mat-sidenav` represents the sidenav. You can put any content you want, though it is usually used to conatain a list of navigational links. The `mat-sidenav-content` element is for conataining your main page content. Since you need the `sidenav` application-wide, you will put it in the `app.component.html` [step] +== Create the sidenav -- changeFile("devon4ng-mat-layout/src/app/app.component.html", { "file": "files/app.component-sidenav.txt" }) changeFile("devon4ng-mat-layout/src/app/app.component.scss", { "file": "files/app.component-sidenav.scss.txt" }) -- -The sidenav’s width will be corrected when we add the navigational links to it. That is the only thing remaining to be done. Lets implement it now: +The sidenav’s width will be corrected when you add the navigational links to it. That is the only thing remaining to be done. Lets implement it now: [step] +== Style the sidenav -- changeFile("devon4ng-mat-layout/src/app/app.component.html", { "file": "files/app.component-navlinks.txt" }) changeFile("devon4ng-mat-layout/src/app/app.component.scss", { "file": "files/app.component-navlinks.scss.txt" }) --- \ No newline at end of file +-- + +==== +In this tutorial you learned how to create an angular application using devonfw-ide, add Angular Material to it and use its components to create a simple layout. +==== \ No newline at end of file diff --git a/devonfw-ide/index.asciidoc b/devonfw-ide/index.asciidoc index c81a38fd3..d2552bd03 100644 --- a/devonfw-ide/index.asciidoc +++ b/devonfw-ide/index.asciidoc @@ -1,13 +1,22 @@ = Bootstrap your devonfw development environment + +[tags] +-- +technology=devonfw IDE +difficulty=beginner +topic=setup;IDE;installation +asset=devonfw IDE +-- + ==== devonfw offers complete IDE solution integrated with a lot​ of integrated tooling and initial settings​. It massively speeds up development, reduces risks and helps deliver better results. -## Prerequisites +### Prerequisites * User should have a prior experience with Eclipse or any IDE. -## Learning goals -1. After completing this scenario, you will have learned how to install devonfw development environment i.e., the devonfw IDE. +### Learning goals +* After completing this scenario, you will have learned how to install devonfw development environment i.e., the devonfw IDE. More information about devonfw IDE can be found on https://devonfw.com/website/pages/docs/devonfw-ide-introduction.asciidoc.html diff --git a/getPlaybookCheckout.js b/getPlaybookCheckout.js new file mode 100644 index 000000000..6e41a6004 --- /dev/null +++ b/getPlaybookCheckout.js @@ -0,0 +1,29 @@ +const core = require("@actions/core"); +const { Octokit } = require("@octokit/core"); +const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN }); + +async function getPlaybookCheckout() { + let pr = process.env.PR_NUMBER; + let head = ""; + try { + let get = await octokit.request('GET /repos/{owner}/{repo}/pulls/{pull_number}', { + owner: 'devonfw-tutorials', + repo: 'tutorials', + pull_number: pr + }); + head = get.data.head; + } catch(e) { + throw e; + } + core.info(`ref: ${head.ref}`); + core.setOutput('ref', head.ref); + core.info(`name : ${head.user.login}`); + core.setOutput('name', head.user.login); + +} + +getPlaybookCheckout().catch(err => { + console.log(err); + process.exit(1); +}); + diff --git a/openapi-generation-servicedocgen/files/pom.xml b/openapi-generation-servicedocgen/files/pom.xml new file mode 100644 index 000000000..4cae6bcc2 --- /dev/null +++ b/openapi-generation-servicedocgen/files/pom.xml @@ -0,0 +1,154 @@ + + + 4.0.0 + org.acme + rest-json-quickstart + 1.0.0-SNAPSHOT + + quarkus-bom + io.quarkus + 2.5.1.Final + 3.0.0-M5 + UTF-8 + 11 + 11 + + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + + io.quarkus + quarkus-resteasy-jackson + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + + + + org.codehaus.mojo + servicedocgen-maven-plugin + 1.0.0 + + + + generate + + + + + + + Order Service REST API Documentation + This documentation describes the REST API of the order service + + icsddevonfwsupport.apps2@capgemini.com + devon4j support + https://devonfw.com + + + https://github.com/devonfw-sample/devon4quarkus-order/blob/master/LICENSE + Apache License 2.0 + + + / + + http + + + .*Resource.* + + + + + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + + + + build + + + + + + + + + native + + + native + + + + native + + + + + org.apache.maven.plugins + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + + diff --git a/openapi-generation-servicedocgen/index.asciidoc b/openapi-generation-servicedocgen/index.asciidoc new file mode 100644 index 000000000..e667f3a18 --- /dev/null +++ b/openapi-generation-servicedocgen/index.asciidoc @@ -0,0 +1,86 @@ += OpenAPI and Swagger UI generation with ServicedocGen plugin + +[tags] +-- +technology=OpenAPI;Maven;Quarkus;Swagger +difficulty=intermediate +topic=plugin;documentation +asset=devon4j +-- + +==== +This tutorial will teach you how to use the [ServicedocGen maven plugin](http://www.mojohaus.org/servicedocgen-maven-plugin/) to generate the OpenAPI specification and Swagger UI from your REST APIs. + +The plugin analysis the REST APIs and the associated JavaDoc and then generates the OpenAPI specification as a static file. It is also able to create an HTML file that represents the Swagger UI and can be served by Quarkus to provide the Swagger UI in the browser. + +For more information about OpenAPI and the ServicedocGen plugin, see the [devon4j documentation](https://github.com/devonfw/devon4j/blob/master/documentation/guide-openapi.asciidoc). + +### Prerequisites +* Installed devonfw-ide (or at least Java and Maven installed) + +### Learning goals +* You will learn how to generate OpenAPI specifications and Swagger UI from REST services using ServicedocGen maven plugin + +==== + +[step] +-- +restoreDevonfwIde(["java", "mvn"]) +-- + +First, clone the `quarkus-quickstarts` repository from GitHub. It contains several sample applications for many extensions to Quarkus. For this tutorial, we will use an application with a simple REST service contained in the `rest-json-quickstart` subfolder. +[step] +== Clone quarkus-quickstarts repository +-- +cloneRepository("", "https://github.com/quarkusio/quarkus-quickstarts.git") +-- + +==== +Next step is to add the ServicedocGen plugin to the project's pom.xml +[step] +== Add the ServicedocGen maven plugin +-- +changeFile("quarkus-quickstarts/rest-json-quickstart/pom.xml", { "file": "files/pom.xml" }) +-- +Take a look at the `configuration` section of the plugin. In this section you can configure the behavior of the plugin. Not all options are necessary, such as the `info` section. This one is only used to add additional information to the OpenAPI file. + +Some other parts are necessary. The `classnameRegex` parameter is used to configure which name pattern the REST service classes must match. + +The `templates` section is used to configure what is created by the plugin. In this case, the OpenAPI specification is created in yaml format and the Swagger UI file is also created. +==== + +In this step we will buid the application. This will cause the ServicedocGen plugin to create the configured files. +[step] +== Build the application +-- +executeCommand("mvn clean package","mvn clean package", { "dir": "quarkus-quickstarts/rest-json-quickstart" }) +-- + +The files are created in the `target/site/servicedoc` folder. To serve them automatically when running the application, move the files to the `src/main/resources/META-INF/resources/` folder. Static files located in this folder are automatically served by Quarkus. +[step] +== Move generated file to META-INF/resources +-- +executeCommand("copy target\\site\\servicedoc\\*.* src\\main\\resources\\META-INF\\resources","mv target/site/servicedoc/* src/main/resources/META-INF/resources/", { "dir": "quarkus-quickstarts/rest-json-quickstart" }) +-- + +Now build the application again so that the static files are also included in the resulting jar file. +[step] +== Build the application again +-- +executeCommand("mvn clean package","mvn clean package", { "dir": "quarkus-quickstarts/rest-json-quickstart" }) +-- + +==== +Now run the application. +[step] +== Run the application +-- +executeCommand("java -jar quarkus-run.jar","java -jar quarkus-run.jar", { "dir": "quarkus-quickstarts/rest-json-quickstart/target/quarkus-app", "asynchronous": true }, {"port":8080 , "startupTime": 120, "path": "fruits", "interval": 2}) +-- + +After executing `java -jar quarkus-run.jar` you can access the REST service by opening the following URL: https://[[HOST_SUBDOMAIN]]-8080-[[KATACODA_HOST]].environments.katacoda.com/fruits + +You can access the OpenAPI specification of this REST API at https://[[HOST_SUBDOMAIN]]-8080-[[KATACODA_HOST]].environments.katacoda.com/OpenApi.yaml + +The Swagger UI is accessible at https://[[HOST_SUBDOMAIN]]-8080-[[KATACODA_HOST]].environments.katacoda.com/SwaggerUI.html +==== diff --git a/openapi-generation-smallrye/files/application.properties b/openapi-generation-smallrye/files/application.properties new file mode 100644 index 000000000..891c9bcf3 --- /dev/null +++ b/openapi-generation-smallrye/files/application.properties @@ -0,0 +1 @@ +quarkus.swagger-ui.always-include=true \ No newline at end of file diff --git a/openapi-generation-smallrye/files/pom.xml b/openapi-generation-smallrye/files/pom.xml new file mode 100644 index 000000000..dd6d8bc56 --- /dev/null +++ b/openapi-generation-smallrye/files/pom.xml @@ -0,0 +1,114 @@ + + + 4.0.0 + org.acme + rest-json-quickstart + 1.0.0-SNAPSHOT + + quarkus-bom + io.quarkus + 2.5.1.Final + 3.0.0-M5 + UTF-8 + 11 + 11 + + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + + io.quarkus + quarkus-resteasy-jackson + + + io.quarkus + quarkus-smallrye-openapi + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + + + + build + + + + + + + + + native + + + native + + + + native + + + + + org.apache.maven.plugins + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + + \ No newline at end of file diff --git a/openapi-generation-smallrye/index.asciidoc b/openapi-generation-smallrye/index.asciidoc new file mode 100644 index 000000000..5fc05db74 --- /dev/null +++ b/openapi-generation-smallrye/index.asciidoc @@ -0,0 +1,61 @@ += OpenAPI and Swagger UI generation with Quarkus Smallrye extension + +[tags] +-- +technology=OpenAPI;Maven;Quarkus;Swagger +difficulty=intermediate +topic=plugin;documentation +asset=devon4j +-- +==== +This tutorial will show you how to include the Quarkus Smallrye OpenAPI extension in Quarkus projects to automatically generate OpenAPI specifications and Swagger UI from your REST APIs. +For more information about OpenAPI and the Smallrye OpenAPI extension, see the [devon4j documentation](https://github.com/devonfw/devon4j/blob/master/documentation/guide-openapi.asciidoc) or the [official Quarkus guide](https://quarkus.io/guides/openapi-swaggerui). + +### Prerequisites +* Installed devonfw-ide (or at least Java and Maven installed) + +### Learning goals +* You will learn how to generate OpenAPI specifications and Swagger UI from REST services + +==== + +[step] +-- +restoreDevonfwIde(["java", "mvn"]) +-- + +First, clone the `quarkus-quickstarts` repository from GitHub. It contains several sample applications for many extensions to Quarkus. We will use a simple REST service for this tutorial and customize the application accordingly. +[step] +== Clone quarkus-quickstarts repository +-- +cloneRepository("", "https://github.com/quarkusio/quarkus-quickstarts.git") +-- + +The next step is to add the Smallrye OpenAPI extension to the project. Open the `pom.xml` file of project in the folder `rest-json-quickstart`. Add the extension `quarkus-smallrye-openapi` to the list of dependencies. +[step] +== Add the extension +-- +changeFile("quarkus-quickstarts/rest-json-quickstart/pom.xml", { "file": "files/pom.xml" }) +-- + +By default, the Swagger UI is enabled only in development mode. To enable it in all cases, set the property `quarkus.swagger-ui.always-include=true` in the application.properties file of the Quarkus project. +[step] +-- +createFile("quarkus-quickstarts/rest-json-quickstart/src/main/resources/application.properties", "files/application.properties") +-- + +==== +This was all to include the extension in the project. Now build and run the application. +[step] +== Build and run the application +-- +executeCommand("mvn clean package","mvn clean package", { "dir": "quarkus-quickstarts/rest-json-quickstart" }) +executeCommand("java -jar quarkus-run.jar","java -jar quarkus-run.jar", { "dir": "quarkus-quickstarts/rest-json-quickstart/target/quarkus-app", "asynchronous": true }, {"port":8080 , "startupTime": 120, "path": "fruits", "interval": 2}) +-- + +After executing `java -jar quarkus-run.jar`, the application should be running. It provides a simple REST service that can be accessed by opening the following URL: https://[[HOST_SUBDOMAIN]]-8080-[[KATACODA_HOST]].environments.katacoda.com/fruits + +You can access the OpenAPI specification of this REST API at https://[[HOST_SUBDOMAIN]]-8080-[[KATACODA_HOST]].environments.katacoda.com/q/openapi + +The Swagger UI is accessible at https://[[HOST_SUBDOMAIN]]-8080-[[KATACODA_HOST]].environments.katacoda.com/q/swagger-ui +==== diff --git a/package-lock.json b/package-lock.json index d56a532c2..4485cd5d4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,17 +4,99 @@ "lockfileVersion": 1, "requires": true, "dependencies": { - "@types/jasmine": { - "version": "3.6.9", - "resolved": "https://registry.npmjs.org/@types/jasmine/-/jasmine-3.6.9.tgz", - "integrity": "sha512-B53NIwMj/AO0O+xfSWLYmKB0Mo6TYxfv2Mk8/c1T2w/e38t55iaPR6p7pHXTTtqfTmevPK3i8T1YweYFTZlxDw==", - "dev": true + "@actions/core": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.4.0.tgz", + "integrity": "sha512-CGx2ilGq5i7zSLgiiGUtBCxhRRxibJYU6Fim0Q1Wg2aQL2LTnF27zbqZOrxfvFQ55eSBW0L8uVStgtKMpa0Qlg==" + }, + "@octokit/auth-token": { + "version": "2.4.5", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.5.tgz", + "integrity": "sha512-BpGYsPgJt05M7/L/5FoE1PiAbdxXFZkX/3kDYcsvd1v6UhlnE5e96dTDr0ezX/EFwciQxf3cNV0loipsURU+WA==", + "requires": { + "@octokit/types": "^6.0.3" + } + }, + "@octokit/core": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.4.0.tgz", + "integrity": "sha512-6/vlKPP8NF17cgYXqucdshWqmMZGXkuvtcrWCgU5NOI0Pl2GjlmZyWgBMrU8zJ3v2MJlM6++CiB45VKYmhiWWg==", + "requires": { + "@octokit/auth-token": "^2.4.4", + "@octokit/graphql": "^4.5.8", + "@octokit/request": "^5.4.12", + "@octokit/request-error": "^2.0.5", + "@octokit/types": "^6.0.3", + "before-after-hook": "^2.2.0", + "universal-user-agent": "^6.0.0" + } + }, + "@octokit/endpoint": { + "version": "6.0.11", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.11.tgz", + "integrity": "sha512-fUIPpx+pZyoLW4GCs3yMnlj2LfoXTWDUVPTC4V3MUEKZm48W+XYpeWSZCv+vYF1ZABUm2CqnDVf1sFtIYrj7KQ==", + "requires": { + "@octokit/types": "^6.0.3", + "is-plain-object": "^5.0.0", + "universal-user-agent": "^6.0.0" + } + }, + "@octokit/graphql": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.6.2.tgz", + "integrity": "sha512-WmsIR1OzOr/3IqfG9JIczI8gMJUMzzyx5j0XXQ4YihHtKlQc+u35VpVoOXhlKAlaBntvry1WpAzPl/a+s3n89Q==", + "requires": { + "@octokit/request": "^5.3.0", + "@octokit/types": "^6.0.3", + "universal-user-agent": "^6.0.0" + } + }, + "@octokit/openapi-types": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-7.3.0.tgz", + "integrity": "sha512-o00X2FCLiEeXZkm1Ab5nvPUdVOlrpediwWZkpizUJ/xtZQsJ4FiQ2RB/dJEmb0Nk+NIz7zyDePcSCu/Y/0M3Ew==" + }, + "@octokit/request": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.5.0.tgz", + "integrity": "sha512-jxbMLQdQ3heFMZUaTLSCqcKs2oAHEYh7SnLLXyxbZmlULExZ/RXai7QUWWFKowcGGPlCZuKTZg0gSKHWrfYEoQ==", + "requires": { + "@octokit/endpoint": "^6.0.1", + "@octokit/request-error": "^2.0.0", + "@octokit/types": "^6.16.1", + "is-plain-object": "^5.0.0", + "node-fetch": "^2.6.1", + "universal-user-agent": "^6.0.0" + } + }, + "@octokit/request-error": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.5.tgz", + "integrity": "sha512-T/2wcCFyM7SkXzNoyVNWjyVlUwBvW3igM3Btr/eKYiPmucXTtkxt2RBsf6gn3LTzaLSLTQtNmvg+dGsOxQrjZg==", + "requires": { + "@octokit/types": "^6.0.3", + "deprecation": "^2.0.0", + "once": "^1.4.0" + } + }, + "@octokit/types": { + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.16.2.tgz", + "integrity": "sha512-wWPSynU4oLy3i4KGyk+J1BLwRKyoeW2TwRHgwbDz17WtVFzSK2GOErGliruIx8c+MaYtHSYTx36DSmLNoNbtgA==", + "requires": { + "@octokit/openapi-types": "^7.2.3" + } }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" }, + "before-after-hook": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.2.tgz", + "integrity": "sha512-3pZEU3NT5BFUo/AD5ERPWOgQOCZITni6iavr5AUw5AUwQjMlI0kzu5btnyD39AF0gUEsDPwJT+oY1ORBJijPjQ==" + }, "brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -29,6 +111,11 @@ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" }, + "deprecation": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", + "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==" + }, "fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -61,21 +148,10 @@ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, - "jasmine": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/jasmine/-/jasmine-3.7.0.tgz", - "integrity": "sha512-wlzGQ+cIFzMEsI+wDqmOwvnjTvolLFwlcpYLCqSPPH0prOQaW3P+IzMhHYn934l1imNvw07oCyX+vGUv3wmtSQ==", - "dev": true, - "requires": { - "glob": "^7.1.6", - "jasmine-core": "~3.7.0" - } - }, - "jasmine-core": { - "version": "3.7.1", - "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-3.7.1.tgz", - "integrity": "sha512-DH3oYDS/AUvvr22+xUBW62m1Xoy7tUlY1tsxKEJvl5JeJ7q8zd1K5bUwiOxdH+erj6l2vAMM3hV25Xs9/WrmuQ==", - "dev": true + "is-plain-object": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz", + "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==" }, "minimatch": { "version": "3.0.4", @@ -85,6 +161,11 @@ "brace-expansion": "^1.1.7" } }, + "node-fetch": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", + "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==" + }, "once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -111,6 +192,11 @@ "glob": "^7.1.3" } }, + "universal-user-agent": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", + "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" + }, "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", diff --git a/package.json b/package.json index da38b35ee..59a5db7f8 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,9 @@ "description": "", "dependencies": { "pegjs": "^0.10.0", - "rimraf": "^3.0.2" + "rimraf": "^3.0.2", + "@octokit/core": "^3.2.3", + "@actions/core": "^1.2.2" }, "author": "", "license": "ISC" diff --git a/selectChangedFiles.js b/selectChangedFiles.js new file mode 100644 index 000000000..86cc6fb0f --- /dev/null +++ b/selectChangedFiles.js @@ -0,0 +1,30 @@ +const core = require("@actions/core"); +const { Octokit } = require("@octokit/core"); +const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN }); + +async function selectChangedFiles() { + let pr = process.env.PR_NUMBER; + let arr = []; + try { + let get = await octokit.request('GET /repos/{owner}/{repo}/pulls/{pull_number}/files', { + owner: 'devonfw-tutorials', + repo: 'tutorials', + pull_number: pr + }); + let files = get.data; + files.forEach(file => { + arr.push(file.filename) + }); + } catch(e) { + throw e; + } + let output = arr.join(' '); + core.info(`Changed Files: ${output}`); + core.setOutput('changedFiles', output); +} + +selectChangedFiles().catch(err => { + console.log(err); + process.exit(1); +}); +