Saturday, 13 October 2018

Maven Profiles [UAT,PROD] Based Property Value Population in Deployable

1) Make sure you have the maven war compiler plugin.
2) Add the profile based on your environment.
3) Create a property folder on the resource path
4) Add a place holder in the property file. service.url=${service.url}
5) Run the Maven Command with the Profile clean install -PUAT
6) Verify in built WAR in WEB-INF/Classes

XML Changes to Pom.xml:-

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <webResources >
                        <webResource>
                            <directory>src/main/webapp/WEB-INF</directory>
                            <filtering>true</filtering>
                            <includes>
                                <include>*.properties</include>
                            </includes>
                        </webResource>
                    </webResources>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

        </plugins>
    </build>

<profiles>
<profile>
<id>UAT</id>
<properties>
<service.url>sanalsamuel</service.url>
</properties>
</profile>
</profiles> 

Sunday, 23 September 2018

JWT Json Web Token Claims - Token Creation and Parsing Example : using jjwt-0.2.jar

Basic - Json Webtoken Example




       

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.TextCodec;

public class JwtTokenUtil {

 public static void main(String[] args) throws UnsupportedEncodingException {

  System.out.println(createAccessJwtToken());

 }

 public static String createAccessJwtToken() throws UnsupportedEncodingException {

  Claims claims = Jwts.claims().setSubject("sanal");
  claims.put("role", "admin,super");
  claims.put("registered", 1);
  claims.put("firstName", "sanal");
  claims.put("lastName", "samuel");

  LocalDateTime currentTime = LocalDateTime.now();

  String token = Jwts.builder().setClaims(claims).setIssuer("OFV")
    .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant()))
    .signWith(SignatureAlgorithm.HS512,
      TextCodec.BASE64.decode("Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E="))
    .compact();

  parser(token);

  return token;
 }

 public static void parser(String jwt) throws UnsupportedEncodingException {
  Jws jws = Jwts.parser()
    .setSigningKey(TextCodec.BASE64.decode("Yn2kjibddFAWtnPJ2AFlL8WXmohJMCvigQggaEypa5E="))
    .parseClaimsJws(jwt);
  System.out.println(jws.getBody());

  Claims claims = jws.getBody();
  System.out.println(claims.getSubject());

 }

}


       
 

Rest Endpoint Invocation over SSL (HTTPS) - Using Spring RestTemplate , Certificate Keystore , SSLContext , SocketFactory JKS


Main Class to achieve rest invocation to any url over HTTPS.
Pre requisite:- Make sure the certificate is imported into new JKS keystore.
The certificate should be added to cacert of your JDK .
       

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author Sanal 
Invoking a Rest Endpoint over SSL
 */
public class RestInvoker {

 // resttemplate has its own encoding mechanism - so do not try encoded urls
 static String restURL = "https://google.com";

 public static void main(String[] args)

 {

  try {
   System.out.println("Invoking Rest Client");

   HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

   SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(SSLFactory.getSSLContext());
   CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
   requestFactory.setHttpClient(httpClient);
   RestTemplate restTemplate = new RestTemplate();

   restTemplate.setRequestFactory(requestFactory);

   System.out.println("INVOKING " + restURL);

   ResponseEntity response = restTemplate.getForEntity(restURL, String.class);
   System.out.println("Response Status Code  " + response.getStatusCodeValue());
   System.out.println("Response Body  " + response.getBody());
  } catch (Exception e) {
   System.out.println("Rest Invocation failed " + e.getStackTrace());
  }

 }

 /*
  * Static Class that will invoke the SSLContext with the appropriate Certs
  * used for the HttpClient Request
  */

 public static class SSLFactory {

  private static String jksFilePath = "C:/Users/Desktop/certs.jks";
  private static String jksPwd = "password";
  private static KeyStore ks;
  private static SSLContext sslContext;

  public SSLFactory() {

   System.out.println("Get a Socket Factory Loaded with Custom certs");

  }

  public static SSLContext getSSLContext() {
   try {

    sslContext = SSLContexts.custom().loadKeyMaterial(loadKeyStore(), jksPwd.toCharArray()).build();
   } catch (Exception e) {
    System.out.println(" KeyStore getSSLContext Exception" + e.getStackTrace());
   }
   return sslContext;

  }

  public static KeyStore loadKeyStore() {
   try (InputStream in = new FileInputStream(new File(jksFilePath))) {
    ks = KeyStore.getInstance(KeyStore.getDefaultType());
    System.out.println("KEYSTORE INIT");

    ks.load(in, jksPwd.toCharArray());

   } catch (Exception e) {
    System.out.println(" Loading KeyStore Exception" + e.getStackTrace());
   }
   return ks;

  }

 }

}


       
 

Wednesday, 15 August 2018

Webhook - Rest EndPoint to Spring Kafka Topic

Use case is to expose a Rest API for execution of  any logic and trigger backend  systems for n number of transaction , invocation or transactions.

Technology Stack : JEE, Spring Boot , Spring - Kafka Template.


1) Start the Kafka and Zoo Keeper Server. (This is required specially for component connection from spring kafka)

2) Run the Spring Boot Micro Service it will connect to the kafka topics, etc on startup.

3) Rest Endpoint will be exposed as a API resource which takes  a Json Object which can be categorized and developed based on the requirement.

4) Once the rest endpoint message is sent , the exposed api uses the already connected Topic and  directly drops the message in the kafka topic.

5) @KafkaListener can be used to read these messages dropped to the topic. These can now be used to invoke or trigger any actions required based on the business use case.


Source link on git  : - https://github.com/sanalsamuel/WebhookToKafka

Angular 4 CLI - NodeJs , NPM

IDE - Atom - need to try webstorm

Angular CLI

1) Download and install Node Server , it installs npm for you.

2) NPM and Node version check.

3) npm install -g @angular/Cli

4) Create your App with the command.  (Creates the Entire Structure )
     ng new MyApp

5)  ng serve

APP is now running on http://localhost:4200/

Next Items :- Components and Routers -- Coming Soon

6) Create a build :- ng build --prod  - creates a build folder called dist - this can be used for future deployment process

Tuesday, 7 August 2018

Oracle Queries for Java Developers



1) Connection count for all users 

select sum(case when status = 'ACTIVE' then 1 else 0 end) as ACTIVE_COUNT
     , sum(case when status = 'INACTIVE' then 1 else 0 end) as INACTIVE_COUNT
     , count(*) as TOTAL_COUNT
     , username, machine
from   v$session
where type <> 'BACKGROUND'
group by username, machine
order by username, machine



2) Session and Process count 

  select resource_name, current_utilization, max_utilization, limit_value
   from v$resource_limit
   where resource_name in ('sessions', 'processes');

3) Alter Session and Process Value

alter system set processes=500 scope=spfile;

alter system set sessions=1248 scope=spfile;

4) How to make changes in oracle DB 

Connect to SQL+ common prompt  

1) Command: connect sys as sysdba

you will be asked for password , now your logged in to the system shows prompt connected.

2) Grant privileges to user 

grant sysdba to system;   (system is the user)


3)   Alter user password or change password 
Alter user sys identified by new_password;   (sys is user and new_password is the password value)

4) Unlock a user account 
 Alter user system account unlock;    

5). Revoke rights from a user 
Revoke sysdba from system;

Tuesday, 26 June 2018

APK - Manifest Data Retrieval in Java using APK parser

1) Pom Dependency
<dependency>
    <groupId>net.dongliu</groupId>
    <artifactId>apk-parser</artifactId>
    <version>2.6.1</version>
</dependency>

Main Application

import java.io.File;
import java.io.IOException;

import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.ApkParser;

public class APKParser {
public static void main(String[] args) throws IOException {
// File Path from Mac 
ApkFile apk = new ApkFile(new File("/Users/sanal/desktop/myapk.apk"));
System.out.println(apk.getApkMeta());
}


}

Sample output

packageName: com.dreamz
label: My App
icon: imagepath/image
versionName: 1.0.0
versionCode: 1
minSdkVersion: 21
targetSdkVersion: 25

maxSdkVersion: null

Tuesday, 19 June 2018

Etag Implementation for Web Api - Caching


Below the details to use the ETag feature from API - Backend Implementation.

Example :- 
1) Request 1 Login and request a getSomethingService  call . you
    will recieve an Etag with value in the response header .

2) Copy the response header for the next request

3) Request 2 add "If-None-Match" request header attribute to service
    request and put the saved value from request 1
                
4) if the response is same , you would get a 304 not

    modified response code.




Thursday, 7 June 2018

SSL - Keytool commands for JDK certificate cacert

Add single Certificate to local JDK on linux servers
keytool -import -trustcacerts -keystore /filepath/java/jre/lib/security/cacerts -storepass changeit -noprompt -alias aliasName -file /certificateFilePath/certifcate.cer

Add a single cert on windows
keytool -importcert -trustcacerts -storepass changeit -noprompt -alias aliasName -file C:\Users\u6071754\Desktop\ofv_cert.cer


Add keystore
keytool -importkeystore -trustcacerts -keystore /filepath/java/jre/lib/security/cacerts -storepass changeit -noprompt -alias aliasName -srckeystore /keyStorePath/KeyStore.jks

Delete Certificate
keytool -delete -v -keystore /filepath/java/jre/lib/security/cacerts -alias aliasName

List All Certificates
keytool -list -v -keystore /filepath/java/jre/lib/security/cacerts > cert.txt 

Cacert pwd is changeit


Command for importing Certificates to Keystore UNIX/Windows:-

Installing Certificate:-
<java installation directory>/bin/keytool -import -noprompt -trustcacerts -alias certificate –file certificate.cer -keystore DemoIdentity.jks -storepass DemoIdentityKeyStorePassPhrase


Viewing Certificates within Keystore:-
<java installation directory>/bin/keytool -list –v -keystore cacerts -storepass changeit

Deleting Certificate
keytool -delete -alias "mykey" -keystore ..\lib\security\cacerts

Locate the keytool from the java installation bin folder.
-alias :- Name with which the certificate is saved to the keystore
-storepass :- password for the keystore to which the new certificate is added.

The default java keystore is the cacerts file located under
<Java installation folder>/jre/lib/security/cacerts
Default password for the cacerts file is ”changeit”.

For Weblogic the keystore files used is DemoIdentity Keystore.
Password for the keystore :- DemoIdentityKeyStorePassPhrase

Add the certificates to the above files, for applications that can directly use the default certificates (Webservices etc) ie, the internal implementation uses the default providers to fetch the certificates directly from the JVM.

For other applications, like LDAP, Webservices that require certificates to be added along with the Request Body etc, Code level implementation has to be done. 

Using Keystores in Java Application:-

Implementation using SSLSocket Factory:-

Create a keystore with the files provided (Using 3rdParty Tools like KeyStore Explorer etc).
Files provided may include the server, Intermediate and Root Certificate. Add all the files to a single keystore. 
Provide a password while creating the  Keystore and the file will have the .jks extension.

Provide the generated keystore to the SSLSocketFactroy.


Refer the below file for Implemetation of SSLSocketFactory to use the Keystore for an LDAP service. The SocketFactory is then set to the LDAP configuration during Authentication.

Thursday, 31 May 2018

org.bouncycastle.jcajce.provider.symmetric.IDEA$Mappings - signer information does not match signer information of other classes in the same package

This is possible issue when the multiple jars of bouncy castle are loaded within the server.

Steps to follow.

1) Make sure right correct and same version is used across multiple application deployments
2) Using the extension mechanism provided by Oracle :-
https://docs.oracle.com/javase/8/docs/technotes/guides/extensions/spec.html

Thursday, 29 March 2018

Best Practices for JEE Backend Development

1)    Application Design Structure and layered architecture.
a)    Build Management -  All configurations for Rest Services etc  , static values in  config files. Each dependency listed with version in lib folder , Profiles for each environment.
b)    Interceptor – API request validation - If the API request has some prequisite validation this needs to be handled here
       Example : Post Login Api Calls – Session Validator , Brute force Attack Prevention – Max Request Interceptor
c)    Request Model Validation - All data parameters of object should be validated at the Pojo Model level.
       Example : Login Request has user object, it should be validated for fields like username
       (validation for null , empty and may be pattern for regex) . This avoids large data being injected in requests. 
d)    Service Level should be generic
       Example :- All consuming REST services/ RMI call  should be through common gateway
e)    Data retrieval from third party service layer should be validated.
       Example :- Keys returned from rest service may be null or empty , such cases need to be handled and updated
       Example  :- Json response from service level is expected to have key “LOGGEDIN”, this has been missed  , such cases data should be validated and custom exception logged and handled gracefully.
f)     Timeouts & Connectivity Downtime Handling
        Rest Connection , Read , Socket Timeout to be addressed and tested.
        DB and other web service etc outbound connections should be tested for possible downtime and gracefully handle the failure.


2)     Code Quality

a)    Attribute and method naming should be clear and understood by any developer who is not the author of the code. (camelCase variable and method declarations)
       E.g. calculateGst(BigDecimal amount), BalanceLoader.java, etc.
       Bad: List list;
       Good: List<String> users;
b)    Methods need to be 15 lines max with exceptions handling within one try catch block  , each method  should do a specific function which is explained in its name.
       E.g. CustomerDao.java for data access logic only, Customer.javafor domain object, CustomerService.java for business logic,
       and CustomerValidator.java for validating input fields, etc.
       Similarly, separate functions like processSalary(String customerCode) will invoke other sub functions with meaningful names like
       evaluateBonus(String customerCode),
       evaluateLeaveLoading(String customerCode), etc
c)     Variable declaration for value retrieval from external method or service, in these scenarios if value if  is not being used to validate / business logic , no new variables should be declared and assigned.
d)    Logging is mandatory to easily track a request flow. Logging levels should be precise to understand the current state of the request flow.
e)    Using collections and library methods for String , Date utility Functionns.
f)     Exception Handling should be optimized.
g)    Creating new Instances of objects ,  Beans , static values assigning should be taken extreme precaution and should be tested locally handling multiple scenarios
h)    String comparison and Object Comparison, should be done effectively.
I)     AutoCloseable Interface implementing classes should use the enhanced try block for handling streams and and IO operations.
j)     Session variables usage should be limited for specific business logic only.
k)    Sonar Lint should be used while development on each class to check before and after changes on bugs.

3)     Checklist 

ChecklistDescription/example
Make a class final and the object immutable where possible.Immutable classes are inherently thread-safe and more secured. For example, the Java String class is immutable and declared as final.
Minimize the accessibility of the packages, classes and its members like methods and variables.E.g. private, protected, default, and public access modifiers.
Code to interface as opposed to implementation.Bad: ArrayList<String> names = new ArrayList<String>();

Good: List<String> names = new ArrayList<String>();
Use right data types.For example, use BigDecimal instead of floating point variables like float or double for monetary values. Use enums instead of int constants.
Avoid finalizers and properly override equals, hashCode, and toString methods.The equals and hashCode contract must be correctly implemented to prevent hard to debug defects.
Write fail-fast code by validating the input parameters.Apply design by contract.
Return an empty collection or throw an exception as opposed to returning a null. Also, be aware of the implicit autoboxing and unboxing gotchas. NullpointerException is one of the most common exceptions in Java.
Don’t log sensitive data.
 Security.
Clearly document security related information.
 Security.
Sanitize user inputs.
 Security.
Favor immutable objects.
 Security.
Use Prepared statements / Optimized ORM as opposed to ordinary statements.
 Security to prevent SQL injection attack.
Release resources (Streams, Connections, etc).
 Security to prevent denial of service attack (DoS) and resource leak issues.
Don’t let sensitive information like file paths, server names, host names, etc escape via exceptions.
Security and Exception Handling.
Follow proper security best practices like SSL (one-way, two-way, etc), encrypting sensitive data, authentication/authorization, etc.
Security.
Use exceptions as opposed to return null.
Exception Handling.
Don’t ignore or suppress exceptions. Standardize the use of checked and unchecked exceptions. Throw exceptions early and catch them late.
Exception Handling.
Write thread-safe code with proper synchronization and use of immutable objects. Also, document thread-safety.
Concurrency.
Keep synchronization section small and favor the use of the new concurrency libraries to prevent excessive synchronization.
Concurrency and Performance.
Reuse objects via flyweight design pattern.
Performance.
Presence of long lived objects like ThreaLocal and static variables holding references to lots of short lived objects.
Memory Leak and Performance
Favor using well proven frameworks and libraries as opposed to reinventing the wheel by writing your own.E.g. Apache commons libraries, Spring libraries, XML/JSON libraries, etc.
RISK Tests and Security Prevention Link


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 ...