Angular and Git project setup

Angular-CLI, VSCode and Git/GitHub configuration

I will create Angular 4 client application with project setup needed to seamlessly develop and store source code to remote Github repository.

Projects folder structure

I will create client side SPA application as client to Java spring boot server application, created in previous blog article.

Both projects (server & client) are in separate folders, only at the deployment stage they will be combined under java server application. In the simplest micro-service deployment scenario, both applications are served from the same server instance. Embedded Tomcat server  will serve all files needed for angular client side application and to drive java REST services as application back-end.

myapp
!--server
!  !--SpringBootMyApp
!     
!--client
   !--AngularMyApp

Generate angular client project

After you have installed all prerequisites for angular you create a new empty application from command line. Command will create application subfolder and all required app files for simple angular app.

/myapp/client/$ ng new AngularMyApp

You can experiment with some command line switches to add additional generator options like generate routes file for example (–routing).

Dry-Run

If you do not want to actually execute commands then add –dry-run option (“-d”  for short) and inspect generated set of commands.

$ ng new app_name --routing 
$ ng new app_name --dry-run 
$ ng new app_name -r -d

Open project in Visual Studio Code

You can open project from command line (“code .”) or open folder from inside editor.

Integrate with Git  source control

After angular-cli create a project it will immediately initialize GIT folder and commit initial version of an application.

You can check log of git commits right after generating new app :

/AngularMyApp/$ git log

and result will be something like this :

Author: Angular CLI <angular-cli@angular.io>
Date:   Mon Jun 26 22:41:07 2017 +0200

chore: initial commit from @angular/cli

We see initial commit was done by @angular/cli tool.

Configure remote Git repository

If you wish to publish code to the Git-Hub server, you need to prepare local windows git to be able to push code to remote server without any username/password interaction.

git config --global credential.helper wincred
git config --global user.name "user_name"
git config --global user.email "email@example.com"

This type of user identification is used with HTTPS repository address for git communication.

You need to have github repository created (empty project!). When you create new repository, try to not create readme file, because you will not be able to push initial code up without “force” option. This option is not possible inside visual studio code. “Force push” is possible with command line or with github desktop client.

With remote repository created configure “git remote”  localy with correct “https” repository address :
/AngularMyApp/ $> git remote add AngularMyApp https://github.com/bisaga/AngularMyApp.git
Push code to Github

After adding remote repository to local git configuration you select “Push to…” inside visual studio code Git extension menu (…), select remote repository and push.

SSH key passphrase

You need to setup your ssh-agent correctly to work with remote git repository without constant interruptions with an question for ssh passphrase.

If you use bash terminal inside vscode and you work on windows, add the ssh-agent to the setup script in your home (~) folder (usually c:\Users\your_name\.bash_profile file.

env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env

You can check with the command

git fetch

If you get the question then you probably need to create proper ssh-agent setup.

 

 

Links

Initial code for AngularMyApp is on this github repostory.

 

Java Spring Boot project setup

You can get source code of this project from github repository “SpringBootMyApp” .

Create Spring Boot Maven project

Go to Spring Boot project generator web site and select minimal project definition with dependencies :

  • Web:  dependency for embedded tomcat server
  • jOOQ: integrated SQL query language and data model code generator
  • Flyway: database model migration tool
  • Postgresql JDBC driver

After downloading ZIP project file, unzip it to some folder and open folder in IntelliJ IDE environment.

Startup class

The project will automatically include embedded tomcat server and spring application start will configure whole application at startup.

package com.bisaga.myapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = { "com.bisaga" })
public class MyappApplication {

	public static void main(String[] args) {
		SpringApplication.run(MyappApplication.class, args);
	}
}

Setup project properties

Under src/main/resources find file application.properties and add configuration for database access  and flyway configuration. Your application will start migration procedure at every application start and syncronize to the correct version automatically.

#Debug
debug=false

# Database connection
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/myappdb
spring.datasource.username=..........
spring.datasource.password=..........

# Jooq dialect
spring.jooq.sql-dialect=POSTGRES

# Flyway
flyway.locations=classpath:db/migration

Flyway migration files

You need a folder where your SQL migration files will reside:

src/main/resources/db/migration

Add first migration file, for example “create currency table” will be saved in file V1_0_0__currency.sql:

/*
 * Currency
 */
CREATE TABLE currency (
	code 						VARCHAR(60) not null,
	abbreviation 				varchar(60),
	description 				text,
	row_id 						serial primary key,					-- row identifier
	created_at 					timestamptz not null default now(),
	created_by 					varchar(60) not null,
	modified_at 				timestamptz,
	modified_by 				varchar(60)
);
CREATE INDEX currency_created_at ON currency (created_at) ;
CREATE INDEX currency_modified_at ON currency (modified_at) ;

-- DEMO DATA
INSERT INTO public.currency (code, abbreviation, description, created_by)
VALUES('EUR', 'Eur', 'Euro', 'admin');

INSERT INTO public.currency (code, abbreviation, description, created_by)
VALUES('USD', 'Usd', 'US Dollar', 'admin');

Be extra careful with names , first part (V1_0_0) is version of migration file, second part of the name is a description, separated with two underline characters.

The scripts must be correct SQL! Validate it first in database environment. If script is not valid, migration procedure will break and you will probably have hard time to figure out what was wrong.

Now you run your application and your database must be prepared according to migration script changes automatically. Flyway start automatically with your application.

More information on this video tutorial for flyway and spring boot..

Maven plugin settings

If you want more control around code generation and migration life cycle, you add flyway and jooq plugins:

Add this properties to the properties section in pom.xml file:

        <!-- Database -->
        <db.url>jdbc:postgresql://localhost:5432/myappdb</db.url>
        <db.username>........</db.username>
        <db.password>........</db.password>
        <!-- FlyWayDB -->
        <org.flywaydb.schema>public</org.flywaydb.schema>
        <org.flywaydb.location>classpath:db/migration</org.flywaydb.location>
        <org.flywaydb.version>4.2.0</org.flywaydb.version>
        <!-- jOOQ -->
        <org.jooq.codegen.namespace>com.bisaga.myapp.database.model</org.jooq.codegen.namespace>
        <org.jooq.input_schema>public</org.jooq.input_schema>
        <org.jooq.target_dir>src/main/java/</org.jooq.target_dir>
        <org.jooq.version>3.9.2</org.jooq.version>
  • Database connection settings in pom.xml will be used by jooq code generator and flyway migration maven plugins.

Flyway and Jooq dependency and version

You probably already have it from generated pom.xml, add it if you don’t have it.

        <dependency>
            <version>${org.flywaydb.version}</version>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jooq</groupId>
            <version>${org.jooq.version}</version>
            <artifactId>jooq</artifactId>
        </dependency>

Version was not required by spring boot but I put version in because I encounter differences between plugin version and spring boot version of the libraries.

Now you need to define plugin definitions as :

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.flywaydb</groupId>
                <version>${org.flywaydb.version}</version>
                <artifactId>flyway-maven-plugin</artifactId>
                <!-- Note that we're executing the Flyway plugin in the "generate-sources" phase -->
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>migrate</goal>
                        </goals>
                    </execution>
                </executions>
                <!-- Note that we need to prefix the db/migration path with filesystem:
                    to prevent Flyway from looking for our migration scripts only on the classpath -->
                <configuration>
                    <url>${db.url}</url>
                    <user>${db.username}</user>
                    <password>${db.password}</password>
                    <locations>
                        <location>${org.flywaydb.location}</location>
                    </locations>
                    <schemas>${org.flywaydb.schema}</schemas>
                </configuration>
            </plugin>

            <plugin>
                <!-- Use org.jooq for the Open Source Edition org.jooq.pro for commercial
                    editions, org.jooq.pro-java-6 for commercial editions with Java 6 support,
                    org.jooq.trial for the free trial edition Note: Only the Open Source Edition
                    is hosted on Maven Central. Import the others manually from your distribution -->
                <groupId>org.jooq</groupId>
                <version>${org.jooq.version}</version>
                <artifactId>jooq-codegen-maven</artifactId>
                <!-- The jOOQ code generation plugin is also executed in the generate-sources phase,
                     prior to compilation -->
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>

                <!-- This is a minimal working configuration. See the manual's section about the code generator
                     for more details -->
                <configuration>
                    <jdbc>
                        <url>${db.url}</url>
                        <user>${db.username}</user>
                        <password>${db.password}</password>
                    </jdbc>
                    <generator>
                        <database>
                            <includes>.*</includes>
                            <inputSchema>${org.jooq.input_schema}</inputSchema>
                        </database>
                        <target>
                            <packageName>${org.jooq.codegen.namespace}</packageName>
                            <directory>${org.jooq.target_dir}</directory>
                        </target>
                    </generator>
                </configuration>
            </plugin>
        </plugins>
    </build>

Flyway and Jooq maven commands

After you add plugin definitions to maven pom.xml file you get new lifecycle commands :

When flyway commands are used directly they search for SQL files in the target “classes” folder and not in the source tree (“src”). When project compiled the files, target folder is synchronized with the current version of code in the source tree.

After compiling project you could run “flyway:migrate” command for example. You can always check files in the target folder and delete it if you are not sure you have the latest version of the files.

Jooq code generation

Jooq generate data model code from your database. The code is added to the project in the namespace as you defined in plugin definition.  It’s wise to split plugin definition to properties and plugin definition part.

<!-- jOOQ -->
<org.jooq.input_schema>public</org.jooq.input_schema>
<org.jooq.codegen.namespace>com.bisaga.myapp.database.model</org.jooq.codegen.namespace>
<org.jooq.target_dir>src/main/java/</org.jooq.target_dir>

Every time you compile project, database model code is regenerated. Check here for more information about jooq.

You can check how database model code is regenerated simply by deleting a line from one of generated files and recompile the project again.

More about jooq & spring boot can be found here.

Create JSON service

Now I need to test the environment if everything is set in place as should be. I will create simple currency service as sample application and test basic CRUD operations.

Create simple data container class

To be able to send JSON payload back and forth from client to server we create a simple transport class:

package com.bisaga.myapp;

/**
 * Created by igorb on 17. 06. 2017.
 */
public class CurrencyDto {
    private String code;
    private String abbreviation;
    private String description;
    private Integer rowId;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public void setAbbreviation(String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getRowId() {
        return rowId;
    }

    public void setRowId(Integer rowId) {
        this.rowId = rowId;
    }
}

Service class and database interaction with Jooq

Now we create service class with which we will interact with database :

/*
*  MIT License
*  Copyright (c) 2017 Igor Babic
*/
package com.bisaga.myapp;

import static com.bisaga.myapp.database.model.tables.Currency.CURRENCY;

import com.bisaga.myapp.database.model.tables.records.CurrencyRecord;
import org.jooq.DSLContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional
class CurrencyService {
    private static final Logger LOG = LoggerFactory.getLogger(CurrencyService.class);

    @Autowired
    private DSLContext db;

    /**
     * List all currencies in the currency table
     * @return Return list of currency records
     */
    List<CurrencyDto> getAll() {
        List<CurrencyDto> currList;
        currList = db.select().from(CURRENCY)
                .fetch().into(CurrencyDto.class);

        return currList;
    }

    /**
     * Search for a currency record by currency code
     * @param code  currency code as parameter
     * @return Return currency record
     */
    CurrencyDto getByCode(String code) {
        List<CurrencyDto> currList;
        currList = db.select().from(CURRENCY)
                .where(CURRENCY.CODE.eq(code))
                .fetch().into(CurrencyDto.class);
        
        return currList.get(0);
    }

    /**
     * Delete currency record by row identifier
     * @param rowId rowId row identifier
     * @return Return number of deleted records
     */
    Integer delete(Integer rowId) {
        return db.delete(CURRENCY).where(CURRENCY.ROW_ID.eq(rowId)).execute();
    }

    /**
     * Save currency execute insert or update command if currency already exist.
     * @param currency instance of CurrencyDto class as parameter
     */
    CurrencyDto saveCurrency(CurrencyDto currency) {
        if (currency.getRowId() == null) {
            return this.insert(currency);
        } else {
            return this.update(currency);
        }
    }

    /**
     * Insert new currency record to database
     * @param currency Currency record as parameter
     * @return Return currency record filled with database defaults after insert
     */
    private CurrencyDto  insert(CurrencyDto currency)  {
        CurrencyRecord record = db.newRecord(CURRENCY, currency);
        record.setCreatedBy("admin");
        record.insert();                // insert to database
        record.into(currency);			// return changes made by database
        return currency;
    }

    /**
     * Update currency record in database
     * @param currency currency record as parameter
     * @return Return currency record filled with changes from database update
     */
    private CurrencyDto update(CurrencyDto currency) {
        CurrencyRecord record = db.newRecord(CURRENCY, currency);
        record.update();                // update to database
        record.into(currency);			// return changes made by database
        return currency;
    }

}

REST controller with router mapping

On the end we need a controller class to expose access points for REST service:

/*
*  MIT License
*  Copyright (c) 2017 Igor Babic
*/
package com.bisaga.myapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.net.Authenticator;
import java.util.List;

@RestController
@RequestMapping(value = "/api/currency", produces = "application/json")
public class CurrencyController {

    @Autowired private CurrencyService service;

    @RequestMapping(method=RequestMethod.GET)
    @ResponseStatus(HttpStatus.FOUND)
    public List<CurrencyDto> findAll() {
        return service.getAll();
    }

    @RequestMapping(value="/{code}", method=RequestMethod.GET)
    @ResponseStatus(HttpStatus.FOUND)
    public CurrencyDto findByCode(@PathVariable("code") String code) {
        return service.getByCode(code);
    }

    @RequestMapping(method=RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public CurrencyDto saveCurrency(@RequestBody CurrencyDto currency) {
        return service.saveCurrency(currency);
    }

    @RequestMapping(method=RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.OK)
    public Integer deleteCurrency(@RequestParam(value = "rowid", required = true) Integer rowId ) {
        return service.delete(rowId);
    }


}

Don’t forget to instantiate services with DI (dependency injection) with @Autowire annotation. This simplify development a lot !

Interactive testing

The service should in this point work as expected, just run application and navigate to “localhost:8080/api/currency”.

You can search for a specific currency with added path variable appended to Url address:

Postman application for Http API testing

To inspect service in more details on the client side, you can use Postman application.

Look at example ofadding a currency with a POST message:

In the headar I add “content-type” variable with value “application/json” and in the payload a json message with a new currency json structure. On the right side I received “200-OK” and a currency record with a record and new row identifier registered in the database.

 

PowerShell startup script

PowerShell on windows 10

To allow script files execution on your machine, you need to change security policy and allow that.  To execute command and change policy you need to run powershell console as administrator.

Set-ExecutionPolicy RemoteSigned

How to create startup script

Create profile.ps1 file and put it into one of default folders (C:\Windows\System32\WindowsPowerShell\v1.0).

Beep on backspace

To disable annoying beep when press on backspace if there is no character left, add next command to the startup script:

Set-PSReadlineOption -BellStyle None

 

 

Visual Studio Code – customization

How to customize your visual studio code

Custom settings are saved in “settings.json” file, you can open it with Ctrol+Shift+P,  search for Preference: Open user settings .

Custom terminal shell – BASH

If you wish to change shell from default windows powershell to cygwin bash terminal for example, use next setting:

"terminal.integrated.shell.windows": "C:\\cygwin64\\bin\\bash.exe"

Of course you will need to set proper folder where your cygwin is installed on your machine.

Change size of fonts and window appearance

    "editor.fontSize": 14,
    "window.zoomLevel": 2,
GIT integration enable/disable

If you do not won’t GIT integration (doesn’t work good with cygwin git version on windows for example) use :

"git.enabled": false,

But, you will need to type git commands manually if you do that.

Angular v4 Typescript Snippets

The Visual Studio Code plugin for code snippets from JohnPapa.

Ctrl+P => ext install Angular2

Angular Language Service

The Visual Studio Code plugin for Html editor intellisense from Angular team.

Ctrl+P => ext install ng-template

 GIT History

Plugin for GIT file compare and history/log checking.

Install :

Ctrl+P => ext install githistory

Use:

Ctrl+Shift+P => search for "Git History"