Thursday, April 29, 2021

Avsc to Pojo generate with maven project

Avro schemas are defined using JSON and let see how we can generate POJO. Here I have used maven and we can play the same with gradle also. 



Maven Dependencies

The below dependencies need to add.


We can provide the source directory and output directory directly into maven. So that we can avoid some boilerplate code in java class.





After set upping this pom, now you can place your avsc file into the methined location the pom.xml. Once you place this execute the maven command which is mvn generate-sources. No the genearting from schema to pojo process will happen. After that we have play aroung our POJO like setting data etc.,. 

Now the project structure is below format. It may differ in eclipse. I am using intellij.



Dont create entity manually. It will be generated automatically. Now its time to write final code here.





Now just run the above program and get the below output. 



From the above output you can get all details. Thats it. Have fun...

Tuesday, April 30, 2019

angular proxy config json not redirected to spring

we may face this error, when we try to hit from angular UI to back end java(Spring etc.,). The problem is with angular proxy conf json file. 

The configuration (Sample )should be ,

{
  "/api": {
    "target": "http://url.com",
    "secure": false,
    "changeOrigin": true,
    "pathRewrite": {"^/api" : ""}
  }
}

Here, "changeOrigin": true, is not mandatory if you are running in local host. means, both Cline and server both are running in same machine. But if it is different host, then changeOrigin is must. However we should need this at final production. So better set now itself.

Monday, April 8, 2019

The default Activity not found

Error : The default activity not found.

Solution:

1. Are you sure , your main activity is declared in Manifest xml ? If not , please declare and run app. It will work. Make sure only main activity name you can change. Other like Intent filter, you shoul not touch.

2. If above solution is not workout, try Run -> Edit Config-> Choose your correct activity or define default activity.

3. If above also not workout like you defined everything well, but still error coming. Please do File -> Invalidate cache and restart.

4. If above also not work, this is the final solution File -> Sync with Gradle. Definitely It will work.


Tuesday, April 2, 2019

Must declare the scalar variable @Po ...

We may get this sql exception error when dealing with sql query. I also faced this and after a big analysis , found two causes.

1. We did DB migration - So your case check any migration (version changes) happened.

2. Second issue - Syntax issue like space , name mismatch, declaring is wrong.


Thursday, March 21, 2019

Creating an array of objects in Java



1. Declaration
 A[ ] arr = new A[4];


 2. Initializing the Objects 

 arr[0] = new A();
 arr[1] = new A();
 arr[2] = new A();
 arr[3] = new A();

 3. Initializing via loop

 for( int i=0; i<4; i++ )
 arr[i] = new A();
 
 
 
 By java 8
 A[] a = Stream.generate(() -> new A()).limit(4).toArray(A[]::new);

Wednesday, February 20, 2019

Could not find method versioncode () for arguments 1.1 on defaultconfig

This problem came, when I tried to upload an apk to playstore with version changes. Means, I launched my second version and got this error.

Solution:

Go to you build.gradle(app) and make changes like below. It will work.
minSdkVersion 15targetSdkVersion 26versionCode 2.0.toInteger() // This is what I changed
versionName "2.0"

Thursday, December 6, 2018

Class not found when running test case during gradle build

Problem:

I got the exception when I run the test case, which is using the generated WSDL source file, and got "Class not found exception" . Because my test case not able to find the genearted source code from WSDL.


Solution:

I added the below line gradle and its working fine.

sourceSets.test.java.srcDirs = ['.apt_generated/xxx,'src/test/java']



Monday, July 16, 2018

BeanExpressionContext' - maybe not public or not valid?

Property or field 'xxxxxxxxx' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?

The solution is just you should read value like below.

@Value("${your.prop.name}")
private List<String> userIdList;

I just removed # symbol from there and its working fine as expected.

Friday, May 11, 2018

Setter and Getter compatability

The below is another way of setting and getting property values and its really a very compatible mode.

Simple Example :


1
2
3
4
5
6
7
8
function User(name, age) {
  this.name = name;
  this.age = age;
}

let john = new User("Test", 25);

alert( john.age ); // 25

Explanation:

1. Line no 6 we are creating value for name and age property.  So the name and age will be assigned  (setter).

2. In line no 8, we are getting age value.

Getter and Setter with Javascript Property

Below is the code how JS code getter and setter should be,


1
2
3
4
5
6
7
8
9
let obj = {
  get propName() {
    // getter, the code executed on getting obj.propName
  },

  set propName(value) {
    // setter, the code executed on setting obj.propName = value
  }
};

Line no 2 and 6 get and set is keyword and propName is your property name to set and get value.

Example:


1
 2
 3
 4
 5
 6
 7
 8
 9
10
let user = {
  name: "FirstName",
  surname: "LastName",

  get fullName() {
    return `${this.name} ${this.surname}`;
  }
};

alert(user.fullName); // FirstName LastName

Explanation:

1. line no 1 user is an object which have name and surname property.

2. Through line no 10, when you call alert(user.fullName) control will be moved to line no 5 and it will be executed.

3. So line no 6 will return the result your user object property with the help of "this".

Example II:


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
let user = {
  name: "First",
  surname: "Second",

  get fullName() {
    return `${this.name} ${this.surname}`;
  },

  set fullName(value) {
    [this.name, this.surname] = value.split(" ");
  }
};

// set fullName is executed with the given value.
user.fullName = "Third Fourth";

alert(user.name); //Third
alert(user.surname);// Fourth





Solution for losing this - Function binding

Top avoid losing of this , we can wrapping a function.

Example :

Solution I:
1
 2
 3
 4
 5
 6
 7
 8
 9
10
let user = {
  firstName: "TestName",
  sayHi() {
    alert(`Hello, ${this.firstName}!`);
  }
};

setTimeout(function() {
  user.sayHi(); // Hello, TestName
}, 3000);

Now above code will work, since we have passed user.sayHi() as function (Outer lexical environment). So it will work like normal method call.

However, using arrow function (ES6) will short your code and solve this problem very easily without any confusing.

Example II: Arrow function :

Solution II:

1
2
3
4
5
6
7
8
let user = {
  firstName: "TestName",
  sayHi() {
    alert(`Hello, ${this.firstName}!`);
  }
};

setTimeout(() => user.sayHi(), 3000);


Example III:

Solution III:
Using bind built in method

Before proceeding we must know its syntax.

let boundFunc = func.bind(context);


Below is the example code and its explanation is below. Now you can understand better.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
let user = {
  firstName: "TestName"
};

function func() {
  alert(this.firstName);
}

let funcUser = func.bind(user);
funcUser(); // TestName

From the above example, func method bind was done and assigned to funcUser. So calling the funcUser will provide the correct result. Means, this bind with user object.

Example IV:

Binding with Object method:



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let user = {
  firstName: "TestName",
  sayHi() {
    alert(`Hello, ${this.firstName}`);
  }
};

let sayHi = user.sayHi.bind(user); // (*)

sayHi(); // Hello, TestName

setTimeout(sayHi, 1000); // Hello, TestName






Losing this - Function binding


Actually, this is an old concept only because If you are using ES6 and you don not worry about this. To know more about function binding , check below.

Example Scenario :

Just assume that, you are using setTimeout with object methods or you are trying to passing object methods, then you will loss "this" power.

Means, using this.xxxxx something will give you the result as undefined.

Example code for losing "this":


1
2
3
4
5
6
7
8
let user = {
  firstName: "TestName",
  sayHi() {
    alert(`Hello, ${this.firstName}!`);
  }
};

setTimeout(user.sayHi, 3000); // Hello, undefined!

Explanation:

1. We have set 3 seconds for setTimeout function at line no 8.

2. Now sayHi method will be executed and it try to print firstName with the help of this.firstName.

3. As "this" was lost , it will print undefined.






Wednesday, May 9, 2018

Difference between Call and Apply


1. The call method always expect comma separated parameters.

2. The apply method always expect array of arguments.

3. However, call and apply both expecting object as first parameter.

Note:

In ES6, we know spread operator ... and you can pass an array (or any iterable) as a list of arguments.

So using this spread with call, almost you are achieving apply concept.


1
2
3
4
let args = [1, 2, 3];

func.call(context, ...args); // pass an array as list with spread operator
func.apply(context, args);

From the above code you can find some minor difference, let see what is that

1. The spread operator ... is iterable args.

2. The apply accepts only array-like args.

So an iterate is possible with call and it works.  Whereas we expect an array-like, apply works.

Generally apply will be faster because of its single operation.

func.apply

Already we saw about call and its expecting comma separated parameters. But in apply we should pass array arguments.

A simple example,


1
2
3
4
5
6
7
8
9
function say(time, phrase) {
  alert(`[${time}] ${this.name}: ${phrase}`);
}

let user = { name: "John" };

let arrayData = ['10:00', 'Hello'];

say.apply(user, arrayData); 

Explanation :

1. We are using apply at line no 9. Here user is our context and arrayData is array arguments for this apply.

2. In the arrayData 10:00 will be considered as time and phrase will be considered as Hello.

3. After executing lie no 9 control moves to line 1 to execute a method say and will print the output.


func.call

Its a built-in function method func.call(context, …args) that allows to call a function explicitly by setting this.

The syntax is


func.call(context, arg1, arg2, ...)

A simple example is below,


1
2
3
4
5
6
7
function say(phrase) {
  alert(this.name + ': ' + phrase);
}

let user = { name: "JavaScript" };

say.call( user, "Hello" ); // Javascript: Hello

Explanation :

1. In line no 7, we have used user as our context and Hello as our argument.

2. You can pass multiple parameters like arg1, arg2 etc.,

3. After executing line no 7, control will move to line no 1 and say method will be executed.


Things to Remember :

Generally, most of the people will get ambiguous for call and apply. To remember this, use mnemonic is "A for array(apply) and C for comma (call).







Monday, April 30, 2018

setInterval

It runs the function regularly after the given interval of time. Suppose, If you want to stop the actions you should call clearInterval(timerId).

The setInterval method syntax is same as setTimeout.

Syntax:


let timerId = setInterval(func|code, delay[, arg1, arg2...])

Example:



let timerId = setInterval(() => alert('I will run every 3 seconds continuously'), 3000);

The above alert will show up every 3 seconds once.

setInterval with clearInterval

Example:

1
2
3
4
let timerId = setInterval(() => alert('Test'), 2000);

// after 5 seconds stop the interval
setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000);

Explanation:
       
                1. Line number 1 will be run continuously for every 2 seconds.

                2. But line number 5 will clear the interval time after 5 seconds. So after 5 seconds alert 
                    "Test" will not shown.





setTimeout with clearTimeout

We can use “timer identifier” which will be returned by setTimeout and the same we can use to cancel the execution.

Syntax:



let timerId = setTimeout(...);
clearTimeout(timerId);

Example:



1
2
3
let myVar = setTimeout(function(){ alert("Hello"); }, 3000);

let xxx = clearTimeout(myVar);

Explanation:

1. Line number 1 will be executed initially

2. To display the alert Hello message 3 seconds need to be waited.

3. But line number 3 will be executed before three seconds. So alert message will not be displayed here.

setTimeout


For executing some methods based on some times, then we should go ahead with setTimeout and  setInterval.

setTimeout allows to run a function once after the interval of time.


The syntax:



let timerId = setTimeout(func|code, delay[, arg1, arg2...])


func|code -  Function or a string of code to execute. Mostly, this will be a function. But some peoples may pass a string of code and its not recommended. The reason I have mentioned in Javascript interview section.

delay -  The delay before run, should be mentioned in milliseconds (1000 ms = 1 second).

arg1, arg2…  - arguments.

Simple Example:



1
2
3
4
5
function sayHi(welcomeMsg, user) {
  alert( welcomeMsg + ', ' + user );
}

setTimeout(sayHi, 5000, "Hello", "Raj"); // Hello, Raj

Explanation:

The sayHi method will be called after 5 seconds. Just compare this example with syntax. Hope you got it.

Note:

Do not pass like sayHi(). You should pass always method name only like sayHi without brackets.





Friday, April 27, 2018

Named Function Expression - NFE

Named Function Expression (NFE)  - We are giving a name to Function Expressions.

Before going into NFE, we should understand what is Ordinary Function Expression. Below is example,


let sayTest = function(one) {
  alert(one);
};

Now just add a name to that, (NFE).


let sayTest = function yourName(one) {
  alert(one);
};

It looks like very simple. But everything is designed for some reason. Let check why we are giving name like this?


1. It allows the function to reference itself internally.

2. It will not be visible to outside of the function.


let sayTest = function yourName(one) {
  if (one) {
    alert(one);
  } else {
    yourName("Guest"); // use yourName to re-call itself
  }
};

sayTest(); // Guest

// Error here
yourName(); // Error Here - not visible outside of the function


Come to our final main concept. Why we want this NFE. See below example,


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let sayHi = function yourName(one) {
  if (one) {
    alert(`Hello, ${one}`);
  } else {
    yourName("Guest");  // Because of this line, this code working
    //sayHi ("Guest"); // This will not work.
  }
};

let welcome = sayHi;
sayHi = null;

welcome(); // nested call works here perfectly

Explanation :

1. Here line number 1, yourName is your NFE. 

2. You have used this name inside line number 5.

3. Suppose if you change the line number 5 to like sayHi("Guest"), will throw an error. Why ?

4. Because line number 10, sayHi was assigned to null. So this will be reflected to line number 9 too. So error will be thrown. (There is no sayHi function).

5. To solve that, we should add NFE , Because internal call possible in NFE.





Function Object with Custom Properties

We can add our own custom properties with function object.

Below example will explain you How do we use custom property with function object.


function countTest() {
  alert("Hi");

  countTest.counter++;
}
countTest.counter = 0; // initial value

countTest(); // Hi
countTest(); // Hi

alert( `Called ${countTest.counter} times` ); // Called 2 times

Explanation :

We are calling countTest function at two times. So while calling at every time counter (custom property) will be executed and returning 2 in alert.