Sunday, 3 December 2017

Rest Api Spring 4 - Swagger - API Documentation

Swagger Configuration For your Project.

1) Pom.xml for Jars 

<!-- SWAGGER DEPENDANCY START -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-core</artifactId>
<version>2.7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spi</artifactId>
<version>2.7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.10</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spring-web</artifactId>
<version>2.7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-common</artifactId>
<version>2.7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
<version>1.2.0.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-metadata</artifactId>
<version>1.2.0.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.13</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-schema</artifactId>
<version>2.7.0</version>
<scope>provided</scope>
</dependency>

<!-- SWAGGER DEPENDANCY END -->



2) Swagger Config Class

package com.dreamz.configuration;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(paths())
                .build();
    }

    // Describe your apis
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger Sample APIs")
                .description("This page lists all the rest apis for Swagger Sample App.")
                .version("1.0-SNAPSHOT")
                .build();
    }

    // Only select apis that matches the given Predicates.
    private Predicate<String> paths() {
    // Match all paths except /error
        return Predicates.and(
        PathSelectors.regex("/.*"), 
        Predicates.not(PathSelectors.regex("/error.*"))
        );
    }
}



3)   API Mapping with Data

@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successful retrieval of user detail",response=DashBoard.class  ),
@ApiResponse(code = 422, message = "Service Error")})
@PostMapping(value = "/dashboard", produces = MediaType.APPLICATION_JSON_VALUE)
public Object test(@RequestBody Message message ,HttpSession session) {//REST Endpoint.

logger.info("hello");
//Message msg = new Message( "Hello " ,"hello111");
String response"";
response ="{'user':{'userId':'as','userKey':'tester from service'}}";
return response;

}



Saturday, 2 September 2017

Log4j2 java logging example

As developers  we often, create the multiple log statements stating entry and and exit of methods and specially trace back to lot of exception handling lines with statically typed error messages.

Ideal way to handle this kind of tracing should be via built in library methods.
In this case Log4j2 makes it really easy with its api for entry and exit.
Simple example to test your logs in your api.

  static final Logger logger = LogManager.getLogger(AppController.class.getName());
@RequestMapping("/")
public String welcome() {
logger.traceEntry();
callMe();
logger.traceExit();
return "API UP";
}
private void callMe() {
try {
logger.traceEntry();
logger.info("Test info");
logger.debug("Test Debug");
throw new NullPointerException();
} catch (Exception e) {
logger.error("error occurred", e);
}
}

Maven projects just require 2 dependency, try to use the latest.

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.8.2</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.8.2</version>

  </dependency>


Configurations are easy and gives you control to use your logging mechanism based on the packages.
log4j.xml. Quick Tip make sure the pattern is well defined to give you the method name.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="CONSOLE" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level 
%logger{36} %method - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console" />
</Root>
<logger name="com.dreamz" level="INFO" />
<Root level="ERROR">
<AppenderRef ref="CONSOLE"/>
</Root>
</Loggers>
</Configuration>

Adding Log4j2 to the spring mvc xml based config , and just make sure log4j2.xml is on the class path


  <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.8.2</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.8.2</version>
    <scope>provided</scope>
     </dependency>
    <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.8.2</version>
   <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
<scope>provided</scope>
</dependency>

Tuesday, 18 July 2017

Brute Force Removal of Json Attribute from Json String : IBM JSON JAVA LIB

       


        
  // Invocation Sending a json String and removal of key elements from the json String
    String logString = json;
    logString = maskedLog(logString);
    logger.info("Response Data : "+logString);
    
    
    
  public static String maskedLog(String logString){
 
    for (String s : sensitiveKeys){
     try {
      logString=   removeField(s, logString);
    } catch (IOException e) {
     logger.severe("Exception in Util maskedLog ");
    }
    }
    return logString;
 }  
    
   public static String removeField(String key, String jsonString) throws NullPointerException, IOException {
  JSONArtifact artifact = (JSONArtifact) JSON.parse(jsonString);     
  removeField(key, artifact);      
  return artifact.toString();  
 }

 private static void removeField(String key, Object json) {
  if (json instanceof JSONObject) {
   JSONObject o = (JSONObject) json;
   o.remove(key);
   Collection values = o.values();
   traverseCollection(key, values);
  } else if (json instanceof JSONArray) {
   JSONArray array = (JSONArray) json;
   traverseCollection(key, array);
  }
 }

 private static void traverseCollection(String key, Collection collection) {
  for (Object o : collection) {
   removeField(key, o);
  }
 }
 
 

       
 

Wednesday, 19 April 2017

Spring Bean Injection without MVC and DispatcherServlet

Basically there is a difference between the type of context initialized for the spring container in terms of web application. If there is a scenario where you cannoto use the spring mvc architecture , there are 2 ways how you can inject the bean in different classes

1) Below Code Example
2) Use Springs AutoWiring mechanism in the servlet class.

1) Create a simple resttemplate bean in the applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">


    <!-- Application Context Init -->
    <beans:bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
      
    </beans:bean>
     


2) Load a spring bean file that is stored within your web inf  and set it to the serveltContext to make it application wide. May be you can invoke this within your application listener to invoke it only while deployment

String filePath = "D:\\workspace\\PROJECTX\\WebContent\\WEB-INF\\spring\\applicationContext.xml";
    ApplicationContext ctx = new FileSystemXmlApplicationContext(filePath);
    sce.getServletContext().setAttribute("ctx", ctx);

3) Use the bean in your method

        ApplicationContext ctx =  (ApplicationContext)  httpRequest.getSession().getServletContext().getAttribute("ctx");
        RestTemplate restTemplate = ctx.getBean(RestTemplate.class);
        ResponseEntity<String> response= restTemplate.getForEntity("https://callMyRestAPI/user",   String.class );


4) jars

Sunday, 16 April 2017

Maven Hot Deployment Plugin on Weblogic 12c

1) Install jar 
mvn install:install-file -DpomFile=oracle-maven-sync-12.2.1.pom -Dfile=oracle-maven-sync-12.2.1.jar
path:- D:\installs\fmw_12.2.1.1.0_wls_quick_Disk1_1of1\wls12210\oracle_common\plugins\maven\com\oracle\maven\oracle-maven-sync\12.2.1

2) Sync Local Repo - (Requires Internet)
mvn com.oracle.maven:oracle-maven-sync:push -DoracleHome=D:\installs\fmw_12.2.1.1.0_wls_quick_Disk1_1of1\wls12210\ -Doracle-maven-sync.testingOnly=false

3) Add Plugin to profile within pom.xml


<build>
        <plugins>
            <plugin>
        <groupId>com.oracle.weblogic</groupId>
        <artifactId>weblogic-maven-plugin</artifactId>
        <version>12.2.1-1-0</version>
        <configuration>
            <adminurl>t3://localhost:7001</adminurl>
            <user>weblogic</user>
            <password>admin123</password>
            <upload>true</upload>
            <!-- <targets>myServer</targets> -->
            <action>deploy</action>
            <remote>false</remote>
            <verbose>true</verbose>
            <source>D:\workspace\YOLO\target</source>
            <name>YOLO</name>
        </configuration>
        <executions>
            <execution>
                <phase>install</phase>
                <goals>
                    <goal>deploy</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
        </plugins>
    </build>


Article to follow :- https://ruleoftech.com/2014/using-the-weblogic-12c-maven-plug-in-for-deployment

Wednesday, 8 March 2017

Oauth2 Spring Security - In Memory (JWT Tokenstore ) and JDBCTokenStore - Oracle DB



SOURCE  : https://github.com/sanalsamuel/tuts

Oauth2 is the standard for protecting your resources , this  example we learn how to use the InMemory Store also the JDBCToken store to decline access easily for a particular resource.

Here we demonstrate to protect REST api using - Spring OAUTH2

SCHEMA REQUIRED : -



    CREATE TABLE "OAUTH_CLIENT_DETAILS"
  (    "CLIENT_ID" VARCHAR2(4000 BYTE),
   "RESOURCE_IDS" VARCHAR2(4000 BYTE),
   "CLIENT_SECRET" VARCHAR2(4000 BYTE),
   "SCOPE" VARCHAR2(4000 BYTE),
   "AUTHORIZED_GRANT_TYPES" VARCHAR2(4000 BYTE),
   "WEB_SERVER_REDIRECT_URI" VARCHAR2(4000 BYTE),
   "AUTHORITIES" VARCHAR2(4000 BYTE),
   "ACCESS_TOKEN_VALIDITY" NUMBER(*,0),
   "REFRESH_TOKEN_VALIDITY" NUMBER(*,0),
   "ADDITIONAL_INFORMATION" VARCHAR2(4000 BYTE),
   "AUTOAPPROVE" VARCHAR2(4000 BYTE),
    PRIMARY KEY ("CLIENT_ID"))

CREATE TABLE "OAUTH_ACCESS_TOKEN"
  (    "TOKEN_ID" VARCHAR2(255 BYTE),
   "TOKEN" BLOB,
   "AUTHENTICATION_ID" VARCHAR2(255 BYTE) NOT NULL ENABLE,
   "USER_NAME" VARCHAR2(255 BYTE),
   "CLIENT_ID" VARCHAR2(255 BYTE),
   "AUTHENTICATION" BLOB,
   "REFRESH_TOKEN" VARCHAR2(255 BYTE),
    CONSTRAINT "OAUTH_ACCESS_TOKEN_PK" PRIMARY KEY ("AUTHENTICATION_ID"))



Example insert

Insert into APIDEV.OAUTH_CLIENT_DETAILS (CLIENT_ID,RESOURCE_IDS,CLIENT_SECRET,SCOPE,AUTHORIZED_GRANT_TYPES,WEB_SERVER_REDIRECT_URI,AUTHORITIES,ACCESS_TOKEN_VALIDITY,REFRESH_TOKEN_VALIDITY,ADDITIONAL_INFORMATION,AUTOAPPROVE) values ('f728f3d76f7f4c88a9b0880504e9fe95','oauth2-resource','$2a$10$CiJhIo78K21cAsftlEBBFe24gwNY1fZCnEoiKALck3b0LkpkYwQ2G','trust','client_credentials','NA','ROLE_CLIENT',300,null,'{"ios":"1.0.2"}','trust');

U = f728f3d76f7f4c88a9b0880504e9fe95
P = 45408dce9b444cabb0c8d2b7b3c2b58f
hashed P = $2a$10$CiJhIo78K21cAsftlEBBFe24gwNY1fZCnEoiKALck3b0LkpkYwQ2G
U = b74dd71e48464efc997442de404b4670
P = 5ba9bb55594e4bdfb68d8f161ded110f

hashed P = $2a$10$x/hbo9LAkHLfD8mrTjQWguglg8zlusLcG591lVNdowSIL12bPQNAe



   


API :  http://localhost:7001/ssOauth/oauth/ 
Authorization : Basic - Username : Password
Grant Type :  client_credentials
Success Response : HTTP 200
Declined Client :-  HTTP 403

 



 

 


API :  http://localhost:7001/ssOauth/api/test
Authorization : Bearer TOKEN eg Bearer 116be482-d40e-48ba-a92a-dc3e012c77b8
Success Response : HTTP 200
Invalid Token : HTTP 401

AWS Certificate Manager - Import Certificate

How to import a certificate. Use Key Store Explorer to open the cert and export keypair in PEM format  This will save a file cert.pem. Make ...