Categories
Angular

ng if else condition in angular with example

In this post, we will learn about ng if else condition in angular with example

NgIf the directive will be used to display DOM based on a condition. It is very useful to show or hide a HTML div

Sample Code
<div ngIf="show">
    <p>This is can be show</p>
</div>
import { Component, OnInit } from '@angular/core';
import { StudentService } from '../../service/student.service';
import { Student } from '../../model/student.model';

@Component({

  selector: 'app-student-details',
  templateUrl: './student-details.component.html',
  styleUrls: ['./student-details.component.css']
})
export class StudentDetailsComponent implements OnInit {

  constructor() { }

  show: boolean;

  ngOnInit(): void {   
    this.show=true;
  }

}

In the above example, we declared a boolean variable called as show. We are changing that boolean value to true on ngOnInit method

In the html file we are using that show boolean variable to display the paragraph tag

if the show boolean is false then the html div will not display

ngIf else Example

We need to define the else block inside a ng-template block. below is the example for ng if else condition

<div ngIf="show; else notshowing">
    <p>This is can be show</p>
</div>

<ng-template #notshowing>
    <p>This will be shown on else statment</p>
</ng-template>
Conclusion

In the above post, we learned about ngIf else condition in angular with example

Related Articles

http post request from angular with example

Categories
Angular

http post request from angular with example

In this post, we will learn to make http post request from angular with example

To communicate with backend server we are using HttpClient from @angular/common/http

Syntax
this.http.post<return-type>(url: string, body: any, options?);

In this example we are going to save a student details. To do that we need to invoke a http post method with student details

{  
  "firstname": "string", 
  "lastname": "string"
  "department": "string",
}

Now I am creating a model class for above json request like below

export class Student {    
    firstname: string;    
    lastname: string;
    department: string;
}

Now we need to create service class to make http post request from angular
creating service layer command:  ng g s student

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class StudentService {

  constructor() { }
  
}

Now we can create saveStudent method to save the student details in back end

 /**
   * In this method we are calling http post method 
   * @param student 
   */
  saveStudentDetails(student: Student): Observable<any>{
    return this.http.post<any>('http://localhost:8080/api/student',student);
  }
Student Service layer
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Student } from '../model/student.model';
@Injectable({
  providedIn: 'root'
})
export class StudentService {

  constructor(private http: HttpClient) { }


  /**
   * In this method we are calling http post method 
   * @param student 
   */
  saveStudentDetails(student: Student): Observable<any>{
    return this.http.post<any>('http://localhost:8080/api/student',student);
  }
  
}

Now we can call this service class method from component, For example I am creating a simple form and component as like below

import { Component, OnInit } from '@angular/core';
import { StudentService } from '../../service/student.service';
import { Student } from '../../model/student.model';

@Component({

  selector: 'app-student-details',
  templateUrl: './student-details.component.html',
  styleUrls: ['./student-details.component.css']
})
export class StudentDetailsComponent implements OnInit {

  constructor(private studentService: StudentService) { }

  student: Student=null;

  ngOnInit(): void {   

  }

  saveStudent(){
    //Creating model class
    this.student.firstname="Beginners";
    this.student.lastname="Bug";
    this.student.department="Blooggin";
    
    //Call service layer from component 
    this.studentService.saveStudentDetails(this.student).subscribe(data=>{
      console.log("Student Added successfully");
    
    },error=>{
      console.log("There was some error ",error);
    });

  }

}
<form (ngSubmit)="saveStudent()">
<label>FirstName:</label> <br/><input type="text" name="firstname" placeholder="Enter First name"><br/>
<label>LastName:</label> <br/><input type="text" name="lastname" placeholder="Enter Last name"><br/>
<label>Department:</label> <br/><input type="text" name="department" placeholder="Enter Department"><br/><br/>
<button class="button" type="submit">Add</button>

</form>
Conclusion

We learned to make http post request from angular with example

Related Articles

call http rest service from angular

Categories
Angular

call http rest service from angular

In this tutorial, we will learn to call http rest service from angular

To understand this tutorial we should know the angular basics like components, service

Before starting we should have a component & service knowledge, Here we are going to use appcomponent as component and going to create a service to call http service

Navigate to src/app from vs code terminal, Execute below command to create service

ng g s app-service

app-service.service.ts & app-service.service.spec.ts will get created in src/app folder

C:\Users\Admin\angular-demo\src\app>ng g s app-service
CREATE src/app/app-service.service.spec.ts (378 bytes)
CREATE src/app/app-service.service.ts (139 bytes)

C:\Users\Admin\angular-demo\src\app>

Now open the app-service.ts file

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AppServiceService {

  constructor() { }
}
Http Endpoint details

For this tutorial, I have created a endpoint which return student details

http://localhost:8080/api/student
Output Json
[
  {
    "id": 1,
    "department": "ECE",
    "firstname": "rajesh",
    "lastname": "kumar"
  }
]

Create a student model class to map the HTTP Response

student.model.ts

export class Student {
    department: string;
    firstname: string;
    id: number;
    lastname: string;
}

create a method to invoke http call. We are using HttpClient from @angular/common/http

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Student } from './model/student.model';


@Injectable({
  providedIn: 'root'
})
export class AppServiceService {

  constructor(private http: HttpClient) { }

  getStudentDetails(): Observable<Student[]>{
    return this.http.get<Student[]>('http://localhost:8080/api/student');

  }

}

Now call the getStudentDetails() method from app.component.ts on ngOnInit

  ngOnInit(): void {
    this.appService.getStudentDetails().subscribe(data => {
      this.studentDetails=data;
    });

Below is the complete app.component.ts

import { Component } from '@angular/core';
import { AppServiceService } from './app-service.service';
import { Student } from './model/student.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  title = 'angular-demo';

  constructor(private appService: AppServiceService) { }

   studentDetails: Student[];

  ngOnInit(): void {
    this.appService.getStudentDetails().subscribe(data => {
      this.studentDetails=data;
    });

  }
}

You can map this StudentDetails to your html as like below

<div *ngIf="studentDetails">
    <table>
        <thead>
            <tr>
                <td>ID</td>
                <td>FirstName</td>
                <td>LastName</td>
                <td>Department</td>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let response of studentDetails">
                <td>
                    {{response.id}}
                </td>
                <td>
                    {{response.department}}
                </td>
                <td>
                    {{response.firstname}}
                </td>
                <td>
                    {{response.lastname}}
                </td>
            </tr>

        </tbody>

    </table>

</div>
<router-outlet></router-outlet>
Conclusion

I this post we learned to call http rest service from angular

Github

https://github.com/rkumar9090/angular-demo/blob/master/src/app/app-service.service.ts

Categories
security spring-boot

spring-boot-security using http basic authentication

In this post, we will learn about spring-boot-security using http basic authentication

In this tutorial we will use spring security where we can enable security for our spring applications

Dependency
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

Add above dependency in your pom.xml

In this example, we are creating two rest endpoints, which I named as hello and hi

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

	@GetMapping("hello")
	public String getHello() {
		return "Hello";
	}

	@GetMapping("hi")
	public String getHi() {
		return "Hi";
	}

}

Now we can create new class SecurityConfig.java to configure our security
we need to add @Configuration @EnableWebSecurityannotations in our SecurityConfig.java and also we need to extend WebSecurityConfigurerAdapter 

And also we need to override two configure methods in SecurityConfig.java

In the first configure method we need to configure user and role details, Here I added two users with two roles 


import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
		auth.inMemoryAuthentication()
		.withUser("admin").password(encoder.encode("password")).roles("ADMIN").and()
		.withUser("user").password(encoder.encode("pass")).roles("USER");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
		.authorizeRequests().antMatchers("/hello").permitAll()
		.anyRequest().authenticated().and().httpBasic();
		
	}

}

In the above snippet, we allowed /hello endpoint and remaining endpoints are authenticated with httpBasic authentication

We are using PasswordEncoder to encode the password

Run the application as spring boot application

Testing

Conclusion

The above example is a simple spring security authentication using http basic. Here we added user details in-memory authentication

Github

https://github.com/rkumar9090/spring-security

Categories
java

automatic mouse mover in java

In this post, we will do automatic mouse mover in java

We can move the cursor with random directions using below code

Example
import java.awt.Robot;

public class MouseMover {

	public static void main(String[] args) {
		try {
			int xCord = 10;
			int yCord = 20;
			while (true) {

				Robot robot = new Robot();
				robot.mouseMove(xCord++, yCord++);
				System.out.println("Moving mouse to " + xCord + " " + yCord);
				Thread.sleep(10000);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Github

https://github.com/rkumar9090/student-example/blob/master/src/main/java/com/beginnersbug/example/mouse/MouseMover.java

Categories
java spring-boot

enable cors in spring boot rest API

In this post we will learn to enable cors in spring boot rest API

For security reasons, browsers prohibit AJAX calls to resources residing outside the current origin.

While we facing cors issue, we need to enable cors in spring boot application explicitly

Enable for whole spring boot

We need to add below class in our spring boot application, this will enable cors for all endpoints

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig {

	public WebMvcConfigurer corsConfigure() {
		return new WebMvcConfigurerAdapter() {
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/**");
			}
		};
	}

}
Enable for specific endpoint

Below snippet will enable cors only for endpoint which starts with /api


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig {

	public WebMvcConfigurer corsConfigure() {
		return new WebMvcConfigurerAdapter() {
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/api/**");
			}
		};
	}

}
Enable for specific orgins

Below snippet will enable for orgin https://beginnersbug.com

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig {

	public WebMvcConfigurer corsConfigure() {
		return new WebMvcConfigurerAdapter() {
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/api/**")
				.allowedOrigins("https://beginnersbug.com");
			}
		};
	}

}
Enable CORS with Annotation

we can enable cors by annotation. we need to mention @crossOrgin annotation in the controller class as like below


import java.util.List;
import java.util.Optional;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.beginnersbug.studentservice.dao.StudentDao;
import com.beginnersbug.studentservice.model.Student;

@RestController()
@CrossOrigin()
@RequestMapping("/api/student")
public class StudentController {

	@Autowired
	StudentDao studentsDao;

	@RequestMapping(method = RequestMethod.GET)
	public List<Student> getStudentsList() {
		return studentsDao.findAll();
	}
}
Github

https://github.com/rkumar9090/student-service/blob/master/src/main/java/com/beginnersbug/studentservice/CorsConfig.java

Related Articles

read value from application.properties spring boot

Categories
date java

change timezone of date in java

In this post, we will learn to change timezone of date in java

In java by default new Date() will give you the system/server timezone.

Syntax
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Example

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

public class ChangeTimeZon {

	public static void main(String[] args) {
		try {
			Date date = new Date();
			System.out.println("Current Date Time : " + date);
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
			// In below line we are mentioned to convert into UTC
			dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
			String utcFormat = dateFormat.format(date);
			System.out.println("After converting into UTC format: " + utcFormat);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
Current Date Time : Thu Jun 18 15:29:35 IST 2020
After converting into UTC format: 2020-06-18 09:59:35 UTC
Conclusion

In the above post, we learned to change timezone of date in java

Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/date/ChangeTimeZon.java

Related Articles

calculate number days between two dates using java

Categories
collections java

join two arraylist in java with example

In this post, we will learn to join two arraylist in java with example

ArrayList is a dynamic array concept in java. We use ArrayList in so many places.

Syntax
list1.addAll(list2);

From the above syntax list2 will added to list1.

Example
import java.util.ArrayList;
import java.util.List;

public class Join2List {

	public static void main(String[] args) {
		try {
			List<String> list1 = new ArrayList<String>();
			List<String> list2 = new ArrayList<String>();

			list1.add("Rajesh");
			list1.add("Usha");

			list2.add("Kumar");
			list2.add("Nandhini");

			System.out.println("---List1 value before adding list2---");
			for (String string : list1) {
				System.out.println(string);
			}

			// Adding list2 to list1
			list1.addAll(list2);

			System.out.println("---List1 value After adding list2---");

			for (String string : list1) {
				System.out.println(string);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
---List1 value before adding list2---
Rajesh
Usha
---List1 value After adding list2---
Rajesh
Usha
Kumar
Nandhini
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/list/Join2List.java

Related Articles

ArrayList in java with example

Categories
java

singleton in java with example

In this post, we will learn singleton in java with example

Singleton is one of the famous design pattern in java. Below are few point of Singleton

  • We Should have the only one instance in the application
  • In below example, we are going to use Lazy Initialization
  • It will create an instance when the application in need
  • We should have a private constructor to avoid outside initialization
public class SingletonExample {

	public static SingletonExample singletonExampleObject = null;

	public String stringVarible = "Singleton string";

	private SingletonExample() {

	}

	public static SingletonExample getSingletonInstance() {
		if (null == singletonExampleObject) {
			singletonExampleObject = new SingletonExample();
		}
		return singletonExampleObject;
	}

}

The above class is an example of Singleton. As mentioned in the above sentence we have a private constructor and static instance of the class

public class Example {

	public static void main(String[] args) {
		try {
			SingletonExample singletonObject = SingletonExample.getSingletonInstance();
			System.out.println(singletonObject.stringVarible);
			singletonObject.stringVarible = "BeginnersBug";

			// Creating another object
			SingletonExample singletonInstance = SingletonExample.getSingletonInstance();
			System.out.println(singletonInstance.stringVarible);
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

}
Singleton string
BeginnersBug

Even though we have two variables for SingletonExample it is sharing same instance

So the Value of stringVaraible is reflected on the second variable

Conclusion

In the above post, we learned about singleton in java with example

Github

https://github.com/rkumar9090/student-example/tree/master/src/main/java/com/beginnersbug/example/singleton

Related Articles

convert java object to JSON string

Categories
java

convert java object to JSON string

In this post, we will learn to convert java object to JSON string using GSON library

We can convert Java object to json string using below dependency

Dependency
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>
Syntax
String jsonString = gson.toJson(student);
Example

import com.beginnersbug.example.model.Student;
import com.google.gson.Gson;

public class ConvertJavaToJson {

	public static void main(String[] args) {
		Gson gson = new Gson();
		Student student = new Student();
		student.setStudentId("001");
		student.setStudentName("Rajesh");
		student.setDepartment("JAVA");
		student.setSchoolName("BeginnersBug");

		String jsonString = gson.toJson(student);

		System.out.println(jsonString);

	}
}
Student.java
public class Student {

	private String studentId;

	private String studentName;

	private String schoolName;

	private String department;

	public String getStudentId() {
		return studentId;
	}

	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public String getSchoolName() {
		return schoolName;
	}

	public void setSchoolName(String schoolName) {
		this.schoolName = schoolName;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

}
Output
{"studentId":"001","studentName":"Rajesh","schoolName":"BeginnersBug","department":"JAVA"}
Github

https://github.com/rkumar9090/student-example/blob/master/src/main/java/com/beginnersbug/example/ConvertJavaToJson.java

Related Articles

convert JSON string to java object