# Quick Start Guide for Service Development

## Introduction to App Framework

The App Framework is a modern application development framework built on Spring Boot, designed to simplify the process of creating, deploying, and managing applications. It supports both Spring Boot 2 (JDK 11) and Spring Boot 3 (JDK 17), offering a comprehensive set of tools and best practices to help developers quickly build efficient and scalable applications.

- [App Development Overview](https://docs.insuremo.com/common/doc_00000003)


<div class="docs-note"><span class="docs-admonitions-text">note</span>

The App Framework provided in this documentation is exclusively designed for use within the specific application referenced herein. It is not intended for the development of new tenant applications. Any attempt to extend or modify the framework for use in other projects or environments is not recommended.Please ensure that the framework is only utilized for its intended purpose within the specified application.

</div>

### Technology Stack

- **Java**: A robust, object-oriented programming language that is extensively utilized in the development of enterprise applications.
- **Spring Boot**: A streamlined framework that accelerates the development of standalone, production-ready Spring applications with minimal configuration required.
- **Maven**: Utilizes Maven for efficient dependency management.
- **RDS**: Employs a relational database for data persistence, supporting databases such as MySQL, MSSQL, and Oracle.
- **JPA**: Utilizes JPA and Hibernate as the Object-Relational Mapping (ORM) framework.
- **Liquibase**: A database version control tool that simplifies the management of database changes and ensures consistency in both database structure and data.

### Service Registration, Discovery, and Governance

- **Configuration Management**:  
  Service properties are configured via the **insureMO Config Center** per environment.
  - When a service starts, it calls the insureMO Config Center API to retrieve the configuration properties.

- **Service Registration and Routing**:  
  Service registration and routing are managed by the hosting container (Kubernetes), following the simplified approach based on insureMO's architecture.  
  - Each service in Kubernetes has a unique `service-name`, and each service can have multiple instances (PODs).
  - The `service-name` acts as an identifier for other services to access. For example, if two services are deployed in Kubernetes, one service can call the APIs of the `bcp-bff` service using `http://bcp-bff/the-api`.
  - To support service versioning and local development, the App Framework includes a built-in request URL rewrite feature for both Feign clients and RestTemplate.

- **API Exposure**:  
  APIs of the services are exposed through the **insureMO API Gateway**.

### Logical Structure of the App Framework

- **App Foundation**: The core component that provides essential services, configuration management, authentication, and security features to ensure the stability and security of applications.
  - [Config Center](https://docs.insuremo.com/common/doc_00000295) External config properties loader - based on insureMO Config Center
  - [I18n](https://docs.insuremo.com/common/doc_00000024) - Translations for labels and dropdown list
  - [Cache](https://docs.insuremo.com/common/doc_00000013) Spring Cache & Ehcache
  - [Use Relational DB](https://docs.insuremo.com/common/doc_00000061)
  - [Message Code](https://docs.insuremo.com/common/doc_00000042)

- **SDK/Runtime/Client**: A set of tools and APIs that streamline the interactions with App Foundation, enabling developers to quickly integrate necessary functionalities.
  - [Platform SDKs Depends on Vela App Foundation](https://docs.insuremo.com/common/doc_00000047)
  - [Welcome to InsureMo SDK for Java](https://docs.insuremo.com/common/doc_00000089)

![App Framework](./image/app_dev_overview/app_service_overview.png)

### Key Concepts for Building Applications

- **insureMO Gateway URL**: The domain address of the insureMO API Gateway required for the application to access insureMO APIs.

- **Access Token**: A key authentication element required for the application to function. The token must be valid to access the platform services.

    ![generic_norms_calling_api](./image/app_dev_overview/generic_norms_calling_api.png)

  - All calls must go through API gateway.
    - Exception: Service can be called from the same namespace through k8s naming.
  - By default, API gateway performs authentication to ensure a valid token is in place.
    - Short period token will be received when user logs in to app.
    - Long period token can be created in API management tool using a functional ID, and used only for service-to-service integration.

- **Middleware Network Connections (RDS, MQ)**: Supports connections to Relational Database Services (RDS) and Message Queues (MQ) to enhance system scalability and enabling asynchronous processing.

### Key Features for Development

- **Asynchronous Processing**
  - **Batch Processing**: Efficiently handle large volumes of data, suitable for scheduled tasks and data migration.
    - [Batch Scheduler](https://docs.insuremo.com/common/doc_00000010)
  - **Message Queuing**: Leverage message queues for asynchronous communication, decoupling service dependencies and improving system resilience.
  - **Async task executor**: The App Framework includes a built-in TaskExecutor `@Async("tasKExecutor")` with context propagation for tracing and application user/tenant.

- **Global Transactions**: Ensure consistency across multiple services, reducing the risk of data inconsistency.
  - [Global Transaction](https://docs.insuremo.com/common/doc_00000023)

- **Internationalization (i18n)**: Built-in support for multiple languages, facilitating global application development to meet diverse user needs.
  - [I18n](https://docs.insuremo.com/common/doc_00000024)
  - [Language Setting](https://docs.insuremo.com/common/doc_00000049)

- **Cache**: Built-in spring cache support for improving performance and reducing unnecessary API calls.

## Quick Run a Service Locally Based on the App Framework

### Preparing the Service

- **Creating a New Service**: In the learning session, you can quickly create one using the App Template, which includes a basic project structure and configuration.
- **Accessing an Existing Service**: If you're working on an existing service, obtain the Git repository URL and the necessary access permissions to clone the service code.

### Prerequisites for Development

- **Source Code Access**: Ensure that you have access to the source code.
  - When creating a new app using the App Template, you can directly download the source code.
  - For existing services, request the access URL and necessary permissions from your manager.
  - Install `GIT` locally to manage source code versioning.

- **JDK**: Ensure that JDK (Java 11.03+ or Java 17) is installed, depending on the Spring Boot version you are using.

<div class="docs-note"><span class="docs-admonitions-text">note</span>

  insureMO APIs require TLS 1.3. In JDK 11, TLS 1.3 was first enabled in JDK 11.0.3. Therefore, for JDK 11, version 11.0.3 or later is required.
  
</div>

- **IDE**: Recommended IDEs include IntelliJ IDEA or Eclipse, which provide excellent support for Spring Boot development.

- **Maven Configuration**: Set up Maven repository to pull required dependencies, including Spring Boot and related libraries.
  
  To access from the `public internet`, please use the settings below. For `internal staff`, please retain your current settings.

  ```XML
  <repositories>
      <repository>
          <releases>
              <enabled>true</enabled>
          </releases>
          <snapshots>
              <enabled>false</enabled>
          </snapshots>
          <id>insuremo-public</id>
          <name>insureMO Maven Repository</name>
          <url>https://public.insuremo.com/artifactory/maven/</url>
      </repository>
  </repositories>

  <pluginRepositories>
      <pluginRepository>
          <releases>
              <enabled>true</enabled>
          </releases>
          <snapshots>
              <enabled>false</enabled>
          </snapshots>
          <id>insuremo-public</id>
          <name>insureMO Maven Repository</name>
          <url>https://public.insuremo.com/artifactory/maven/</url>
      </pluginRepository>
  </pluginRepositories>
  ```

-  **insureMO Gateway URL, Access Token and Tenant Code**: Local development requires this information to load configuration properties from insureMO.
  
    In the learning session, follow the steps below:
   - Log in to [insureMO Portal](https://portal.insuremo.com/) and access **My Console**.
   - Enter your application details by clicking the app card.
   - Locate your runtime environment tag.
   - In the tenant section, the personal access tokens are listed. You can view and use any of them.
   - If you want to create a new token, click ***Create Key***.
   - Save the token,  you will use it later.
     - `insuremo_access_token=Bearer ******`
   - Save the gateway url for access to insureMO Config Center.
     - `insuremo_gw_url=https://***-gw.insuremo.com`
   - Save the tenant code, you will use it later.
     - `TENANT_CODE=trial5`

<div class="docs-note"><span class="docs-admonitions-text">note</span>

  **DO NOT** delete tokens created by others.
  
</div>

### Downloading the Code Locally

- **Learning Session**: Use Console to download the zip file of source code.
  - [Download Code](./stepbystep/download_code.md)

- **Existing Service**: Use Git to clone the code into your local development environment.
  - Before starting or committing any changes, remember to run `git pull` to ensure you get the latest version.

### Importing the Code into Your IDE

Import the service's source code into your IDE, ensuring that the IDE recognizes the Maven project structure correctly.

### Running Maven Install to Pull Dependencies

Execute `mvn install` in the project root directory to fetch the project dependencies.

### Configuring Local Startup Properties

- Set up the **Gateway URL** and **Access Token** to ensure the service can be accessed correctly.
  Configure below environment variables before you run App.java.

    ```javascript
    insuremo_access_token=Bearer xxxxx;insuremo_gw_url=https://***-gw.insuremo.com;spring.profiles.active=local;TENANT_CODE=xxxxx     
    
    # set spring.profiles.active=local to enable local profile application-local.properties to local development purpose
    # insuremo_access_token value is we just created it with above steps.
    ```

- Adjust other configuration parameters as needed, such as port numbers and environment variables.
  - [Add properties for local development](https://docs.insuremo.com/common/doc_00000007#service-app-development-locally)

- Configure the datasource used by the service.
  - Ideally, each microservice should have its own dedicated database schema. The database connection information is maintained in the insureMO Config Center and automatically loaded when the service launches, based on the `spring.application.name` property in `bootstrap.properties` or `application.properties`.

    - In the learning session, if you've downloaded the code for local development without forking the project, the default `application name` is `appframework-bff-app`, and the JDBC information is configured in Config Center.
    - For local development and testing, if you need to modify the database without affecting others, you have these options:
      - **Use an insureMO Database Schema:** Apply a database schema within insureMO. 
      - **Create a Local Database Schema:** Create a local database schema using the `utf8mb4_bin` charset.

      After setup, override the JDBC connection details in your `application-local.properties`. Here’s an example:

      ```java
      jdbc.url=jdbc:log4jdbc:mysql://localhost:3306/local_db?useSSL=false&useUnicode=true&characterEncoding=utf8&failOverReadOnly=false&useTimezone=true&serverTimezone=UTC
      jdbc.user=local_db
      jdbc.password=local_dbpassword
      ```

    - Similarly, to change the RabbitMQ connection to your local server for local development and testing, override the settings in `application-local.properties`.  Here’s a sample configuration (replace `trial5` with your tenant code):

    ```java
    # replace the trial5 prefix with your tenant code
    trial5.spring.rabbitmq.addresses=localhost:5672
    trial5.spring.rabbitmq.ssl.enabled=false
    trial5.spring.rabbitmq.virtualHost=trial5
    trial5.spring.rabbitmq.username=trial5
    trial5.spring.rabbitmq.password=xxxx
    ```

### Initializing Database (Optional)

If necessary, execute Liquibase scripts to initialize the database structure and data, ensuring consistency with the production environment.

- [How to Use Liquibase](https://docs.insuremo.com/common/doc_00000061#how-to-use-liquibase)
- [How to Use Relational Database in App](https://docs.insuremo.com/common/doc_00000061)

### Successful Startup and API Debugging

Start the service and use tools like Postman or curl to debug API endpoints, verifying that the service functions as expected.

- Running Steps:
  - Run `./mvn install` to download all dependencies.
  - Run  `App.java.`


## Building, Deploying, and Monitoring

### Continuous Integration and Continuous Deployment (CI/CD)

- **Setting up CI/CD**:
  - If you have created the service using the App Template, ensure that you fork the code in the App Workspace. This will automatically generate a CI/CD pipeline.
  - You can also use your existing CI/CD if there is one.
- **Configure the CI/CD Pipeline**:   

   Configure your CI/CD pipeline to automate the processes of building, testing, and deploying. This automation will significantly improve development efficiency.

-  **Build and Deploy Apps**

<div class="docs-note"><span class="docs-admonitions-text">note</span>

  In the learning session, if you are working within a shared tenant, `fork` is not allowed.
  
</div>

### API Registration and Endpoints

#### API Registration

Register APIs in the API Gateway to ensure that services can be called by other microservices and clients seamlessly. See [API Management and Gateway](https://docs.insuremo.com/common/doc_00000356).

There are two approaches to expose APIs:

- **Wildcard Exposure by Service Name**: Expose APIs using the service name (static route). For details, see [Static Route Configuration and Automated Publishing](https://docs.insuremo.com/common/doc_00000321).
- **Explicit Registration**: Manually register the API in the API management system.

  - [Register API](https://docs.insuremo.com/common/doc_00000356#register-api)
  - When you started a service app, you can request *{root}/swagger.json* to see all API definitions of this app.
  - Enter ***insureMO Portal***, find ***My Console*** > ***All Services***, select your target Environment, find your App in ***Deployed Pods***, and click ***Publish APIs*** to publish your APIs.
  
<div class="docs-note"><span class="docs-admonitions-text">note</span>

Above operation is only authorized to tenant admin.

</div>

#### API Endpoints

**Static Route**

API endpoints based on the service name are generally used for UI application call, and app domain URL (`https://<app-env-domain>/api/segment/service-name/api-xxx`):

- `https://tenant-ptdev.insuremo.com/api/tenant/uw-bff/uwPolicy/v1/LoadAgentInfo`
- `https://tenant-ptdev.insuremo.com/api/platform/dd/public/codetable/v1/data/list/byName`
- `https://tenant-ptdev.insuremo.com/api/jpcore/jp-common-service/common/auth/checkAuthCode`

Alternatively, you can access through gateway URL (`https://gw-env-domain/sement/service-name/api-xxx`):

- `https://ptdev-gw.insuremo.com/tenant/uw-bff/uwPolicy/v1/LoadAgentInfo`
- `https://ptdev-gw.insuremo.com/platform/dd/public/codetable/v1/data/list/byName`
- `https://ptdev-gw.insuremo.com/jpcore/jp-common-service/common/auth/checkAuthCode`

Static route configuration is required. For details, see [Static Route Configuration and Automated Publishing](https://docs.insuremo.com/non_insurance_service/docs/md/static_route_en_without_pat).

**API Registry**

API register within API management, based on swagger/openapi, gateway URL (`https://<gw-env-domain>/vendor/version/api-xxx`):

- `https://ptdev-gw.insuremo.com/platform/1.0/config/v1/tenant/common`
- `https://sandbox-2-sg-gw.insuremo.com/trialzone6/1.0/appframework-bff-app/test/testbff`

### API Auth and Permission

#### Principles

- All calls must go through API gateway, with the exception: service can be called from the same namespace through k8s naming.
- By default, API gateway performs authentication to ensure a valid token is in place.
  - Short period token will be received when user logs in to app.
  - Long period token (personal access token) is used for service app calls and 3rd party integration. It can be created in API management tool using a functional ID.

#### Users
  
Three types of users can be used for the API auth:

- **Member**: Individual end user. For instance, an individual end user of an insurance carrier can register an account using a phone number or other identifier, which allows them to manage their policies and claims.
- **App User**: Staff or employees operating the application. See [App URP](https://docs.insuremo.com/iam/urp#5-api-authority).
- **Platform User**: Machines or services calling insureMO APIs. See [Account Management](https://docs.insuremo.com/common/doc_00000371#account-management-functionality).

<div class="docs-note"><span class="docs-admonitions-text">note</span>

  There is an OpenAPI extension available in swagger.json to specify the user source. The extension is denoted by `x-mo-user-source-id`, which can be applied at the top level of swagger.json or at the operation level. Its values are:

- mo: Platform user (default value)
- platform: App URP user
- member: Member user
  
</div>

#### Permission Control

- [App URP](https://docs.insuremo.com/common/doc_00000384#5-api-authority)
- [MO API Permission](https://docs.insuremo.com/common/doc_00000356#permission-requested-by-api-consumer)

<div class="docs-note"><span class="docs-admonitions-text">note</span>

  There is an OpenAPI extension available in swagger.json to specify the user source. The extension is denoted by `x-mo-gateway-authorization-url`, which can be applied at the top level of swagger.json or at the operation level. Its values are:

- mo: insureMO platform api permission (default value)
- app_urp: App URP permission
  
</div>

### Monitoring

- [API (Dashboard)](https://docs.insuremo.com/common/doc_00000377) 
- [Alert (Dashboard)](https://docs.insuremo.com/common/doc_00000378)

## Security

### Security Features Provided by App Foundation

- **ID Signing, Masking, and Encryption**: Ensure the security of data during transmission and storage, preventing data breaches.  
  - [Data Signature](https://docs.insuremo.com/common/doc_00000058#sensitive-system-id-data-signature-for-api)
  - [Data Mask](https://docs.insuremo.com/common/doc_00000058#sensitive-business-data-mask-for-api)
- **Data Storage**: Support for encrypting sensitive data, protecting user privacy and ensuring compliance with regulations.
  - [Data Encryption](https://docs.insuremo.com/common/doc_00000058#sensitive-business-data-storage-encryption)
- **Log Masking**: Support for encrypting sensitive data when outputting logs.
  - [Log Encryption](https://docs.insuremo.com/common/doc_00000058#sensitive-api-requestresponse-body-in-log-encryption)

If users want to see full API plain bodies, they can copy bodies from the log monitor and paste them into the log encryption. See [Log Decryption](https://docs.insuremo.com/common/doc_00000043#log-encryption-and-decryption).

## Calling APIs

It is recommended to use the SDK to call insureMO APIs. However, in some cases, developers may prefer to use `RestTemplate` for API calls, such as for inter-service communication within the application. The App Framework provides built-in `RestTemplate` beans with features like URL Rewrite, Context Propagation, Request Authentication, and Timeout. Developers can directly use these beans to make API calls.

```java

// For service call, e.g. http://bcp-bff/xxx
@Qualifier("restTemplateWithLoadBalance")

// For gateway API call, e.g. http://gateway.ebao/eBao/1.0/email/xxx
@Qualifier("origRestTemplateForContainerCall")
```

## Optimization

### Performance Optimization Strategies

- **Data Caching**: Utilize Redis or local caching mechanisms to enhance data access speeds and reduce database load.
  - [Cache](https://docs.insuremo.com/common/doc_00000013)
- **Thread Management**: Dynamically adjust the number of executing threads based on load conditions to optimize resource utilization.
  - Customize the configcenter parameter *server.tomcat.max-threads* to fit your condition.
- **JVM Heap Size Configuration**: Properly configure the JVM heap size to prevent memory overflow and performance bottlenecks.
  - [Memory Size](https://docs.insuremo.com/common/doc_00000046#is-assigned-memory-not-big-enough)
- **JDBC Connection Pool Sizing**: Adjust the database connection pool size based on concurrency requirements to ensure stable and available database connections.
  - Customize the configcenter parameter *jdbc.maxPoolSize* to fit your condition.
- **RabbitMQ Consumers**: Adjust the maximum concurrent consumers for app messages.
  - Customize the config property *app.queue.maxConcurrentConsumers* to fit your condition.

## Troubleshooting

### Troubleshooting Steps

- **Logs**: Examine application logs for error messages to identify and resolve problems.
- **Tracing**: Utilize distributed tracing tools to analyze request flows and pinpoint performance bottlenecks.
- **Boot Admin**: Utilize Boot Admin to monitor application health and performance metrics, enabling quick identification and resolution of problems.

Please log in <https://tenant-env.insuremo.com/ui/admin/> with your username and password. You have two options to switch the boot-admin page:

- Replace the /ui/admin/ with /boot-admin/, i.e., the target URL would be <https://tenant-env.insuremo.com/boot-admin/>.
- Click **Boot Admin** – Tenant menu on the left side under the Public Setting.
  - [Spring Boot Admin](https://docs.insuremo.com/common/doc_00000370)

## Extension and Integration

### Using iHub for API Integration

A cloud-native service that speeds up the integration and connectivity among different systems in the insurance industry with unlimited scalability.

For details, see [iHub](https://docs.insuremo.com/common/doc_00000376).

### Discovering more APIs in insureMO

See [insureMO API Reference](https://docs.insuremo.com/tech/pro/sdk/api).

### Using SDK for Extensions

Utilize the SDK to extend functionality and integrate with third-party services, simplifying interactions with external systems and enhancing application capabilities.

See [Welcome to insureMO SDK for Java](https://docs.insuremo.com/common/doc_00000089).

The App Framework has built-in support for insureMO SDK, setting below maven dependencies:

```
<project>
  <properties>
    <insuremo.SDK.version>1.1.X</insuremo.SDK.version>
  </properties>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.insuremo.SDK</groupId>
        <artifactId>bom</artifactId>
        <version>${insuremo.SDK.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  <dependencies>
    <!-- support for insuremo SDK -->
    <dependency>
      <groupId>com.ebao.vela</groupId>
      <artifactId>vela-insuremo-SDK-starter</artifactId>
    </dependency> 
 
    <!-- SDK -->
    <dependency>
      <groupId>com.insuremo.SDK</groupId>
      <artifactId>email</artifactId>
    </dependency>
  </dependencies>
</project>
```

<div class="docs-note"><span class="docs-admonitions-text">note</span>

This document may include links to external websites and third-party features solely for demonstration purposes. These links and features do not constitute an endorsement or recommendation on our part. We do not control and are not responsible for the content, services, or privacy practices of these third parties. Users are advised to review the respective terms and privacy policies independently.

</div>
