Commit c3537238 authored by Siva Rama Krishna's avatar Siva Rama Krishna

initial commit

parents
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
\ No newline at end of file
variables:
RELEASE_NAME: "project4954"
SERVICE_PORT: 8080
REGISTRY_URL: 751503455312.dkr.ecr.us-west-2.amazonaws.com/pgnonprod
SONAR_URL: "http://pg-sonar-altimetrik-com-82028342.us-west-2.elb.amazonaws.com"
SONAR_LOGIN: "cc3fc35cad01a325d1b3904bcf3aa38b153fa7f1"
BRANCH_NAME: "master"
stages:
- Build
- Test
- ReleaseCleanup
- ReleaseDeploy
- Validation
Build:
stage: Build
script:
- mvn clean install -Dk8s.db.env=db-config-k8s
- $(aws ecr get-login --no-include-email --region us-west-2)
- docker build -t 751503455312.dkr.ecr.us-west-2.amazonaws.com/pgnonprod:$CI_PIPELINE_ID .
- docker push 751503455312.dkr.ecr.us-west-2.amazonaws.com/pgnonprod:$CI_PIPELINE_ID
sonar:
stage: Test
script:
- mvn --batch-mode verify sonar:sonar -Dsonar.branch=$BRANCH_NAME -Dsonar.exclusions="pom.xml" -Dsonar.host.url=$SONAR_URL -Dsonar.login=$SONAR_LOGIN
ReleaseCleanup:
stage: ReleaseCleanup
script:
- echo `pwd`
- cd ./helm && /sbin/helm delete --purge $RELEASE_NAME && exit 0
allow_failure: true
ReleaseDeploy:
stage: ReleaseDeploy
script:
- echo `pwd`
- sed -i s/#BUILD_ID#/$CI_PIPELINE_ID/g ./helm/service/values.yaml
- sed -i s/#SERVICE_PORT#/$SERVICE_PORT/g ./helm/service/values.yaml
- kubectl config use-context arn:aws:eks:us-west-2:751503455312:cluster/pg-eks
- cd ./helm && /sbin/helm install service --name $RELEASE_NAME
Validation:
stage: Validation
script:
- sleep 45
- if [ `curl -s -o /dev/null -I -w "%{http_code}" https://pgtest.altimetrik.com/$RELEASE_NAME` = "200" ]; then exit 0; else exit 1; fi
allow_failure: false
\ No newline at end of file
FROM openjdk:8-jre-alpine
ADD /src/main/resources/application.properties //
ADD /src/main/resources/application.yml //
ADD /src/main/resources/db-config.properties //
ADD /src/main/resources/db-config-k8s.properties //
ADD /target/demo-0.0.1-SNAPSHOT.jar //
ENTRYPOINT ["java", "-jar", "/demo-0.0.1-SNAPSHOT.jar"]
# java8_springboot-2.0.5-api-template-3.0
Spring Boot with MySQL
For instructions, Please refer to the link `https://pg-gitlab-test.altimetrik.com/PlaygroundEngineeringEnv/java8_springboot-2.0.5-api-template-3.0/blob/master/EclipseCheUserGuide.pdf`
To connect to database console of the app available over `app access url`, Please refer to `/src/main/resources/db-config-k8s.properties` having the `url` and `JDBC connection properties`
\ No newline at end of file
# Patterns to ignore when building packages.
# This supports shell glob matching, relative path matching, and
# negation (prefixed with !). Only one pattern per line.
.DS_Store
# Common VCS dirs
.git/
.gitignore
.bzr/
.bzrignore
.hg/
.hgignore
.svn/
# Common backup files
*.swp
*.bak
*.tmp
*~
# Various IDEs
.project
.idea/
*.tmproj
.vscode/
apiVersion: v1
appVersion: "1.0"
description: A Helm chart for Kubernetes
name: project4954
version: 0.1.0
\ No newline at end of file
1. Get the application URL by running these commands:
{{- if .Values.ingress.enabled }}
{{- range $host := .Values.ingress.hosts }}
{{- range $.Values.ingress.paths }}
http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host }}{{ . }}
{{- end }}
{{- end }}
{{- else if contains "NodePort" .Values.service.type }}
export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "project4954.fullname" . }})
export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}")
echo http://$NODE_IP:$NODE_PORT
{{- else if contains "LoadBalancer" .Values.service.type }}
NOTE: It may take a few minutes for the LoadBalancer IP to be available.
You can watch the status of by running 'kubectl get svc -w {{ include "project4954.fullname" . }}'
export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "project4954.fullname" . }} -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
echo http://$SERVICE_IP:{{ .Values.service.port }}
{{- else if contains "ClusterIP" .Values.service.type }}
export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "project4954.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}")
echo "Visit http://127.0.0.1:8080 to use your application"
kubectl port-forward $POD_NAME 8080:80
{{- end }}
\ No newline at end of file
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "project4954.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "project4954.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "project4954.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}
\ No newline at end of file
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "project4954.fullname" . }}
labels:
app.kubernetes.io/name: {{ include "project4954.name" . }}
helm.sh/chart: {{ include "project4954.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
app.kubernetes.io/name: {{ include "project4954.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
template:
metadata:
labels:
app.kubernetes.io/name: {{ include "project4954.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
spec:
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
volumeMounts:
- name: efs-pvc
mountPath: ./src/main/resources
env:
- name: "k8s.db.env"
value: "db-config-k8s"
ports:
- name: http
containerPort: {{ .Values.service.internalport }}
protocol: TCP
resources:
{{- toYaml .Values.resources | nindent 12 }}
{{- with .Values.nodeSelector }}
volumes:
- name: efs-pvc
persistentVolumeClaim:
claimName: efs
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
\ No newline at end of file
{{- if .Values.ingress.enabled -}}
{{- $fullName := include "project4954.fullname" . -}}
{{- $ingressPaths := .Values.ingress.paths -}}
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: {{ $fullName }}
labels:
app.kubernetes.io/name: {{ include "project4954.name" . }}
helm.sh/chart: {{ include "project4954.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- with .Values.ingress.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- if .Values.ingress.tls }}
tls:
{{- range .Values.ingress.tls }}
- hosts:
{{- range .hosts }}
- {{ . | quote }}
{{- end }}
secretName: {{ .secretName }}
{{- end }}
{{- end }}
rules:
{{- range .Values.ingress.hosts }}
- host: {{ . | quote }}
http:
paths:
{{- range $ingressPaths }}
- path: {{ . }}
backend:
serviceName: {{ $fullName }}
servicePort: http
{{- end }}
{{- end }}
{{- end }}
\ No newline at end of file
apiVersion: v1
kind: Service
metadata:
name: {{ include "project4954.fullname" . }}
labels:
app.kubernetes.io/name: {{ include "project4954.name" . }}
helm.sh/chart: {{ include "project4954.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
type: {{ .Values.service.type }}
ports:
- port: {{ .Values.service.port }}
targetPort: http
protocol: TCP
name: http
selector:
app.kubernetes.io/name: {{ include "project4954.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
\ No newline at end of file
apiVersion: v1
kind: Pod
metadata:
name: "{{ include "project4954.fullname" . }}-test-connection"
labels:
app.kubernetes.io/name: {{ include "project4954.name" . }}
helm.sh/chart: {{ include "project4954.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
annotations:
"helm.sh/hook": test-success
spec:
containers:
- name: wget
image: busybox
command: ['wget']
args: ['{{ include "project4954.fullname" . }}:{{ .Values.service.port }}']
restartPolicy: Never
\ No newline at end of file
# Default values for project4954.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
replicaCount: 1
image:
repository: 751503455312.dkr.ecr.us-west-2.amazonaws.com/pgnonprod
tag: #BUILD_ID#
pullPolicy: IfNotPresent
nameOverride: ""
fullnameOverride: ""
service:
type: NodePort
port: 80
internalport: #SERVICE_PORT#
ingress:
enabled: true
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/rewrite-target: /
#kubernetes.io/tls-acme: "true"
paths:
path: /project4954
hosts:
# - afe6ec7ed3f3711e9b98006759708723-313212737.us-west-2.elb.amazonaws.com
- pgtest.altimetrik.com
tls:
- secretName: custom-tls-cert
hosts:
- pgtest.altimetrik.com
resources: {}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 128Mi
nodeSelector: {dbvol: h2dbstore}
tolerations: []
affinity: {}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.altimetrik.ee</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot with MySQL</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<swagger.annotations.version>1.5.20</swagger.annotations.version>
<swagger.version>2.8.0</swagger.version>
<!-- The main class to start by executing "java -jar" -->
<start-class>com.altimetrik.ee.demo.Application</start-class>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Swagger based Dependencies -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger.annotations.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Tomcat Embed -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- To compile JSP files -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<body>
<div>
<div>
<form id="ftformId" action="/project4954/status" method="post">
<h1>Fund Transfer</h1>
<h2>From Account:<input name="fromAcc" id="fromAccId"/></h2>
<h2> To Account:<input name="toAcc" id="toAccId"/></h2>
<h2> Amount ($):<input name="amount" id="amountId"/></h2>
<button type="submit" form="ftformId">Transfer</button>
</form>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<body>
<div>
<div>
<h1>Welcome to CITI Sample Fund Transfer Project</h1>
<h2>Click here for <strong><a href="fundtransfer">${message}</a></strong></h2>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<body>
<div>
<div>
<h1>Status</h1>
<font color="green"><h2>${message}</h2></font>
</div>
</div>
</body>
</html>
\ No newline at end of file
package com.altimetrik.ee.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import com.altimetrik.ee.demo.service.ComponentDetailsService;
@EnableAsync
@EnableScheduling
@SpringBootApplication(scanBasePackages = { "com.altimetrik" })
/*@PropertySources({ @PropertySource(value = "classpath:db-config.properties", ignoreResourceNotFound = true),
@PropertySource(value = "classpath:${k8s.db.env}.properties", ignoreResourceNotFound = true) })*/
public class Application {
private static ConfigurableApplicationContext context;
/*
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
*/
public static void main(String[] args) {
context = SpringApplication.run(Application.class, args);
context.getBean(ComponentDetailsService.class)
.createComponentDetails(context.getEnvironment().getProperty("spring.application.name"));
}
}
package com.altimetrik.ee.demo.bean;
public class ComponentDetailsBean {
private String componentName;
private String componentIdentifier;
public ComponentDetailsBean() {
super();
}
public ComponentDetailsBean(String componentName, String componentIdentifier) {
super();
this.componentName = componentName;
this.componentIdentifier = componentIdentifier;
}
public String getComponentName() {
return componentName;
}
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public String getComponentIdentifier() {
return componentIdentifier;
}
public void setComponentIdentifier(String componentIdentifier) {
this.componentIdentifier = componentIdentifier;
}
@Override
public String toString() {
return "ComponentDetailsBean [componentName=" + componentName + ", componentIdentifier=" + componentIdentifier
+ "]";
}
}
package com.altimetrik.ee.demo.bean;
import java.util.List;
public class PairedComponentDetailsBean extends ComponentDetailsBean {
private List<ComponentDetailsBean> pairedComponentDetails;
public PairedComponentDetailsBean() {
super();
}
public PairedComponentDetailsBean(final String componentName, final String componentIdentifier) {
super(componentName, componentIdentifier);
}
public PairedComponentDetailsBean(final String componentName, final String componentIdentifier,
final List<ComponentDetailsBean> pairedComponentDetails) {
super(componentName, componentIdentifier);
this.pairedComponentDetails = pairedComponentDetails;
}
public PairedComponentDetailsBean(final ComponentDetailsBean componentDetails,
final List<ComponentDetailsBean> pairedComponentDetails) {
super(componentDetails.getComponentName(), componentDetails.getComponentIdentifier());
this.pairedComponentDetails = pairedComponentDetails;
}
public List<ComponentDetailsBean> getPairedComponentDetails() {
return pairedComponentDetails;
}
public void setPairedComponentDetails(List<ComponentDetailsBean> pairedComponentDetails) {
this.pairedComponentDetails = pairedComponentDetails;
}
}
package com.altimetrik.ee.demo.config;
import static springfox.documentation.builders.PathSelectors.regex;
import java.util.Collections;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.altimetrik.ee.demo.controller")).paths(regex("/.*"))
.build().enable(true).apiInfo(metaData());
}
private ApiInfo metaData() {
return new ApiInfo("Demo Application", "Demo API Services", "2.0", "https://www.altimetrik.com/privacy-policy/",
new Contact("Playground", "https://playground.altimetrik.com", "pg-mgr1@altimetrik.com"),
"Apache License Version 2.0", "https://www.apache.org/licenses/LICENSE-2.0", Collections.emptyList());
}
}
package com.altimetrik.ee.demo.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Value;
@RestController
@RequestMapping(value = "/")
@CrossOrigin
public class Default {
@Value("${k8s.db.env}")
private String deploymentEnv;
@GetMapping(value = "/", produces = { "text/html" }, consumes = MediaType.ALL_VALUE)
public ResponseEntity<String> getUserDetailByGitlabEmailId() {
String data = "Welcome to Playground Engineering Environment";
if (deploymentEnv != null && !deploymentEnv.isEmpty()) {
data = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "<title>Playground Engineering Environment</title>\n"
+ "<style>\n" + "body {\n" + " background-color: white;\n" + " text-align: center;\n"
+ " color: black;\n" + "}\n" + "table {\n" + " align: center;\n"
+ " border-collapse: collapse;\n" + " width: 65%;\n" + "}\n" + "td, th {\n"
+ " border: 1px solid #dddddd;\n" + " padding: 8px;\n" + "}\n" + "tr:nth-child(even) {\n"
+ " background-color: #dddddd;\n" + "}\n" + "</style>\n" + "</head>\n" + "<body>\n"
+ "<img src='https://playground.altimetrik.com/assets/img/playground-logo2.svg' alt='Avatar' style='width:200px'>\n"
+ "<h2>Welcome to Playground Engineering Environment</h2>\n" + "<h3>Database access details</h3>\n"
+ "<table align=center>\n" + " <tr>\n" + " <th>DB Admin Console</th>\n" + " <th>JDBC URL</th>\n"
+ " <th>User Name</th>\n" + " <th>Password</th>\n" + " </tr>\n" + " <tr>\n"
+ " <td><a target='_blank' href='https://pgtest.altimetrik.com/project4954/project4954/'>https://pgtest.altimetrik.com/project4954/project4954/</a></td>\n"
+ " <td>jdbc:h2:file:./src/main/resources/project4954</td>\n" + " <td>playground</td>\n"
+ " <td>password</td>\n" + " </tr>\n" + "</table>\n" + "</body>\n" + "</html>\n";
}
return new ResponseEntity<>(data, HttpStatus.OK);
}
}
\ No newline at end of file
package com.altimetrik.ee.demo.controller;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import com.altimetrik.ee.demo.service.FundTransferService;
@Controller
public class FundTransferController {
@Autowired
@Qualifier("FundTransferServiceImpl")
private FundTransferService fundTransferService;
@GetMapping(path="/index")
public String home(Map<String, Object> model) {
model.put("message", fundTransferService.home());
return "index";
}
@GetMapping(path="/fundtransfer")
public String fundtransfer(Map<String, Object> model) {
return "fundtransfer";
}
@PostMapping(path="/status")
public String status(HttpServletRequest request, Map<String, Object> model) {
String toAccount = request.getParameter("toAcc");
model.put("message", fundTransferService.status(toAccount));
return "status";
}
}
\ No newline at end of file
package com.altimetrik.ee.demo.controller;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
registry.viewResolver(resolver);
}
}
package com.altimetrik.ee.demo.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.altimetrik.ee.demo.bean.PairedComponentDetailsBean;
import com.altimetrik.ee.demo.service.ComponentDetailsService;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping(value = "/service")
public class ServiceController {
protected static Logger logger = LoggerFactory.getLogger(ServiceController.class.getName());
@Value("${spring.application.name}")
private String applicationName;
@Autowired
private ComponentDetailsService componentDetailsService;
@GetMapping(value = "/")
@ApiOperation(value = "Get service name and identifier", notes = "Get service details and its corresponding values for all paired services", response = PairedComponentDetailsBean.class)
public PairedComponentDetailsBean findAll() {
return componentDetailsService.findAll(this.applicationName);
}
}
package com.altimetrik.ee.demo.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
@Entity
@Table(name = "component_details")
public class ComponentDetailsEntity {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "component_name")
private String componentName;
@Column(name = "component_identifier")
private String componentIdentifier;
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_date", nullable = false, updatable = false)
private Date createdDate;
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_date")
private Date updatedDate;
public ComponentDetailsEntity() {
super();
}
public ComponentDetailsEntity(String componentName, String componentIdentifier) {
super();
this.componentName = componentName;
this.componentIdentifier = componentIdentifier;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getComponentName() {
return componentName;
}
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public String getComponentIdentifier() {
return componentIdentifier;
}
public void setComponentIdentifier(String componentIdentifier) {
this.componentIdentifier = componentIdentifier;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((componentIdentifier == null) ? 0 : componentIdentifier.hashCode());
result = prime * result + ((componentName == null) ? 0 : componentName.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ComponentDetailsEntity other = (ComponentDetailsEntity) obj;
if (componentIdentifier == null) {
if (other.componentIdentifier != null)
return false;
} else if (!componentIdentifier.equals(other.componentIdentifier))
return false;
if (componentName == null) {
if (other.componentName != null)
return false;
} else if (!componentName.equals(other.componentName))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "ComponentDetailsEntity [id=" + id + ", componentName=" + componentName + ", componentIdentifier="
+ componentIdentifier + "]";
}
}
package com.altimetrik.ee.demo.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.altimetrik.ee.demo.bean.ComponentDetailsBean;
import com.altimetrik.ee.demo.entity.ComponentDetailsEntity;
@Repository
public interface ComponentDetailsRepository extends JpaRepository<ComponentDetailsEntity, Long> {
<S extends ComponentDetailsEntity> S save(final S componentDetails);
<S extends ComponentDetailsEntity> List<S> save(final Iterable<S> componentDetails);
ComponentDetailsEntity findByComponentName(final String componentName);
ComponentDetailsEntity findByComponentIdentifier(final String componentIdentifier);
@Query("SELECT new com.altimetrik.ee.demo.bean.ComponentDetailsBean(c.componentName,c.componentIdentifier) FROM ComponentDetailsEntity c WHERE c.componentName = (:componentName)")
ComponentDetailsBean getByComponentName(@Param("componentName") final String componentName);
@Query("SELECT new com.altimetrik.ee.demo.bean.ComponentDetailsBean(c.componentName,c.componentIdentifier) FROM ComponentDetailsEntity c WHERE c.componentName != (:componentName)")
List<ComponentDetailsBean> getByComponentNameNotIn(@Param("componentName") final String componentName);
}
package com.altimetrik.ee.demo.service;
import org.springframework.stereotype.Service;
import com.altimetrik.ee.demo.bean.PairedComponentDetailsBean;
@Service
public interface ComponentDetailsService {
boolean createComponentDetails(final String applicationName);
PairedComponentDetailsBean findAll(final String applicationName);
}
package com.altimetrik.ee.demo.service;
public interface FundTransferService {
String home();
String status(String toAccount);
}
package com.altimetrik.ee.demo.service.impl;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.altimetrik.ee.demo.bean.PairedComponentDetailsBean;
import com.altimetrik.ee.demo.entity.ComponentDetailsEntity;
import com.altimetrik.ee.demo.repository.ComponentDetailsRepository;
import com.altimetrik.ee.demo.service.ComponentDetailsService;
@Service
public class ComponentDetailsServiceImpl implements ComponentDetailsService {
protected static Logger logger = LoggerFactory.getLogger(ComponentDetailsServiceImpl.class.getName());
@Value("${spring.application.name}")
private String applicationName;
@Autowired
private ComponentDetailsRepository componentDetailsRepository;
@Override
public PairedComponentDetailsBean findAll(final String applicationName) {
final PairedComponentDetailsBean pairedComponentDetails = new PairedComponentDetailsBean(
this.componentDetailsRepository.getByComponentName(applicationName),
this.componentDetailsRepository.getByComponentNameNotIn(applicationName));
return pairedComponentDetails;
}
@Override
public boolean createComponentDetails(final String applicationName) {
if (this.componentDetailsRepository.findByComponentName(applicationName) == null) {
this.componentDetailsRepository
.save(new ComponentDetailsEntity(applicationName, UUID.randomUUID().toString()));
}
return true;
}
@Scheduled(cron = "${cron.component.identifier.reg-ex}")
public void regenerateComponentIdentifier() {
final ComponentDetailsEntity componentDetails = this.componentDetailsRepository
.findByComponentName(this.applicationName);
componentDetails.setComponentIdentifier(UUID.randomUUID().toString());
this.componentDetailsRepository.save(componentDetails);
}
}
package com.altimetrik.ee.demo.service.impl;
import org.springframework.stereotype.Service;
import com.altimetrik.ee.demo.service.FundTransferService;
@Service("FundTransferServiceImpl")
public class FundTransferServiceImpl implements FundTransferService {
@Override
public String home() {
return "Fund Transfer !!";
}
@Override
public String status(String toAccount) {
return "Fund transfered successfully to Account# " + toAccount;
}
}
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<body>
<div>
<div>
<form id="ftformId" action="/project4954/status" method="post">
<h1>Fund Transfer</h1>
<h2>From Account:<input name="fromAcc" id="fromAccId"/></h2>
<h2> To Account:<input name="toAcc" id="toAccId"/></h2>
<h2> Amount ($):<input name="amount" id="amountId"/></h2>
<button type="submit" form="ftformId">Transfer</button>
</form>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<body>
<div>
<div>
<h1>Welcome to CITI Sample Fund Transfer Project</h1>
<h2>Click here for <strong><a href="fundtransfer">${message}</a></strong></h2>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<body>
<div>
<div>
<h1>Status</h1>
<font color="green"><h2>${message}</h2></font>
</div>
</div>
</body>
</html>
\ No newline at end of file
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
# Enabling H2 Console
spring.h2.console.enabled=true
# Custom H2 Console URL
spring.h2.console.path=/project4954
# Enable Web Access
spring.h2.console.settings.web-allow-others=true
# Disable h2 details in default controller
k8s.db.env=
\ No newline at end of file
# Spring properties
spring:
application:
name: demo # Service registers under this name
cron:
component:
identifier:
reg-ex: 0 0/60 * * * ?
# HTTP Server
server:
port: 8080 # HTTP (Tomcat) port
undertow:
accesslog:
enabled: true
# Logging configurations
logging:
level:
root: INFO
com.memorynotfound: DEBUG
org.springframework.web: INFO
org.springframework.security: INFO
org.hibernate.SQL: WARN
# Please use the the url 'https://{pgtest/pgsandbox/citi-pg-project}.altimetrik.com/project4954/project4954/'
# to connect to the database wih the properties mentioned below.
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=playground
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
# temporary data storage
spring.datasource.url = jdbc:h2:file:./src/main/resources/project4954
\ No newline at end of file
# Spring Boot automatically creates a JPA EntityManagerFactory using Hibernate
# but we need to override some defaults:
spring.jpa.hibernate.ddl-auto: update
spring.jpa.hibernate.show_sql= true
spring.jpa.hibernate.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.hibernate.naming.physical-strategy= org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.open-in-view = true
# Spring performance optimization
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.properties.javax.persistence.query.timeout= 60000
spring.jpa.properties.hibernate.query.plan_cache_max_soft_references= 1024
spring.jpa.properties.hibernate.query.plan_cache_max_strong_references= 64
spring.jpa.properties.hibernate.query.plan_cache_max_size= 1024
spring.jpa.properties.hibernate.query.plan_parameter_metadata_max_size= 32
spring.jpa.show-sql: true
# Connection properties
spring.datasource.url= jdbc:mysql://db:3306/playground?autoReconnect=true&useSSL=false
spring.datasource.username= playground
spring.datasource.password= password
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle= true
spring.datasource.validationQuery= SELECT 1
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
\ No newline at end of file
package com.altimetrik.ee.demo.tests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
public class ApplicationTests {
@Test
public void appTest() {
assertTrue(true);
}
}
package com.altimetrik.ee.demo.tests;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import com.altimetrik.ee.demo.service.impl.FundTransferServiceImpl;
@RunWith(JUnit4.class)
public class TestFundTransferService {
private FundTransferServiceImpl fundTransferServiceImpl;
@Before
public void setup() {
fundTransferServiceImpl = new FundTransferServiceImpl();
}
@Test
public void testHome() {
assertEquals("Fund Transfer !!", fundTransferServiceImpl.home());
}
@Test
public void testSubService() {
String toAccount = "123";
assertEquals("Fund transfered successfully to Account# "+ toAccount, fundTransferServiceImpl.status("123"));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment