Sunday, 14 November 2021

What is LocalDate in Java 8 ?

LocalDate class is an immutable & thread safe class. Its based on ISO-8601 calendar system.

It represents a date without any time components. Its date format often viewed in the form year-month-day {2021-11-14}.

Using this class, you can also access other data fields like :

    > day-of-year

    > day-of-week

    > week-of-year

Example:

public class LocalDateEx{

public static void main(String[] args) {
LocalDate date = LocalDate.of(2021, 4, 14);
System.out.println("Year of the given date "+ date.getYear());
System.out.println("Month of the given date "+ date.getMonth());
System.out.println("day of week of the given date "+ date.getDayOfWeek());
System.out.println("day of month of the given date "+ date.getDayOfMonth());
System.out.println("day of year of the given date "+ date.getDayOfYear());
System.out.println("day of year of the given date "+ date.getDayOfYear());
System.out.println("month of year(1 to 12) of the given date "+
                                                                                             date.getMonthValue());
        System.out.println("is given date a leap year? "+ date.isLeapYear());
System.out.println(date);
}
}


Factorial of any number in Java 8 - using reduction

Reduction - will reduce a stream of values to a result by using an identity (may be an initial value) and a function that will be applied internally on that stream. This processing may not be sequentially, its parallel stream.

import java.util.stream.LongStream;


public class Factorial {
public static void main(String[] args) {
    System.out.println(facto(5));
}

public static int facto(int n){
return IntStream.rangeClosed(1, n)
.reduce(1, (int a, int b) -> a * b);
}
}
we can either use LongStream or IntStream. 
LongStream.rangeClosed(1, n) gives stream of values from 1 to n, 
n is included here.
if you want to exclude nth value, 
you can use
LongStream.range(1, n) gives stream of values from 1 to n-1.
reduce function will apply a function a*b with 1 as initial value
 (also known as identity)
Its the similar operation as the following code.
long result = identity;
* for (long element : this stream)
* result = accumulator.applyAsLong(result, element)
* return result;
But the above code performs the same operation in sequential manner, 
but the reduce will apply the function in parallel form.

Monday, 9 August 2021

Fizz Buzz Program in Java (a string representation of numbers from 1 to n)

Problem Statement:

/**
* Fizz Buzz program:
*
* Write a program that outputs the string representation of numbers from 1 to n
*
* But for multiples of three it should output "Fizz" instead of the number &
* for the multiples of five output "Buzz".
*
* For numbers which are multiples of both three and five output
* "FizzBuzz"
*
* For n = 6
*
* create an array of strings like
* [ "1"
* "2"
* "Fizz"
* "4"
* "Buzz"
* "Fizz"
* ]
*
* */
Accepted Program:
package com.algos;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FizzBuzz {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
List<String> fbList = new ArrayList<>();
getFizzBuzzStrArray(n, fbList);
for(String fb: fbList) {
System.out.println(fb);
}
}

private static void getFizzBuzzStrArray(int n, List<String> fbList) {
for(int i=1; i<=n; i++)
{
if (i % 3 == 0 && i % 5 == 0) {
fbList.add("FizzBuzz");
continue;
} else if (i % 3 == 0) {
fbList.add("Fizz");
continue;
} else if (i % 5 == 0) {
fbList.add("Buzz");
continue;
} else {
fbList.add(String.valueOf(i));
}
}
}
} 
Output For n=15:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Thursday, 24 June 2021

How to read your tweets, create a tweet & publish in Java using twitter4j-stream api ?

Firstly, you need to create an app in https://apps.twitter.com using a developer account in Twitter. During this process, if you are doing this for first time, you may need to sign up in this & then create an app. 

To further explain this, actually Twitter provides OAuth credentials to this app, using those OAuth credentials, your app can successfully login to tied up Twitter account, then it can post, read & any other such Twitter operations can be done by app on behalf of the actual Twitter account. It works like, your app acts as client app with Twitter as OAuth provider. Just like any other OAuth Client with a OAuth Provider. A typical OAuth flow.

After creating an app in above mentioned link, you need to set the permissions for your app - if you want only read the tweets - A read-only permission would be enough. Otherwise if you want to tweet (post a tweet) from you app, you need to give write permissions as well.

The same link apps.twitter.com  gives you these four important OAuth related information, which you will read & configure in you application (java application).

OAuth Consumer Key:  <Some alphanumeric key>

[Recognises you app as a consumer]

OAuth Consumer Secret:  <Some alphanumeric key>

[represents your app secret]

OAuth Access Token:  <Some alphanumeric key>

[Recognises Access Token - valid for some time - only - you can revoke this token & regenerate - whenever you like to]

OAuth Access Token Secret:  <Some alphanumeric key>

[Recognises Access Token Secret]

NOTE: Keep these credentials in secret configuration locations like VAULT.

Dependencies Required: twitter4j-stream

Gradle:

implementation group: 'org.twitter4j', name: 'twitter4j-stream', version: '4.0.7'
Add the above dependencies in your build.gradle (or if your are using maven, 
pls form the maven config as similar to the above groupid & artefact)
-----------------------------------------------------------------------------
package com.basic.twitter;

import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterDemo {
public static void main(String[] args) throws TwitterException {
Twitter twitter = getTwitterInstance();
readTweets(twitter);
String message
            = "I am writing this tweet from my Java IDE using twitter4j-stream";
sendTweet(twitter, message);
}

private static void sendTweet(Twitter twitter, String message)
               throws TwitterException {
Status status = twitter.updateStatus(message);
System.out.println(status.getRetweetCount()); //checking any retweet count
}


private static void readTweets(Twitter twitter) throws TwitterException {
ResponseList<Status> messages = twitter.getHomeTimeline();
messages.stream().map(m -> m.getText()).forEach(message -> {
System.out.println(message);
System.out.println("--------------------------------\n");
});
}

private static Twitter getTwitterInstance() {
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder
.setOAuthConsumerKey("<<Your OAuth Consumer Key>>")
.setOAuthConsumerSecret("<<Your OAuth Consumer Secret>>")
.setOAuthAccessToken("<<Your OAuth Access Token>>")
.setOAuthAccessTokenSecret("<<Your OAuth Token Secret>>");

TwitterFactory twitterFactory
                    = new TwitterFactory(configurationBuilder.build());
return twitterFactory.getInstance();
}
}

Tuesday, 22 June 2021

Usage of Kafka Clients: Write a kafka producer that write messages to a kafka topic

Lets say we have created a kafka topic using a command line :

kafka-topics.sh --bootstrap-server 127.0.0.1:9092 --topic twitter-topic --create 

--partitions 3      



Verify the Kafka topic details - by listing in the console:


kafka-topics.sh --bootstrap-server 127.0.0.1:9092 --topic twitter-topic --describe         


Topic: twitter-topic PartitionCount: 3 ReplicationFactor: 1 Configs: segment.bytes=1073741824

Topic: twitter-topic Partition: 0 Leader: 0 Replicas: 0 Isr: 0

Topic: twitter-topic Partition: 1 Leader: 0 Replicas: 0 Isr: 0

Topic: twitter-topic Partition: 2 Leader: 0 Replicas: 0 Isr: 0  



Now you have a kafka topic - Write a Kafka Producer using Kafka clients dependency:



Dependencies (if in gradle):


dependencies {
implementation group: 'org.apache.kafka', name: 'kafka-clients', version: '2.8.0'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
}

Write a Kafka producer in a normal java class inside main method:
----------------------------------------------------------------------
package com.basic.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class ProducerWithoutKeyDemo {
public static void main(String[] args) {
//Add REQUIRED properties - set up kafka config
Properties properties = new Properties();
//If you don't set the following properties
        //possible exception: org.apache.kafka.common.config.ConfigException
        //If don't not set: exception: No resolvable bootstrap urls given in bootstrap.servers
properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
//If don't not set: exception:
        //Missing required configuration "key.serializer" which has no default value.
properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                                                                            StringSerializer.class.getName());
//If don't not set: exception:
        //Missing required configuration "value.serializer" which has no default value.
properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                                                                            StringSerializer.class.getName());
        //create a kafka producer
KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
        //send data to kafka topic
        String message = "Hey man";
ProducerRecord<String, String> producerRecord
                    = new ProducerRecord<>("twitter-topic", message);
//send needs a ProducerRecord type - defined without a key.
//without key means - the messages can go to any partition in twitter-topic
producer.send(producerRecord);

//Very important note:
//If you don't flush - message will not go to topic
producer.flush();
//Instead of the above- you flush & close in one step by using .close() method
producer.close();
}
}
----------------------------------------------------------------------
You can test the producer by executing a console consumer on terminal:

kafka-console-consumer.sh --bootstrap-server 127.0.0.1:9092 --topic twitter-topic 

Leetcode Solved: Convert a Roman number to Integer

PRODLEM STATEMENT:

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.


Roman numerals are usually written largest to smallest from left to right.
However, the numeral for four is not IIII. 
Instead, the number four is written as IV. 
Because the one is before the five we subtract it making four. 
The same principle applies to the number nine, which is written as IX. 
There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.


Example 1:

Input: s = "III"
Output: 3
Example 2:

Input: s = "IV"
Output: 4
Example 3:

Input: s = "IX"
Output: 9
Example 4:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.


Constraints:

1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
----------------------------------------------------------------------
package com.algos;

import java.util.HashMap;
import java.util.Map;

public class RomanToInteger {

public static void main(String[] args) {
System.out.println(romanToInt("MDCCCLIX")); //XL L X V IV III = 112
}

public static int romanToInt(String s) {
char[] chars = s.toCharArray();
int iCount = 0;
int total = 0;
Map<String, Integer> charMap = new HashMap<>();
charMap.put("I", Integer.valueOf(1));
charMap.put("V", Integer.valueOf(5));
charMap.put("X", Integer.valueOf(10));
charMap.put("L", Integer.valueOf(50));
charMap.put("C", Integer.valueOf(100));
charMap.put("D", Integer.valueOf(500));
charMap.put("M", Integer.valueOf(1000));
char prev = '\0'; // (char) 0
for (int c = chars.length - 1; c >= 0; c--) {
if ('I' == chars[c]) {
iCount++;
if (iCount > 3) {
c--;
break;
} else {
if (prev == 'V' || prev == 'X') {
iCount = 0; //need to verify
total = total - 1;
} else {
total = total + charMap.get("I");
}
prev = chars[c];
if (iCount == 3) {
iCount = 0;
}
continue;
}
} else if ('V' == chars[c]) {
prev = chars[c];
total = total + charMap.get("V");
} else if ('X' == chars[c]) {
if(prev == 'L' || prev == 'C') {
total = total - 10;
} else {
total = total + charMap.get("X");
}
prev = chars[c];
} else if ('L' == chars[c]) {
prev = chars[c];
total = total + charMap.get("L");
} else if ('C' == chars[c]) {
if(prev == 'D' || prev == 'M') {
total = total - 100;
} else {
total = total + charMap.get("C");
}
prev = chars[c];
} else if ('D' == chars[c]) {
prev = chars[c];
total = total + charMap.get("D");
} else if ('M' == chars[c]) {
prev = chars[c];
total = total + charMap.get("M");
}
}
return total;
}
}

Friday, 18 June 2021

How to check whether a given number is Armstrong Number or not?

What is an Armstrong Number?

An Armstrong Number is a number, where the sum of cubes of each digit of that 
number is equal to the given number.
Example: 371 = 33 + 73 + 13
----------------------------------------------------------------------------------------------------------------------
package com.algos;

import java.util.Scanner;

public class ArmstrongNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(checkArmstrongNumber(n));
}

private static boolean checkArmstrongNumber(int n) {
int movingCubeTot = 0;
int temp = n;
while(temp > 0) {
int currDig = temp % 10;
temp = temp/10;
movingCubeTot = movingCubeTot + (currDig * currDig * currDig);
}
return n == movingCubeTot;
}
}

Thursday, 17 June 2021

Git Commands: used by a developer on daily basis

How to initialize a project or any folder to use the git?

Typically, developers use the git for better continuous integration (collaborative work among multiple team members). But, in general, any person who is novice to the computer knowledge can take the benefit of the git version control system. For example, a novel writer, can use the git.

git init

<in a project folder> will initialize the git & git for then, tracks your changes.


How to check the current status of git? 

git status

This command helps the user of the git to know what is the current status of the version control: like what files are changed, among those files which are being in untracked & in staging (ready to commit state).


How to check the logs of git?

git log 

git log --oneline

The above commands help you to show the recent commits to current project. Note: Every commit will have a SHA id(an alphanumeric id) & author info. Generally, we use to know what's the recent changes that have been added to a file / project. 


How to check the branch info?

Branching model in git is a model, where individual work piece assigned to a developer is developed on a different branch, sometimes called as feature branch. Generally, we name the branches with the work related terms. For example, if I am working on purchase order related work, I will create a new branch with a suitable name something like purchase-order branch or sometimes we create branches with JIRA story numbers (for example, on DCP project - branch : DCP-1234)

To the know what are the branches existing: we can use 

git branch

this command will show all the branches. Some branches will be both remote & local branches. This means, during the initial development of a piece of work, the branch may still exist as a local branch for that developer. Until this branch is been pushed, it will have only a local branch. Once a branch is pushed & it will be available in remote.

How to see the local & remote branches using terminal?

To see all the local & remote branches:

git branch -a 

To see the local branches:

git branch

To see the remote branches:

git branch -r


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