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

initial commit

parents
# Created by .ignore support plugin (hsz.mobi)
FROM openjdk:8-jre-alpine3.7
ADD /target/#ARTIFACT# //
ADD /src/main/resources/application.properties //
ADD /src/main/resources/logback.xml //
ADD /src/main/resources/db-config.properties //
ADD /src/main/resources/service.properties //
ENTRYPOINT ["java", "-jar", "/#ARTIFACT#"]
pipeline {
agent any
environment {
BRANCHES="${env.GIT_BRANCH}"
COMMIT="${env.GIT_COMMIT}"
}
stages {
stage('Set variables') {
steps {
script {
BRANCH = "${BRANCHES}".tokenize('/')[-1]
def data = readJSON file:'metadata.json'
DOCKERHOST="""${data.hosting."${BRANCH}".dockerHost}"""
DOCKERPORT="""${data.hosting."${BRANCH}".dockerPort}"""
HOSTPORT="""${data.hosting."${BRANCH}".hostPort}"""
DOCKERREPO="docker.artifactory"
VALIDATIONURL="""${data.'application.properties'."${BRANCH}".validationURL}"""
VALIDATIONSLEEP="""${data.'application.properties'."${BRANCH}".validationSleep}"""
DBNODEPRIMARY="""${data.'db-config.properties'."${BRANCH}".DBNODEPRIMARY}"""
DBNODESECONDARY1="""${data.'db-config.properties'."${BRANCH}".DBNODESECONDARY1}"""
DBNODESECONDARY2="""${data.'db-config.properties'."${BRANCH}".DBNODESECONDARY2}"""
DBREPLICASET="""${data.'db-config.properties'."${BRANCH}".DBREPLICASET}"""
DBSCHEMA="""${data."db-config.properties"."${BRANCH}".DBSCHEMA}"""
DBUSR="""${data."db-config.properties"."${BRANCH}".DBUSR}"""
DBPW="""${data."db-config.properties"."${BRANCH}".DBPW}"""
PLAYGROUNDSERVICEURL="""${data."application.properties"."${BRANCH}".PLAYGROUNDSERVICEURL}"""
USESWAGGER="""${data."application.properties"."${BRANCH}".USESWAGGER}"""
def (NS, ENV2, JOB)="${JOB_NAME}".tokenize('/')
def (NET1, B1, B2)="${NS}".tokenize('.')
JOBENV="${ENV2}"
NET="${NET1}"
ORG="${NET}-${JOBENV}"
OLDBUILD=(BUILD_ID as int) - 1
def pom=readMavenPom file: 'pom.xml'
ARTIFACTID="${pom.artifactId}"
ARTIFACTVERSION="${pom.version}"
ARTIFACTPACKAGING="${pom.packaging}"
ARTIFACT="${ARTIFACTID}-${ARTIFACTVERSION}.${ARTIFACTPACKAGING}"
sh "sed -i s/#DBNODEPRIMARY#/${DBNODEPRIMARY}/g ./src/main/resources/db-config.properties"
sh "sed -i s/#DBNODESECONDARY1#/${DBNODESECONDARY1}/g ./src/main/resources/db-config.properties"
sh "sed -i s/#DBNODESECONDARY2#/${DBNODESECONDARY2}/g ./src/main/resources/db-config.properties"
sh "sed -i s/#DBREPLICASET#/${DBREPLICASET}/g ./src/main/resources/db-config.properties"
sh "sed -i s/#DBSCHEMA#/${DBSCHEMA}/g ./src/main/resources/db-config.properties"
sh "sed -i s/#DBUSR#/${DBUSR}/g ./src/main/resources/db-config.properties"
sh "set +x && sed -i s/#DBPW#/${DBPW}/g ./src/main/resources/db-config.properties"
sh "sed -i s/#PLAYGROUNDSERVICEURL#/${PLAYGROUNDSERVICEURL}/g ./src/main/resources/application.properties"
sh "sed -i s/#PLAYGROUNDSERVICEURL#/${PLAYGROUNDSERVICEURL}/g ./src/test/resources/application-test.properties"
sh "sed -i s/#USESWAGGER#/${USESWAGGER}/g ./src/main/resources/application.properties"
}
}
}
stage('Maven build') {
steps {
sh 'mvn clean package'
}
}
stage('Jacoco Coverage') {
steps {
jacoco changeBuildStatus: false, maximumClassCoverage: '50', maximumComplexityCoverage: '50', maximumLineCoverage: '50'
}
}
stage('Sonarqube') {
steps {
script {
def scannerHome=tool 'sonarqube'
withSonarQubeEnv('sonarqube_local') {
sh "${scannerHome}/bin/sonar-scanner -Dsonar.projectKey=${JOB_BASE_NAME} -Dsonar.sources='.' -Dsonar.java.binaries='.' -Dsonar.exclusions='target/**/*' -Dsonar.projectVersion=${JOBENV}.${BUILD_ID} -Dsonar.branch=${BRANCH} "
}
}
}
}
stage('Build docker image') {
steps {
script {
sh "sed -i s/#ARTIFACT#/${ARTIFACT}/g Dockerfile"
withDockerRegistry([credentialsId: 'dockeraws_pw', url: "http://docker.artifactory/"]) {
TAG="docker.artifactory/${ORG}/${JOB_BASE_NAME}:${BUILD_ID}"
def image=docker.build("${TAG}", "--no-cache -f Dockerfile .")
stage('Push docker image') {
image.push "${BUILD_ID}"
}
}
}
}
}
stage('Deploy docker image') {
steps {
script {
println "ENV: ${JOBENV}"
if (("${JOBENV}"=="3dash") || ("${JOBENV}"=="prod")) {
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'dockeraws_pw', usernameVariable: '_DOCKERUSER', passwordVariable: '_DOCKERPWD']]) {
sh """
ssh centos@${DOCKERHOST} "docker login -u $_DOCKERUSER -p $_DOCKERPWD ${DOCKERREPO} && docker pull ${DOCKERREPO}/${ORG}/${JOB_BASE_NAME}:${BUILD_ID}"
ssh centos@${DOCKERHOST} "docker stop ${JOB_BASE_NAME} || true && docker rm ${JOB_BASE_NAME} || true"
ssh centos@${DOCKERHOST} "docker run -d --name ${JOB_BASE_NAME} --restart always --network=${NET} -p ${HOSTPORT}:${DOCKERPORT} ${DOCKERREPO}/${ORG}/${JOB_BASE_NAME}:${BUILD_ID}"
ssh centos@${DOCKERHOST} "docker rmi ${DOCKERREPO}/${ORG}/${JOB_BASE_NAME}:${OLDBUILD} || true"
"""
}
}
else {
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'dockeraws_pw', usernameVariable: '_DOCKERUSER', passwordVariable: '_DOCKERPWD']]) {
sh """
ssh centos@${DOCKERHOST} "docker login -u $_DOCKERUSER -p $_DOCKERPWD ${DOCKERREPO} && docker pull ${DOCKERREPO}/${ORG}/${JOB_BASE_NAME}:${BUILD_ID}"
ssh centos@${DOCKERHOST} "docker stop ${JOB_BASE_NAME} || true && docker rm ${JOB_BASE_NAME} || true"
ssh centos@${DOCKERHOST} "docker run -d --name ${JOB_BASE_NAME} --restart always -p ${HOSTPORT}:${DOCKERPORT} ${DOCKERREPO}/${ORG}/${JOB_BASE_NAME}:${BUILD_ID}"
ssh centos@${DOCKERHOST} "docker rmi ${DOCKERREPO}/${ORG}/${JOB_BASE_NAME}:${OLDBUILD} || true"
"""
}
}
}
}
}
stage ('Validate End-Point') {
steps {
script {
sh """sleep "${VALIDATIONSLEEP}" && curl -H "Content-Type: application/json" "${VALIDATIONURL}" """
def connection=new URL("${VALIDATIONURL}").openConnection() as HttpURLConnection
connection.setRequestProperty('User-Agent', 'groovy-2.4.4')
connection.setRequestProperty('Content-Type', 'application/json')
RESULT=connection.inputStream.text
//if $RESULT
}
}
}
stage('Send results to Slack') {
steps {
slackSend(color: '#439FE0', message: "'${env.JOB_NAME}' #'${env.BUILD_ID}' '${COMMIT}' ", channel: '#pg-svcs')
}
}
}
post {
always {
script {
currentBuild.result = currentBuild.result ?: 'SUCCESS'
notifyBitbucket()
}
}
}
}
## Description ##
The template used in creating this service has the configuration inclusive of
1. `Consul` - Service Registry and Discovery
2. `Hystrix` - Circuit Breaker
3. `RabbitMQ` - Message Broker
4. `SpringBootAdmin` - Service Monitoring
5. `ElasticSearch` - Log Indexer
6. `Logstash` - Log Collector
7. `Kibana` - Log Visualizer
8. `Zipkin` - Log Trace Collector
9. `SpringCloudSleuth` - Log Tracing
10. `Togglz` - Feature Toggles
11. `Swagger` - API documentation
# Playground Template #
{
"hosting": {
"feature": {
"dockerPort": "8080",
"hostPort": "50116",
"dockerHost": "10.101.102.56"
},
"develop": {
"dockerPort": "8080",
"hostPort": "50116",
"dockerHost": "10.101.101.128"
},
"release": {
"dockerPort": "8080",
"hostPort": "50116",
"dockerHost": "10.101.103.65"
},
"master": {
"dockerPort": "8080",
"hostPort": "50116",
"dockerHost": "10.101.102.123"
}
},
"db-config.properties": {
"feature": {
"DBNODEPRIMARY": "cluster0-shard-00-00-q6qiu.azure.mongodb.net:27017",
"DBNODESECONDARY1": "cluster0-shard-00-01-q6qiu.azure.mongodb.net:27017",
"DBNODESECONDARY2": "cluster0-shard-00-02-q6qiu.azure.mongodb.net:27017",
"DBREPLICASET": "Cluster0-shard-0",
"DBSCHEMA": "pg_innovation_dev",
"DBUSR": "pg-dev",
"DBPW": "bek7sgkny5yJIjIS"
},
"develop": {
"DBNODEPRIMARY": "cluster0-shard-00-00-q6qiu.azure.mongodb.net:27017",
"DBNODESECONDARY1": "cluster0-shard-00-01-q6qiu.azure.mongodb.net:27017",
"DBNODESECONDARY2": "cluster0-shard-00-02-q6qiu.azure.mongodb.net:27017",
"DBREPLICASET": "Cluster0-shard-0",
"DBSCHEMA": "pg_innovation_qa",
"DBUSR": "pg-dev",
"DBPW": "bek7sgkny5yJIjIS"
},
"release": {
"DBNODEPRIMARY": "cluster0-shard-00-00-q6qiu.azure.mongodb.net:27017",
"DBNODESECONDARY1": "cluster0-shard-00-01-q6qiu.azure.mongodb.net:27017",
"DBNODESECONDARY2": "cluster0-shard-00-02-q6qiu.azure.mongodb.net:27017",
"DBREPLICASET": "Cluster0-shard-0",
"DBSCHEMA": "pg_innovation_uat",
"DBUSR": "pg-dev",
"DBPW": "bek7sgkny5yJIjIS"
},
"master": {
"DB": "playground-db:3306",
"DBSCHEMA": "pg_innovation",
"DBUSR": "appsupport",
"DBPW": "Oracle@123"
}
},
"application.properties": {
"feature": {
"USESWAGGER": true,
"PLAYGROUNDSERVICEURL": "3-playground.altimetrik.com",
"validationURL": "https://3-playground.altimetrik.com/template/",
"validationSleep": "30"
},
"develop": {
"USESWAGGER": true,
"PLAYGROUNDSERVICEURL": "2-playground.altimetrik.com",
"validationURL": "https://2-playground.altimetrik.com/template/",
"validationSleep": "30"
},
"release": {
"USESWAGGER": true,
"PLAYGROUNDSERVICEURL": "1-playground.altimetrik.com",
"validationURL": "https://1-playground.altimetrik.com/template/",
"validationSleep": "30"
},
"master": {
"USESWAGGER": false,
"PLAYGROUNDSERVICEURL": "playground.altimetrik.com",
"validationURL": "https://playground.altimetrik.com/template/",
"validationSleep": "30"
}
}
}
<?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</groupId>
<artifactId>playground-template</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>playground-template</name>
<description>Playground Template</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.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>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
<spring-boot-admin.version>2.1.0</spring-boot-admin.version>
<hystrix.version>1.3.0.RELEASE</hystrix.version>
<logback-encoder.version>4.9</logback-encoder.version>
<swagger.version>2.9.2</swagger.version>
<swagger-annotations.version>1.5.20</swagger-annotations.version>
<togglz.version>2.6.1.Final</togglz.version>
<commons-io.version>2.6</commons-io.version>
<gson.version>2.8.5</gson.version>
</properties>
<developers>
<developer>
<name>Tushar Das</name>
<email>tdas@altimetrik.com</email>
<organization>Altimetrik India Pvt Ltd</organization>
<organizationUrl>http://www.altimetrik.com</organizationUrl>
</developer>
</developers>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>${spring-boot-admin.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>${hystrix.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
<version>${hystrix.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>${logback-encoder.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<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>org.togglz</groupId>
<artifactId>togglz-spring-boot-starter</artifactId>
<version>${togglz.version}</version>
</dependency>
<dependency>
<groupId>org.togglz</groupId>
<artifactId>togglz-console</artifactId>
<version>${togglz.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version><!--$NO-MVN-MAN-VER$ -->
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<jvmArguments>
<options>
<option>-Xms512m</option>
<option>-Xmx1024m</option>
<option>-XX:+UseG1GC</option>
<option>-XX:MaxMetaspaceSize=512m</option>
<option>-XX:+UnlockExperimentalVMOptions</option>
<option>-XX:MaxGCPauseMillis=100</option>
<option>-XX:+ExplicitGCInvokesConcurrent</option>
<option>-XX:+UseStringDeduplication</option>
<option>-XX:ParallelGCThreads=10</option>
</options>
</jvmArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.3</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/jacoco</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation;
import java.io.File;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.togglz.core.manager.EnumBasedFeatureProvider;
import org.togglz.core.repository.StateRepository;
import org.togglz.core.repository.file.FileBasedStateRepository;
import org.togglz.core.spi.FeatureProvider;
import org.togglz.core.user.NoOpUserProvider;
import org.togglz.core.user.UserProvider;
import com.altimetrik.playground.innovation.feature.Features;
import com.altimetrik.playground.innovation.properties.ErrorProperties;
import com.altimetrik.playground.innovation.properties.ServiceProperties;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@ServletComponentScan
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
@EnableHystrixDashboard
@PropertySource(value = { "classpath:db-config.properties", "classpath:service.properties" })
@EnableConfigurationProperties({ ServiceProperties.class, ErrorProperties.class })
public class PlaygroundApplication {
public static void main(String[] args) {
SpringApplication.run(PlaygroundApplication.class, args);
}
@Bean
public FeatureProvider featureProvider() {
return new EnumBasedFeatureProvider(Features.class);
}
@Bean
public UserProvider userProvider() {
return new NoOpUserProvider();
}
@Bean
public StateRepository getStateRepository() {
return new FileBasedStateRepository(new File("src/main/resources/features.properties"), 10_000);
}
@Bean
public Gson gson() {
return new GsonBuilder().serializeNulls().create();
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.bean;
import lombok.Data;
@Data
public class BaseRequestBean {
public BaseRequestBean() {
super();
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.bean;
public class BaseResponse extends ResponseModel {
private static final long serialVersionUID = 1L;
public BaseResponse(StatusDetails status) {
super.setStatus(status);
}
public BaseResponse() {
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.bean;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class PgUser {
private Long userId;
private String name;
private String emailId;
public PgUser() {
super();
}
}
package com.altimetrik.playground.innovation.bean;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
* The Class Principal.
*
* @author Senthilkumar Duraisamy
*/
@JsonInclude(Include.NON_NULL)
public class Principal implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -1364484672867322008L;
/** The user id. */
private String userId;
/** The user name. */
private String userName;
/** The default realm. */
private String realm;
/** The default roles. */
private String roles;
/** The authenticated. */
private Boolean authenticated;
/** The first name. */
private String firstName;
/** The last name. */
private String lastName;
/** The user info mstr id. */
private String userInfoMstrId;
public String getUserInfoMstrId() {
return userInfoMstrId;
}
public void setUserInfoMstrId(String userInfoMstrId) {
this.userInfoMstrId = userInfoMstrId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* Gets the user id.
*
* @return the user id
*/
public String getUserId() {
return userId;
}
/**
* Sets the user id.
*
* @param userId the new user id
*/
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
/**
* Gets the realm.
*
* @return the realm
*/
public String getRealm() {
return realm;
}
/**
* Sets the realm.
*
* @param realm the new realm
*/
public void setRealm(String realm) {
this.realm = realm;
}
/**
* Gets the roles.
*
* @return the roles
*/
public String getRoles() {
return roles;
}
/**
* Sets the roles.
*
* @param roles the new roles
*/
public void setRoles(String roles) {
this.roles = roles;
}
/**
* Gets the authenticated.
*
* @return the authenticated
*/
public Boolean getAuthenticated() {
return authenticated;
}
/**
* Sets the authenticated.
*
* @param authenticated the new authenticated
*/
public void setAuthenticated(Boolean authenticated) {
this.authenticated = authenticated;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Principal [userId=");
builder.append(userId);
builder.append(", userName=");
builder.append(userName);
builder.append(", realm=");
builder.append(realm);
builder.append(", roles=");
builder.append(roles);
builder.append(", authenticated=");
builder.append(authenticated);
builder.append(", firstName=");
builder.append(firstName);
builder.append(", lastName=");
builder.append(lastName);
builder.append(", userInfoMstrId=");
builder.append(userInfoMstrId);
builder.append("]");
return builder.toString();
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.bean;
import java.io.Serializable;
import lombok.Data;
@Data
public class ResponseModel implements Serializable {
private static final long serialVersionUID = -8769927865634815829L;
private StatusDetails status;
public ResponseModel() {
super();
}
public ResponseModel(StatusDetails status) {
super();
this.status = status;
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.bean;
import lombok.Data;
@Data
public class StatusDetails {
/**
* Success Status code.
*/
public static final int SUCCESS = 1;
/**
* Failure Status code.
*/
public static final int FAILED = 0;
private Integer statusCode;
private String errorCode;
private String messageDescription;
public StatusDetails() {
super();
}
public StatusDetails(String errorCode, String messageDescription) {
super();
this.errorCode = errorCode;
this.messageDescription = messageDescription;
}
public StatusDetails(Integer statusCode) {
super();
this.statusCode = statusCode;
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.annotation.RabbitListenerConfigurer;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistrar;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory;
@Configuration
public class RabbitConfig implements RabbitListenerConfigurer {
public final static String QUEUE_NAME = "playground-innovation";
public final static String EXCHANGE_NAME = "playground.services-exchange";
public final static String ROUTING_KEY_NAME = "playground-innovation";
@Bean
Queue queue() {
return new Queue(QUEUE_NAME, true);
}
@Bean
TopicExchange exchange() {
return new TopicExchange(EXCHANGE_NAME);
}
@Bean
Binding binding(Queue queue, TopicExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY_NAME);
}
@Bean
public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(producerJackson2MessageConverter());
return rabbitTemplate;
}
@Bean
public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
public MappingJackson2MessageConverter consumerJackson2MessageConverter() {
return new MappingJackson2MessageConverter();
}
@Bean
public DefaultMessageHandlerMethodFactory messageHandlerMethodFactory() {
DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
factory.setMessageConverter(consumerJackson2MessageConverter());
return factory;
}
@Override
public void configureRabbitListeners(final RabbitListenerEndpointRegistrar registrar) {
registrar.setMessageHandlerMethodFactory(messageHandlerMethodFactory());
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.config;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
/**
* This configuration helps in disabling the authentication provided by spring
* boot admin client. Removing this configuration would result in a login page
* for authorization.
*
* @author skondapalli
*/
//@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl("/");
http.csrf().disable().authorizeRequests().antMatchers("/**").permitAll();
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.config;
import static springfox.documentation.builders.PathSelectors.regex;
import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.altimetrik.playground.innovation.properties.ServiceProperties;
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;
/**
* URL's for api docs and swagger UI are as follows:
* http://localhost:8080/reportsvc//swagger-ui.html
* http://localhost:8080/reportsvc//v2/api-docs
*
* @author skondapalli
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Autowired
ServiceProperties serviceProperties;
@Bean
public Docket serviceEndpoint() {
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("com.altimetrik.playground.innovation.controller")).paths(regex("/.*"))
.build().enable(serviceProperties.isSwaggerEnabled()).apiInfo(metaData());
}
private ApiInfo metaData() {
return new ApiInfo("Playground Innovation Service", "Playground API Services for Innovation Service", "1.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());
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.constants;
/**
* Indicates different possible actions across the service.
*
* @author skondapalli.
*/
public enum ActionTypeEnum {
UPDATE_IDEA("UPDATE_IDEA"), UPDATE_IDEA_STATUS("UPDATE_IDEA_STATUS");
private final String message;
ActionTypeEnum(final String argMessage) {
message = argMessage;
}
public final String getMessage() {
return message;
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.constants;
public enum ArtifactModeEnum {
IDEA("IDEA"), POC("POC");
private final String message;
ArtifactModeEnum(final String argMessage) {
message = argMessage;
}
public final String getMessage() {
return message;
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.constants;
public enum ArtifactTypeEnum {
LINK("LINK");
private final String message;
ArtifactTypeEnum(final String argMessage) {
message = argMessage;
}
public final String getMessage() {
return message;
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.constants;
public enum Status {
SUCCESS("SUCCESS"), FAILURE("FAILURE");
private String requestStatus;
Status(final String requestStatus) {
this.requestStatus = requestStatus;
}
public String getRequestStatus() {
return this.requestStatus;
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.altimetrik.playground.innovation.bean.BaseResponse;
import com.altimetrik.playground.innovation.bean.ResponseModel;
import com.altimetrik.playground.innovation.bean.StatusDetails;
import com.altimetrik.playground.innovation.exception.PgApplicationException;
public abstract class BaseController extends ResponseEntityExceptionHandler {
private static final String MESSAGE_DESCRIPTION = "messageDescription";
private static final String ERROR_CODE = "errorCode";
protected static final String PLATFORM_UNHANDLED_EXCEPTION_THROWN = "PG unhandled exception thrown.";
protected static final String PLATFORM_FATAL_EXCEPTION_THROWN = "PG fatal exception thrown.";
protected static final String PLATFORM_SYSTEM_EXCEPTION_THROWN = "PG system exception thrown.";
protected static final String PLATFORM_VALIDATION_ERROR = "Validation errors encountered";
protected static final String PLATFORM_APPLICATION_EXCEPTION_THROWN = "PG application exception thrown.";
@ExceptionHandler(PgApplicationException.class)
public ResponseEntity<BaseResponse> resolveApplicationException(HttpServletRequest request, HttpServletResponse response, Exception exception) {
PgApplicationException appException = (PgApplicationException) exception;
StatusDetails errorStatus = getErrorStatus(appException.getMessage(),
appException.getLocalizedMessage(appException.getMessage(), new Locale(""), appException.getArguments()));
BaseResponse errorResponse = new BaseResponse(errorStatus);
return new ResponseEntity<>(errorResponse, HttpStatus.OK);
}
@Override
@ResponseStatus(HttpStatus.BAD_REQUEST)
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
final List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
Map<String, Set<String>> errorsMap = fieldErrors.stream()
.collect(Collectors.groupingBy(FieldError::getField, Collectors.mapping(FieldError::getDefaultMessage, Collectors.toSet())));
return new ResponseEntity(errorsMap.isEmpty() ? ex : errorsMap, headers, status);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<BaseResponse> resolveUnhandledException(HttpServletRequest request, HttpServletResponse response, Exception exception) {
exception.printStackTrace();
StatusDetails errorStatus = getErrorStatus(PLATFORM_UNHANDLED_EXCEPTION_THROWN, exception.getMessage());
BaseResponse errorResponse = new BaseResponse(errorStatus);
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
/**
* Creates exception status object with the necessary information.
* @param errorCode - error code from exception class.
* @param errorMessage - error message.
* @return - status object.
*/
protected StatusDetails getErrorStatus(String errorCode, String errorMessage) {
StatusDetails errorResponse = new StatusDetails();
errorResponse.setErrorCode(errorCode);
errorResponse.setStatusCode(StatusDetails.FAILED);
errorResponse.setMessageDescription(errorMessage);
return errorResponse;
}
/**
* Prepares validation error response from binding result.
* @param bindingResult - which holds the validation errors.
* @param responseModel - response model.
*/
protected void prepareValidationErrorResponse(BindingResult bindingResult, ResponseModel responseModel) {
List<Object> errorArguments = new ArrayList<>();
StringBuilder messageDescription = new StringBuilder();
StringBuilder errorCodes = new StringBuilder();
StatusDetails status = new StatusDetails();
status.setStatusCode(StatusDetails.FAILED);
bindingResult.getFieldErrors().forEach(error -> {
if (messageDescription.length() > 0) {
messageDescription.append("; ");
}
messageDescription.append("@" + error.getField() + ": " + error.getDefaultMessage()).toString();
if (errorCodes.length() > 0) {
errorCodes.append("; ");
}
errorCodes.append(error.getCodes()[0]);
errorArguments.add(error.getRejectedValue());
});
status.setErrorCode(errorCodes.toString());
status.setMessageDescription(messageDescription.toString());
responseModel.setStatus(status);
}
/**
* Filters the errors from the errorList for the given objectname.
* @param errorsList - List of ObjectErrors
* @param objectName - Name of the model object
* @return list of errors.
*/
protected List getErrorsForObject(List<?> errorsList, String objectName) {
List filteredErrors = new ArrayList<ObjectError>();
for (Object object : errorsList) {
if (objectName.equals(((ObjectError) object).getObjectName())) {
filteredErrors.add(object);
}
}
return filteredErrors;
}
@SuppressWarnings("unchecked")
public static <T> T getNativeException(Throwable exp, Class<T> requiredType) {
if (requiredType != null) {
if (requiredType.isInstance(exp)) {
return (T) exp;
}
else if (exp instanceof Exception) {
return getNativeException(((Exception) exp).getCause(), requiredType);
}
}
return null;
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.controller;
import java.util.Calendar;
import javax.naming.ServiceUnavailableException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import com.altimetrik.playground.innovation.rabbitmq.MessagePublisher;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
@RestController
public class ServiceController {
@Autowired
protected RestTemplate restTemplate;
@Autowired
private MessagePublisher messagePublisher;
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
@GetMapping(value = "/")
public String home() {
return Calendar.getInstance().getTime().toString();
}
@GetMapping("/health-check")
public ResponseEntity<String> healthCheck() {
return new ResponseEntity<String>(HttpStatus.OK);
}
@GetMapping("/discovery")
@HystrixCommand(fallbackMethod = "home")
public String validateDiscovery() throws RestClientException, ServiceUnavailableException {
return this.restTemplate.getForObject("http://playground-innovation/", String.class);
}
@GetMapping("/message")
@HystrixCommand(fallbackMethod = "home")
public String publishMessage() {
final String now = Calendar.getInstance().getTime().toString();
this.messagePublisher.publishMessageToQueue(now);
return now;
}
@GetMapping("/test")
public String test() {
return "application is deployed successfully and running";
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.UUID;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 331467586921967105L;
/** The guid. */
private String guid = UUID.randomUUID().toString();
/** The created date. */
private Date createdDate;
/** The created by. */
private String createdBy;
/** The last modified date. */
private Date lastModifiedDate;
/** The last modified by. */
private String lastModifiedBy;
public BaseEntity() {
super();
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.exception;
public class AbstractServiceException extends Exception {
private int code;
public AbstractServiceException(final int code, final String message) {
super(message);
this.setCode(code);
}
public AbstractServiceException(final String message, final Throwable cause) {
super(message, cause);
}
public int getCode() {
return code;
}
public void setCode(final int code) {
this.code = code;
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.exception;
public class AuthorizationException extends AbstractServiceException {
public AuthorizationException(final int code, final String message) {
super(code, message);
}
public AuthorizationException(final String message, final Throwable cause) {
super(message, cause);
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.exception;
public class FeatureNotEnabledException extends AbstractServiceException {
public FeatureNotEnabledException(final int code, final String message) {
super(code, message);
}
public FeatureNotEnabledException(final String message, final Throwable cause) {
super(message, cause);
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.exception;
import java.util.Locale;
import com.altimetrik.playground.innovation.util.PlatformErrorConstant;
public abstract class PgApplicationException extends Exception {
private static final long serialVersionUID = 1186927232091885741L;
private static final String ERR_PREFIX = "[Error Code: ";
private static final String ERR_SUFFIX = "] ";
private final Object[] errorArguments;
public PgApplicationException() {
this(PlatformErrorConstant.APPLICATION_ERROR);
}
/**
* single argument constructor.
* @param errorCode - this argument receives error code instead of message.
* @param errorArgs - the arguments to be used to replace values within the message.
*/
public PgApplicationException(String errorCode, Object...errorArgs) {
this(errorCode, null, errorArgs);
}
/**
* Preferred constructor to be used to wrap the underlying exception within this exception object.
* @param errorCode - object encapsulating the error details(error code and message) with the predefined errorCode and message template.
* @param cause - the underlying cause of the exception
* @param errorArgs - the arguments to be used to replace values within the message.
*/
public PgApplicationException(String errorCode, Throwable cause, Object...errorArgs) {
super(errorCode, cause);
this.errorArguments = errorArgs;
}
/**
* Constructor with only exception argument.
* @param cause - passes exception instance.
*/
public PgApplicationException(Throwable cause) {
this(PlatformErrorConstant.APPLICATION_ERROR, cause);
}
/**
* Constructor with error code and exception instance and other attribute.
* @param errorCode - this argument receives error code instead of message.
* @param cause - instance of any exception
* @param enableSuppression - enable suppression
* @param writableStackTrace - writable stack trace.
* @param errorArgs - the arguments to be used to replace values within the message.
*/
public PgApplicationException(String errorCode, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Object...errorArgs) {
super(errorCode, cause, enableSuppression, writableStackTrace);
this.errorArguments = errorArgs;
}
/**
* Subclasses to provide their implementation to get the localized message for the given error code.
* @param errorCode - to translate into localized message.
* @param locale - locale to identify the messages.
* @param args - to replace with the place holder if any.
* @return - returns the localized text.
*/
public abstract String getLocalizedMessage(String errorCode, Locale locale, Object... args);
/**
* The component name for this exception.
* @return the component name of the module to which the exception is associated with.
*/
private String getComponent() {
return this.getClass().getSimpleName();
}
public Object[] getArguments() {
return errorArguments;
}
public String getUserMessage() {
return super.getMessage();
}
public String getTraceabilityMessage() {
String message = super.getMessage();
StringBuilder sb = new StringBuilder();
sb.append(getComponent()).append(" : ");
String errCode = message;
if (errCode != null) {
sb.append(ERR_PREFIX);
sb.append(errCode);
sb.append(ERR_SUFFIX);
}
sb.append(buildMessage(message, getCause()));
message = sb.toString();
return message;
}
/**
* Builds a message for the given base message and root cause.
* @param message the base message
* @param cause the root cause
* @return the full exception message
*/
private static String buildMessage(String message, Throwable cause) {
if (cause != null) {
StringBuilder sb = new StringBuilder();
if (message != null) {
sb.append(message).append("; ");
}
sb.append("nested exception is ").append(cause);
return sb.toString();
}
return message;
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.feature;
import org.togglz.core.Feature;
import org.togglz.core.annotation.EnabledByDefault;
import org.togglz.core.annotation.Label;
import org.togglz.core.context.FeatureContext;
import com.altimetrik.playground.innovation.exception.FeatureNotEnabledException;
public enum Features implements Feature {
@Standard
@EnabledByDefault
@Label("Invite Request Acceptance")
ACCEPT_INVITE,
@Standard
@Label("Join Request Approval")
APPROVE_JOIN;
// Reduced the scope for exception handling using a FeatureValidatorUtil
// class.
private boolean isActive() throws FeatureNotEnabledException {
return FeatureContext.getFeatureManager().isActive(this);
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.feature;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.togglz.core.annotation.FeatureGroup;
import org.togglz.core.annotation.Label;
@FeatureGroup
@Label("Standard")
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Standard {
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.model;
import java.io.Serializable;
import java.util.Date;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import lombok.Data;
@Data
public class BaseEntity implements Serializable {
private static final long serialVersionUID = -6450038133573391912L;
@CreatedBy
private String createdBy;
@CreatedDate
private Date createdDate;
@LastModifiedBy
private String lastModifiedBy;
@LastModifiedDate
private Date lastModifiedDate;
public BaseEntity() {
super();
}
public BaseEntity(String loggedInUser) {
super();
this.createdBy = loggedInUser;
this.lastModifiedBy = loggedInUser;
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@ConfigurationProperties(prefix = "error")
public class ErrorProperties {
private int unknownErrorCode;
private String unknownErrorMessage;
private int featureNotEnabledErrorCode;
private String featureNotEnabledErrorMessage;
private int invalidIdeaStatusTransitionErrorCode;
private String invalidIdeaStatusTransitionErrorMessage;
private int invalidRoleInfoErrorCode;
private String invalidRoleInfoErrorMessage;
private int authorizationErrorCode;
private String authorizationErrorMessage;
private int invalidIdeaInfoErrorCode;
private String invalidIdeaInfoErrorMessage;
private int operationNotAllowedErrorCode;
private String operationNotAllowedErrorMessage;
private int invalidIdeaCategoryInfoErrorCode;
private String invalidIdeaCategoryInfoErrorMessage;
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
@Data
@ConfigurationProperties(prefix = "innovation")
public class ServiceProperties {
private String url;
private boolean swaggerEnabled;
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.rabbitmq;
import java.util.Calendar;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
import com.altimetrik.playground.innovation.config.RabbitConfig;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class MessageListener {
@RabbitListener(queues = RabbitConfig.QUEUE_NAME)
public void process(final String data) {
try {
log.info("Processing a message at " + Calendar.getInstance().getTime());
// Use the ObjectMapper to perform the data conventions and continue
// with
// further processing.
// Header should contain the meta data of the messages consumed so
// that the
// corresponding handlers can be invoked.
}
catch (Exception e) {
// Log the exception.
}
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.rabbitmq;
import java.util.Calendar;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.altimetrik.playground.innovation.config.RabbitConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class MessagePublisher {
@Autowired
private RabbitTemplate rabbitTemplate;
public void publishMessageToQueue(final Object message) {
try {
this.rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME, RabbitConfig.ROUTING_KEY_NAME, new ObjectMapper().writeValueAsString(message));
log.info("Published the message at " + Calendar.getInstance().getTime());
}
catch (Exception e) {
// Log the exception.
}
}
}
/**
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
*/
package com.altimetrik.playground.innovation.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.mongodb.config.EnableMongoAuditing;
/**
* The Class AuditorAwareConfig.
* @author Altimetrik CodeGen
*/
@Configuration
@EnableMongoAuditing(auditorAwareRef = "auditorAware")
public class AuditorAwareConfig {
/**
* Auditor aware.
*
* @return the auditor aware
*/
@Bean
public AuditorAware<String> auditorAware() {
return new SpringSecurityAuditorAware();
}
}
/**
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
*/
package com.altimetrik.playground.innovation.security;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* AuthConfig Class.
* @author Harish Mangala
*/
@Component
public class AuthConfig {
/**
* x-playground-authentication.
*/
public static final String X_AUTHENTICATION_TOKEN = "x-playground-authentication";
/** The default user. */
@Value("${regulus.security.defaultUser:#{'SYSTEM'}}")
private String defaultUser;
/** The default user. */
@Value("${regulus.security.defaultUserId:#{'SYSTEM'}}")
private String defaultUserId;
/** The default realm. */
@Value("${regulus.security.defaultRealm:#{'REGULUS'}}")
private String defaultRealm;
/** The default roles. */
@Value("${regulus.security.defaultRoles:#{'ROLE_anonymous'}}")
private String defaultRoles;
/** The third party authentication users. */
@Value("${regulus.thirdparty.auth.users:SYSTEM}")
private List<String> thirdPartyUsers;
/** The user info mstr id. */
@Value("${regulus.security.defaultUser:#{0L}}")
private Long userInfoMstrId;
/**
* Gets thirdPartyUser.
* @return the thirdPartyUser
*/
public List<String> getThirdPartyUsers() {
return thirdPartyUsers;
}
/**
* Gets the default user.
*
* @return the default user
*/
public String getDefaultUser() {
return defaultUser;
}
/**
* Gets the default user id.
*
* @return the default user id
*/
public String getDefaultUserId() {
return defaultUserId;
}
public Long getUserInfoMstrId() {
return userInfoMstrId;
}
public void setUserInfoMstrId(Long userInfoMstrId) {
this.userInfoMstrId = userInfoMstrId;
}
/**
* Gets the default realm.
*
* @return the default realm
*/
public String getDefaultRealm() {
return defaultRealm;
}
/**
* Gets the default roles.
*
* @return the default roles
*/
public String getDefaultRoles() {
return defaultRoles;
}
}
/**
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
*/
package com.altimetrik.playground.innovation.security;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import com.altimetrik.playground.innovation.bean.Principal;
/**
* AuthValidatorUtil Class.
* @author Altimetrik Technologies
*/
public final class AuthValidatorUtil {
/**
* Instantiates a new auth validator util.
*/
private AuthValidatorUtil() {
// No Constructor.
}
/**
* Checks if is valid user.
*
* @param principal
* the principal
* @param userId
* the user id
* @return true, if is valid user
*/
public static boolean isValidUser(Principal principal, String userId) {
if (StringUtils.isBlank(userId) || principal == null) {
return false;
}
return (userId.equals(principal.getUserId()));
}
/**
* Checks if is valid user by user name.
*
* @param principal
* the principal
* @param userName
* the user name
* @return true, if is valid user by user name
*/
public static boolean isValidUserByUserName(Principal principal, String userName) {
if (StringUtils.isBlank(userName) || principal == null) {
return false;
}
return (userName.equals(principal.getUserName()));
}
/**
* Checks if is valid user.
*
* @param authentication
* the authentication
* @param userId
* the user id
* @return true, if is valid user
*/
public static boolean isValidUser(Authentication authentication, String userId) {
return isValidUser(getPrincipal(authentication), userId);
}
/**
* Checks if is valid user by user name.
*
* @param authentication
* the authentication
* @param userName
* the user name
* @return true, if is valid user by user name
*/
public static boolean isValidUserByUserName(Authentication authentication, String userName) {
return isValidUserByUserName(getPrincipal(authentication), userName);
}
/**
* Gets the principal.
*
* @param authentication
* the authentication
* @return the principal
*/
public static Principal getPrincipal(Authentication authentication) {
if (authentication != null && authentication.getPrincipal() instanceof Principal) {
return ((Principal) authentication.getPrincipal());
}
return null;
}
/**
* to get user name of the authenticated user.
* @param authentication
* @return
*/
public static String getUserName(Authentication authentication) {
Principal principal = getPrincipal(authentication);
if (principal != null) {
return principal.getUserName();
}
return null;
}
/**
* to get the user id of the authenticated user.
* @param authentication
* @return
*/
public static String getUserId(Authentication authentication) {
Principal principal = getPrincipal(authentication);
if (principal != null) {
return principal.getUserId();
}
return null;
}
}
/**
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
*/
package com.altimetrik.playground.innovation.security;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
import com.altimetrik.playground.innovation.bean.Principal;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
/**
* Detects if there is no {@code Authentication} object in the
* {@code SecurityContextHolder}, and populates it with gateway authenticated
* user details.
*
* @author Altimetrik Technologies
*/
@Slf4j
public class GatewayAuthenticationFilter extends AnonymousAuthenticationFilter {
private static final String SPACE = " ";
/** The default user. */
@Value("${regulus.security.defaultUser:#{'anonymoususer'}}")
private String defaultUser;
/** The default realm. */
@Value("${regulus.security.defaultRealm:#{'anonymous'}}")
private String defaultRealm;
/** The default roles. */
@Value("${regulus.security.defaultRoles:#{'ROLE_anonymous'}}")
private String defaultRoles;
/**
* Instantiates a new gateway authentication filter.
*
* @param key the key
*/
public GatewayAuthenticationFilter(String key) {
super(key);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
String principal = StringUtils.defaultIfBlank(request.getHeader("x-regulus-user"), this.defaultUser);
if (SecurityContextHolder.getContext().getAuthentication() == null) {
SecurityContextHolder.getContext().setAuthentication(createAuthentication(request));
if (log.isDebugEnabled()) {
log.debug("Populated SecurityContextHolder with gateway authenticated user: '" + SecurityContextHolder.getContext().getAuthentication() + "'");
}
}
else {
if (log.isDebugEnabled()) {
log.debug("SecurityContextHolder not populated with gateway authenticated user, as it already contained: '" + SecurityContextHolder.getContext().getAuthentication()
+ "'");
}
}
if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof Principal) {
Principal principalObj = (Principal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
principal = principalObj.getUserName();
}
Stopwatch stopwatch = Stopwatch.createStarted();
chain.doFilter(req, res);
stopwatch.stop();
createTraceEvent(principal, stopwatch.elapsed(TimeUnit.MILLISECONDS), request);
}
/**
* Creates the authentication.
* @param request the request
* @return the authentication
*/
@Override
protected Authentication createAuthentication(HttpServletRequest request) {
String principal = StringUtils.defaultIfBlank(request.getHeader("x-regulus-user"), this.defaultUser);
String key = StringUtils.defaultIfBlank(request.getHeader("x-regulus-user-realm"), this.defaultRealm);
boolean notAuthenticated = "false".equalsIgnoreCase(request.getHeader("x-regulus-user-authenticated"));
String authorityString = StringUtils.defaultIfBlank(request.getHeader("x-regulus-user-authorities"), this.defaultRoles);
List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authorityString);
AnonymousAuthenticationToken authentication = new AnonymousAuthenticationToken(key, principal, authorities);
authentication.setAuthenticated(!notAuthenticated);
return authentication;
}
protected void createTraceEvent(String principal, long millis, HttpServletRequest request) {
StringBuilder message = new StringBuilder();
message.append(StringUtils.defaultIfBlank(request.getHeader("X-Real-IP"), "-") + SPACE);
message.append(principal + SPACE);
message.append(request.getRequestURI() + SPACE);
message.append(request.getMethod() + SPACE);
message.append(StringUtils.defaultIfBlank(request.getHeader("X-Request-ID"), "-") + SPACE);
message.append(millis);
log.info(message.toString());
}
}
/**
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
*/
package com.altimetrik.playground.innovation.security;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
import com.altimetrik.playground.innovation.bean.Principal;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
/**
* Detects if there is no {@code Authentication} object in the
* {@code SecurityContextHolder}, and populates it with gateway authenticated
* user details.
*
* @author Altimetrik CodeGen.
*/
@Slf4j
public class GatewayAuthenticationTokenFilter extends AnonymousAuthenticationFilter {
@Autowired
private AuthConfig authConfig;
/**
* Instantiates a new gateway authentication filter.
* @param key the key
*/
public GatewayAuthenticationTokenFilter(String key) {
super(key);
}
/**
* Creates the authentication.
* @param request the request
* @return the authentication
*/
@Override
protected Authentication createAuthentication(HttpServletRequest request) {
Principal principal = null;
String authToken = StringUtils.defaultIfBlank(request.getHeader(AuthConfig.X_AUTHENTICATION_TOKEN), null);
if (!org.springframework.util.StringUtils.isEmpty(authToken)) {
try {
byte[] base64AuthToken = Base64.getDecoder().decode(authToken);
principal = new ObjectMapper().readValue(new String(base64AuthToken), Principal.class);
}
catch (IOException e) {
log.error("Failed to parse principal object from auth token: '" + authToken + "'", e);
principal = null;
}
}
if (principal == null) {
principal = new Principal();
principal.setUserName(authConfig.getDefaultUser());
principal.setUserId(authConfig.getDefaultUserId());
principal.setUserInfoMstrId(Long.toString(authConfig.getUserInfoMstrId()));
principal.setRealm(authConfig.getDefaultRealm());
principal.setRoles(authConfig.getDefaultRoles());
principal.setAuthenticated(Boolean.TRUE);
}
List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(principal.getRoles());
AnonymousAuthenticationToken authentication = new AnonymousAuthenticationToken(principal.getRealm(), principal, authorities);
authentication.setAuthenticated(principal.getAuthenticated());
if (log.isDebugEnabled()) {
log.debug("Populated SecurityContextHolder with gateway authenticated user: '" + authentication + "'");
}
return authentication;
}
}
/**
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
*/
package com.altimetrik.playground.innovation.security;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AnonymousAuthenticationProvider;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
/**
* Security config class.
*
* @author Altimetrik Technologies.
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/** The regulus. */
private static String strRegulus = "regulus";
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(gatewayAuthenticationProvider());
}
/**
* Gateway authentication provider.
*
* @return the authentication provider
*/
@Bean
public AuthenticationProvider gatewayAuthenticationProvider() {
return new AnonymousAuthenticationProvider(strRegulus);
}
/**
* Gateway authentication filter.
*
* @return the anonymous authentication filter
*/
@Bean
public AnonymousAuthenticationFilter gatewayAuthenticationFilter() {
return new GatewayAuthenticationFilter(strRegulus);
}
/**
* Gateway authentication token filter.
*
* @return the anonymous authentication filter
*/
@Bean
public AnonymousAuthenticationFilter gatewayAuthenticationTokenFilter() {
return new GatewayAuthenticationTokenFilter(strRegulus);
}
/**
* Unauthorized entry point.
*
* @return the authentication entry point
*/
@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
/**
* Trust resolver.
*
* @return the authentication trust resolver
*/
@Bean
public AuthenticationTrustResolver trustResolver() {
return new AuthenticationTrustResolver() {
@Override
public boolean isRememberMe(final Authentication authentication) {
return false;
}
@Override
public boolean isAnonymous(final Authentication authentication) {
return false;
}
};
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers("/**").permitAll().anyRequest()
.authenticated().and().anonymous().authenticationFilter(gatewayAuthenticationTokenFilter()).authenticationProvider(gatewayAuthenticationProvider());
}
}
/**
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
*/
package com.altimetrik.playground.innovation.security;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* The Class AuditorAwareImpl.
* @author Altimetrik CodeGen
*/
public class SpringSecurityAuditorAware implements AuditorAware<String> {
@Value("${regulus.security.enabled:true}")
private boolean securityEnabled;
@Override
public Optional<String> getCurrentAuditor() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null && !securityEnabled) {
return Optional.of("Sysadmin");
}
String userId = AuthValidatorUtil.getUserId(authentication);
return Optional.of(userId);
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.togglz.core.context.FeatureContext;
import com.altimetrik.playground.innovation.exception.FeatureNotEnabledException;
import com.altimetrik.playground.innovation.feature.Features;
import com.altimetrik.playground.innovation.properties.ErrorProperties;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
public class FeatureValidatorUtil {
@Autowired
private ErrorProperties errorProperties;
private ErrorProperties getErrorProperties() {
return this.errorProperties;
}
public boolean isActive(Features feature) throws FeatureNotEnabledException {
if (FeatureContext.getFeatureManager().isActive(feature))
return true;
log.error("Feature not enabled", feature.toString());
throw new FeatureNotEnabledException(this.getErrorProperties().getFeatureNotEnabledErrorCode(), this.getErrorProperties().getFeatureNotEnabledErrorMessage());
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.util;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import com.altimetrik.playground.innovation.entity.BaseEntity;
import com.mongodb.Function;
@Service
public class MongoUtils {
@Autowired
private MongoTemplate mongo;
public <D, N extends BaseEntity> N findNestedDocument(Class<D> docClass, String collectionName, String outerId, String innerId, Function<D, List<N>> collectionGetter) {
// get index of subdocument in array
Query query = new Query(Criteria.where("_id").is(outerId).and(collectionName + "._id").is(innerId));
query.fields().include(collectionName + "._id");
D obj = mongo.findOne(query, docClass);
if (obj == null) {
return null;
}
List<String> itemIds = collectionGetter.apply(obj).stream().map(N::getGuid).collect(Collectors.toList());
int index = itemIds.indexOf(innerId);
if (index == -1) {
return null;
}
// retrieve subdocument at index using slice operator
Query query2 = new Query(Criteria.where("_id").is(outerId).and(collectionName + "._id").is(innerId));
query2.fields().include(collectionName).slice(collectionName, index, 1);
D obj2 = mongo.findOne(query2, docClass);
if (obj2 == null) {
return null;
}
return collectionGetter.apply(obj2).get(0);
}
public void removeNestedDocument(UUID outerId, UUID innerId, String collectionName, Class<?> outerClass) {
Update update = new Update();
update.pull(collectionName, new Query(Criteria.where("_id").is(innerId)));
mongo.updateFirst(new Query(Criteria.where("_id").is(outerId)), update, outerClass);
}
}
package com.altimetrik.playground.innovation.util;
public final class PlatformErrorConstant {
private PlatformErrorConstant() {
//private constructor to avoid instantiation.
}
/**
* Use this constant for default system exception.
*/
public static final String SYSTEM_ERROR = "system.error";
/**
* Use this constant for default application exception.
*/
public static final String APPLICATION_ERROR = "application.error";
/**
* Use this constant for default fatal exception.
*/
public static final String FATAL_ERROR = "fatal.error";
}
package com.altimetrik.playground.innovation.util;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import com.altimetrik.playground.innovation.bean.Principal;
/**
* The Class UserUtil.
*/
@Component("userUtil")
public class UserUtil {
/**
* Gets the logged in user.
*
* @return the logged in user
*/
public String getLoggedInUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Principal principal = (Principal) authentication.getPrincipal();
return principal.getUserId();
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.webmvc;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.io.IOUtils;
public class RequestWrapper extends HttpServletRequestWrapper {
private ByteArrayOutputStream cachedInputStream;
public RequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (this.cachedInputStream == null) {
// Cache the request input stream.
this.cacheInputStream();
}
// An input stream which reads the cached input stream.
return new CachedServletInputStream();
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
private void cacheInputStream() throws IOException {
// Cache the input stream in order to read it multiple times.
this.cachedInputStream = new ByteArrayOutputStream();
IOUtils.copy(super.getInputStream(), this.cachedInputStream);
}
public class CachedServletInputStream extends ServletInputStream {
private ByteArrayInputStream input;
public CachedServletInputStream() {
// Create a new input stream from the cached input stream.
this.input = new ByteArrayInputStream(cachedInputStream.toByteArray());
}
@Override
public int read() throws IOException {
return this.input.read();
}
@Override
public boolean isFinished() {
return this.input.available() == 0;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener listener) {
throw new RuntimeException("No async processing implementation");
}
}
}
/*******************************************************************************
* Copyright (C) Altimetrik 2018. All rights reserved.
*
* This software is the confidential and proprietary information
* of Altimetrik. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms and conditions
* entered into with Altimetrik.
******************************************************************************/
package com.altimetrik.playground.innovation.webmvc;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter(urlPatterns = { "/v1/role/*" })
public class RolesFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
final RequestWrapper request = new RequestWrapper((HttpServletRequest) servletRequest);
final HttpServletResponse response = (HttpServletResponse) servletResponse;
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
logging:
level:
org:
springframework:
data:
mongodb:
core: DEBUG
management:
endpoint:
health:
show-details: always
endpoints:
web:
exposure:
include: '*'
playground:
microservice-admin-host: 10.101.102.56
server:
port: ${PORT:8080}
servlet:
context-path: /playground-template
spring:
application:
name: playground-template
boot:
admin:
client:
instance:
metadata:
user:
name: user
password: user
password: admin
url: http://${playground.microservice-admin-host}:50207
username: admin
cloud:
consul:
discovery:
enabled: true
health-check-interval: 60s
health-check-path: ${server.servlet.context-path}/health-check
instance-id: ${spring.application.name}:${spring.application.instance_id:${random.value}}
host: ${playground.microservice-admin-host}
port: 8500
rabbitmq:
host: ${playground.microservice-admin-host}
password: admin
port: 5672
username: admin
virtual-host: /
security:
user:
name: user
password: user
sleuth:
sampler:
probability: 1
zipkin:
base-url: http://${playground.microservice-admin-host}:9411/
sender:
type: web
togglz:
console:
enabled: true
secured: false
use-management-port: false
enabled: true
,------. ,--. ,--.
| .--. ' | | ,--,--. ,--. ,--. ,---. ,--.--. ,---. ,--.,--. ,--,--, ,-| |
| '--' | | | ' ,-. | \ ' / | .-. | | .--' | .-. | | || | | \ ' .-. |
| | --' | | \ '-' | \ ' ' '-' ' | | ' '-' ' ' '' ' | || | \ `-' |
`--' `--' `--`--' .-' / .`- / `--' `---' `----' `--''--' `---'
/*******************************************************************************
* Copyright 2012-19, Altimetrik, India. Pvt. Ltd. All Rights Reserved.
******************************************************************************/
\ No newline at end of file
# Spring Boot automatically creates a JPA EntityManagerFactory using Hibernate
# but we need to override some defaults:
spring.jpa.show-sql=true
spring.jpa.open-in-view=true
# - Mongo DB Configurations
#spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use.
#spring.data.mongodb.grid-fs-database= # GridFS database name.
spring.data.mongodb.socketKeepAlive=true
spring.data.mongo.repositories.enabled=true
spring.data.mongodb.uri=mongodb://#DBUSR#:#DBPW#@#DBNODEPRIMARY#,#DBNODESECONDARY1#,#DBNODESECONDARY2#/#DBSCHEMA#?ssl=true&replicaSet=#DBREPLICASET#&authSource=admin&retryWrites=true&serverSelectionTimeoutMS=90000&connectTimeoutMS=60000&maxPoolSize=30
#Tue Mar 05 23:03:13 IST 2019
APPROVE_JOIN=false
ACCEPT_INVITE=true
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread,%X{X-B3-TraceId:-},%X{X-B3-SpanId:-}] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<appender name="STASH"
class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>10.101.102.56:5050</destination>
<encoder
class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<mdc /> <!-- MDC variables on the Thread will be written as JSON fields -->
<context /> <!--Outputs entries from logback's context -->
<version /> <!-- Logstash json format version, the @version field in the output -->
<logLevel />
<loggerName />
<pattern>
<pattern>{"ServiceName": "playground-innovation"}</pattern>
</pattern>
<threadName />
<message />
<logstashMarkers />
<arguments />
<stackTrace />
</providers>
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
<appender-ref ref="STASH" />
</root>
<logger name="com.altimetrik" level="ALL">
<appender-ref ref="STASH" />
</logger>
<logger name="org" level="ERROR" />
<logger name="net" level="ERROR" />
</configuration>
# Service properties
innovation.swagger-enabled=true
innovation.url=https://#PLAYGROUNDSERVICEURL#/
# Error properties
error.unknown-error-code=1000
error.unknown-error-message=unknown error
error.template-not-loading-error-code=1001
error.feature-not-enabled-error-message=feature not enabled
error.invalid-idea-status-transition-error-code=1002
error.invalid-idea-status-transition-error-message=invalid idea transition
error.invalid-role-info-error-code=1003
error.invalid-role-info-error-message=invalid role info
error.authorization-error-code=1004
error.authorization-error-message=unauthorized access to endpoint
error.invalid-idea-info-error-code=1005
error.invalid-idea-info-error-message=invalid idea info
error.operation-not-allowed-error-code=1006
error.operation-not-allowed-error-message=operation not allowed
error.invalid-idea-category-info-error-code=1007
error.invalid-idea-category-info-error-message=invalid idea category info
\ No newline at end of file
logging:
level:
org:
springframework:
data:
mongodb:
core: DEBUG
management:
endpoint:
health:
show-details: always
endpoints:
web:
exposure:
include: '*'
playground:
microservice-admin-host: 10.101.102.56
server:
port: ${PORT:8080}
servlet:
context-path: /template
spring:
application:
name: playground-template
boot:
admin:
client:
instance:
metadata:
user:
name: user
password: user
password: admin
url: http://${playground.microservice-admin-host}:50207
username: admin
cloud:
consul:
discovery:
enabled: true
health-check-interval: 60s
health-check-path: ${server.servlet.context-path}/health-check
instance-id: ${spring.application.name}:${spring.application.instance_id:${random.value}}
host: ${playground.microservice-admin-host}
port: 8500
rabbitmq:
host: ${playground.microservice-admin-host}
password: admin
port: 5672
username: admin
virtual-host: /
security:
user:
name: user
password: user
sleuth:
sampler:
probability: 1
zipkin:
base-url: http://${playground.microservice-admin-host}:9411/
sender:
type: web
togglz:
console:
enabled: true
secured: false
use-management-port: false
enabled: true
,------. ,--. ,--.
| .--. ' | | ,--,--. ,--. ,--. ,---. ,--.--. ,---. ,--.,--. ,--,--, ,-| |
| '--' | | | ' ,-. | \ ' / | .-. | | .--' | .-. | | || | | \ ' .-. |
| | --' | | \ '-' | \ ' ' '-' ' | | ' '-' ' ' '' ' | || | \ `-' |
`--' `--' `--`--' .-' / .`- / `--' `---' `----' `--''--' `---'
/*******************************************************************************
* Copyright 2012-19, Altimetrik, India. Pvt. Ltd. All Rights Reserved.
******************************************************************************/
\ No newline at end of file
# Spring Boot automatically creates a JPA EntityManagerFactory using Hibernate
# but we need to override some defaults:
spring.jpa.show-sql=true
spring.jpa.open-in-view=true
# - Mongo DB Configurations
#spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use.
#spring.data.mongodb.grid-fs-database= # GridFS database name.
spring.data.mongodb.socketKeepAlive=true
spring.data.mongo.repositories.enabled=true
spring.data.mongodb.uri=mongodb://#DBUSR#:#DBPW#@#DBNODEPRIMARY#,#DBNODESECONDARY1#,#DBNODESECONDARY2#/#DBSCHEMA#?ssl=true&replicaSet=#DBREPLICASET#&authSource=admin&retryWrites=true&serverSelectionTimeoutMS=90000&connectTimeoutMS=60000&maxPoolSize=30
#Tue Mar 05 23:03:13 IST 2019
APPROVE_JOIN=false
ACCEPT_INVITE=true
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread,%X{X-B3-TraceId:-},%X{X-B3-SpanId:-}] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<appender name="STASH"
class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<destination>10.101.102.56:5050</destination>
<encoder
class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
<providers>
<mdc /> <!-- MDC variables on the Thread will be written as JSON fields -->
<context /> <!--Outputs entries from logback's context -->
<version /> <!-- Logstash json format version, the @version field in the output -->
<logLevel />
<loggerName />
<pattern>
<pattern>{"ServiceName": "playground-innovation"}</pattern>
</pattern>
<threadName />
<message />
<logstashMarkers />
<arguments />
<stackTrace />
</providers>
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
<appender-ref ref="STASH" />
</root>
<logger name="com.altimetrik" level="ALL">
<appender-ref ref="STASH" />
</logger>
<logger name="org" level="ERROR" />
<logger name="net" level="ERROR" />
</configuration>
# Service properties
innovation.swagger-enabled=true
innovation.url=https://#PLAYGROUNDSERVICEURL#/
# Error properties
error.unknown-error-code=1000
error.unknown-error-message=unknown error
error.template-not-loading-error-code=1001
error.feature-not-enabled-error-message=feature not enabled
error.invalid-idea-status-transition-error-code=1002
error.invalid-idea-status-transition-error-message=invalid idea transition
error.invalid-role-info-error-code=1003
error.invalid-role-info-error-message=invalid role info
error.authorization-error-code=1004
error.authorization-error-message=unauthorized access to endpoint
error.invalid-idea-info-error-code=1005
error.invalid-idea-info-error-message=invalid idea info
error.operation-not-allowed-error-code=1006
error.operation-not-allowed-error-message=operation not allowed
error.invalid-idea-category-info-error-code=1007
error.invalid-idea-category-info-error-message=invalid idea category info
\ No newline at end of file
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