Thursday, 17 June 2021

Git Commands used to work with other people's repositories

https://help.github.com/articles/fetching-a-remote/

git clone

git fetch

git merge

git pull

When you are working with other people's repositories:

you may use these commands

These commands are useful working with remote repositories.

git clone :
---------------
to grab a complete copy of a another user's repository - use git clone

$git clone https://www.github.com/USERNAME/REPOSITORY.git


git fetch:
--------------
Use git fetch to fetch the new work done by the other people.

Fetching from a repository grabs all the new remote-tracking (refs/remote/origin/foo referred to as a origin/foo) branches and tags without merging those changes into  your branches.

 git merge:
-----------------

merge combines your local changes with changes made by others.

Typically , you would merge a remote-tracking branch with your local branch

git pull:
--------------
It is a shortcut for both git fetch and git merge in same command

because pull performs a merge on the retrieved changes, you should ensure your local work is commited before running the pull command.

If you run into a merge conflict if you cannot resolve, or if you decide to quit the merge, use git merge --abort to take the branch where it was before you pulled.







Thursday, 10 June 2021

How to print the date in specific format in java?

You can format the dates in java using SimpleDateFormat class from java.text pacakge.

Create an object of SimpleDateFormat - provide the pattern to constructor.
Note: Pattern will have date specific literals.

String pattern = "yy-MM-dd";

SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);

For example: 

package com.algos;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormat {
public static void main(String[] args) {
String pattern = "dd-MM-yy";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
System.out.println(dateFormat.format(new Date()));
}
}

How to reverse the words in a sentence in java ?

Two ways:

> using new StringBuilder().append method
> using apache commons dependence - StringUtils.reverseDelimited(sentence, ' ')
Example:
package com.algos;

public class ReverseSentence {
public static void main(String[] args) {
String sentence = "I am in love with her";
System.out.println("Reverse of a sentence: "
                        + reverseSentence(sentence));
System.out.println(sentence.length() == reverseSentence(sentence).length());
        //2nd way
//By using apache-commons:commons-lang3 dependency
//StringUtils.reverseDelimited(str)
}

private static String reverseSentence(String sentence) {
if (sentence == null) return null;
String[] words = sentence.split(" ");
StringBuilder output = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
output.append(words[i]);
output.append(" ");
}
return output.toString().trim();
}
}

How to reverse the String in java ?

You can use some mutable string related classes like StringBuilder / StringBuffer classes for reversing the string.

> You can use reverse() method of StringBuilder : 
new StringBuilder().reverse for doing this.
> You can also use apache commons dependence - 
& use StringUtils.reverse(String str)
Example:
package com.algos;

public class ReverseString {
public static void main(String[] args) {
String str = "Hello World";
System.out.println("1st Way : Reverse of given string : "
                + reverseStr(str));
        System.out.println("2nd Way : Reverse of given string : " 
                + reverseStr2(str));
//Using 3rd way
//By using apache-commons:commons-lang3
//StringUtils.reverse(str)
}

private static String reverseStr2(String str) {
if (str == null) {
return null;
}
StringBuilder builder = new StringBuilder(str).reverse();
return builder.toString();
}

private static String reverseStr(String str) {
if (str == null) {
return null;
}
char[] in = str.toCharArray();
StringBuilder builder = new StringBuilder();
for (int i = in.length - 1; i >= 0; i--) {
builder.append(in[i]);
}
return builder.toString();
}
}

How to find the missing number from a given array (when only one number is missing from a sequence of non-zero numbers)?

Assumptions :

The array may have only one number missing in the sequence of numbers
with out zero in it.
Example:
int[] arr= {1, 3};
The missing number is 2 (where numbers are from 1 to 3)
Algorithm:
> Calculate the array size, using array size - calculate the sum of n numbers 
(n: array size + 1)
> Traverse the array elements using a for loop - calculate the moving sum
> then after that, diff of number of n numbers - moving sum of elements will 
give the missing number
Example:
package com.algos;

public class OnlyMissingNumberInArray {

public static void main(String[] args) {
int[] arr= {1, 3};
//The missing number from 1 to 3 is 2
System.out.println("The missing number "+ findMissingNumber(arr));
}

private static int findMissingNumber(int[] arr) {
//Calculate sum of numbers from 1 to 3 using n(n+1)/2
int n = arr.length + 1;
int sumOf = n * (n + 1)/2;
int sum = 0;
for(int i : arr) {
sum = sum + i; //moving sum
}
return sumOf - sum; //missing number 2
}
}

Thursday, 3 June 2021

Gradle Build : Project API Inbuilt properties

 One can use these properties given by gradle project api, within build.gradle file.

------------------------------Start of the File--------------------------

build.gradle

//project api properties
logger.info("Name of the project: ${project.name}")
logger.info(
"absolute path of the project: ${project.path}")
logger.info(
"description for the project: ${project.description}")
logger.info(
"directory containing the build script: ${project.projectDir}")
logger.info(
"build directory: ${project.buildDir}")
logger.info(
"${project.group}")
logger.info(
"${project.version}")

//The above properties - print same as below
//project api properties without project. prefix - implied by default
logger.info("Name of the project: ${name}")
logger.info("absolute path of the project: ${path}")
logger.info("description for the project: ${description}")
logger.info("directory containing the build script: ${projectDir}")
logger.info("build directory: ${buildDir}")
logger.info("${group}")
logger.info("${version}")
------------------------------End of the File--------------------------
Execution:
gradle -i build

-i for enabling logging for info level.
Output:
Name of the project: gradle-demo
absolute path of the project: :
description for the project: null
directory containing the build script: /Users/dinesh/IdeaProjects/gradle-demo
build directory: /Users/dinesh/IdeaProjects/gradle-demo/build

unspecified
Name of the project: gradle-demo
absolute path of the project: :
description for the project: null
directory containing the build script: /Users/dinesh/IdeaProjects/gradle-demo
build directory: /Users/dinesh/IdeaProjects/gradle-demo/build

unspecified

Gradle Logging Options: How to use logger in gradle build files?

 By default, there are no logs printed, because logging is disabled by default.

OptionOutputs Log Levels

no logging options

LIFECYCLE and higher

-q or --quiet

QUIET and higher

-w or --warn

WARN and higher

-i or --info

INFO and higher

-d or --debug

DEBUG and higher (that is, all log messages)


Note: reference official docs

Tuesday, 18 May 2021

What is Feign Web Service Client ?

Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it.

The following dependency is expected to add Feign in the project:

Dependency:

group id: org.springframework.cloud

artefact id: spring-cloud-starter-openfeign

Annotations:

@EnableFeignClients    - to enable the Feign Client

Sample Feign Client:

@FeignClient(name = "products", url="${productsUrl}")

public interface ProductClient {

        @RequestMapping(method=RequestMethod.GET,  value ="/products")

        List<Product> getProducts();

        @RequestMapping(method= RequestMethod.POST,  

        value ="/products/{productId}", consumes = "application/json")

        Product update(@PathVariable("productId") Long productId);

}


string value "products" within @FeignClient annotation is the arbitrary client which might be used in Ribbon (load balancing) support.

Note:

> you can also specify url attribute (absolute value or just a hostname).

> you can use qualifier attribute for giving an alias value for the bean name, if not given the name of bean in the application context is the fully qualified name of the interface.

---------------------------

Note: Each feign client is part of an ensemble of components that work together to contact a remote server, and the ensemble has a name that is given in name attribute of @FeignClient annotation.

Spring Cloud creates a new ensemble as an ApplicationContext on demand for each named client using FeignClientsConfiguration. This contains other things feign.Decorder, a feign.Encoder, and a feign.Contract.

You can control the feign client by declaring additional configuration using configuration attribute.


@FeignClient(name = "products", configuration= FooConfiguration.class)

public interface ProductClient {

    //..

}

Note: FooConfiguration does not need to be annotated with @Configuration. However, if it, then take care to exclude it from any @ComponentScan that would otherwise include this configuration as it become the default source for feign.Decoder, feign.Encoder, feign.Contract.

OTHER EXTRA INFO:

Spring Cloud Netflix provides the following beans by default:

> Decoder feignDecoder: ResponseEntityDecoder (which wraps a SpringDecorder)

> Encoder feignEncoder: SpringEncoder

> Logger feignLogger: Slf4jLogger

> Contract feignContract: SpringMvcContract

> Feign.Builder feignBuilder HystrixFeign.Builder

> Client feignClient: if Ribbon is enabled it is a LoadBalancerFeignClient, otherwise the feign client is used.

Not only by using a separate Configuration class, you can configure the @FeignClient using application props.

Example: 

feign:

    client: 

        config:

            <feignName>:

                connectTimeout: 5000

                readTimeout:    5000

                loggerLevel: full

                errorDecoder: com.example.SimpleErrorDecoder

                retryer: com.example.SampleRetryer

                requestInterceptors:

                        - com.example.SampleRequestInterceptor

                        - com.sample.ExampleRequestInterceptor

                decode404: false

                encoder: com.example.SampleEncoder

                decoder: com.example.SampleDecoder

                contract: com.example.SampleContract


The above props will apply to only named feign client. To apply to all feign clients, you can declare the props using default feign name:

Example:

  feign:

    client:

        config:

            default:

                connectTimeout:    5000

                readTimeout:    5000

                loggerLevel: basic

Now, this config props applies to all feign clients.

Note: If you create both Configuration class and Feign Config props in application yaml, configuration props will win.

You can change this behaviour by changing the prop:

   feign.client.default-to-properties to false.

Feign Logging:

A logger is created for each Feign Client created. 

By default the name of the logger is the full class name of the interface used to create the Feign client.

you can configure the log level per client 

e.g, 

logging.level.com.sample.ProductClient: DEBUG

com.sample.ProductClient - full class name

Logging Levels available are:

    NONE - No logging (default)

    BASIC - logs only 

        > request method    > URL    > response status > execution time

    HEADERS    - logs basic info along with req and response headers

    FULL - log the headers, body and metadata for both requests and responses.

Sunday, 11 April 2021

How to create aliases for git commands used frequently?

We can create aliases, shorter versions for git commands, using git config command.

git config --global alias.<shorter_name> <command>

If the command is having multiple words, then you single quotes

git config --global alias.<shorter_name>     '<command>    <attribute1> <attr2> .... '

Examples:

For checkout command use:

git config --global alias.co checkout

For commit command use:

git config --global alias.ct commit

For branch command use:

git config --global alias.br branch

For status command use:

git config --global alias.st status

For pull complete command (multiple words) use:

git config --global alias.plm 'pull origin master'


Note: you can check all the aliases & other config options using

git config --global --list

Output:

alias.co=checkout

alias.br=branch

alias.ct=commit

alias.st=status

alias.plm=pull origin master


Wednesday, 10 March 2021

How to use curl to GET query / search in elasticsearch?

You can use curl commands to search/query in elasticsearch just like in Kibana.

For example: 

you can get the count the number of documents in the cluster, you can use  GET _count endpoint.

Using curl:

curl -H "Content-Type: application/json" -XPOST 'http://localhost:9200/_count?pretty' -d '

{

"query" : {

"match_all" : {}

}

}'


Without the header, you might get 406 Not Acceptable exception like 

{

  "error" : "Content-Type header [application/x-www-form-urlencoded] is not supported",

  "status" : 406

}



Respective kibana command(short-hand):


GET _count

{

  "query": {

    "match_all": {}

  }

}


Monday, 8 March 2021

How to the check the elasticsearch cluster status using CURL command (whether it is UP & Running or not)?

 You can check the elasticsearch status by executing the following curl command: 

curl 'http://localhost:9200/?pretty'

generally, you must see the response something like the following text:


{

  "name" : "Dineshs.local",

  "cluster_name" : "elasticsearch",

  "cluster_uuid" : "cyHGu82bTNeWsmubNRblKA",

  "version" : {

    "number" : "7.9.3",

    "build_flavor" : "default",

    "build_type" : "tar",

    "build_hash" : "c4138e5121ef06a6404866cddc601906fe5c868",

    "build_date" : "2020-10-16T10:36:16.141335Z",

    "build_snapshot" : false,

    "lucene_version" : "8.6.2",

    "minimum_wire_compatibility_version" : "6.8.0",

    "minimum_index_compatibility_version" : "6.0.0-beta1"

  },

  "tagline" : "You Know, for Search"

}


This confirms that the Elasticsearch cluster is up and running

How to copy the files/directories into Kubernetes (K8S) Pods from local to remote pods (either ways)

Sometimes, we may get into situations where we need files from Kubernetes (K8S) pods to local file system & vice versa.

K8S has built-in commands for copying resources into & from K8S pods.

Case 1: To copy into local system from remote pods

kubectl cp <namespace_of_pod>/<pod_generated_name>:<source_copying_dir_path> <destination_local_dir_path>

kubectl cp catalog /catalog-app-es1xy2323sds:/appl/repositories     ~/

(here, I am copying the directory /appl/repositories from remote pod named catalog-app-es1xy2323sds (generated name) from Kubernetes cluster to local root path ~/ 

Case 2: To copy from local system to remote pods

kubectl cp <source_local_dir_path> <namespace_of_pod>/<pod_generated_name>:<destination_copying_dir_path> 

kubectl cp  ~/config  catalog /catalog-app-es1xy2323sds:/appl/repositories 

(here, I am copying the directory ~/config from local file system to remote pod named catalog-app-es1xy2323sds (generated name) in the namespace catalog)

you can search for all the namespaces using

kubectl get namespaces

you can search all the pods for a particular namespace using

kubectl get pods -n <namespace_name>

How to extract a TAR file in Linux / unix OS or on MAC

You can use tar command to extract, create, list, update, add/replace the files in the given .tar compressed file.

tar command provides the various options:

-t          List

-x         Extract

-c         Create

-r        Add/Replace


-v        Verbose

-f        <filename> Location of archieve


For Example, to list the contents/files in an given .tar file

tar -tf <.tar filename>            Lists all the files

tar -xvf <.tar filename>        Extracts all the files