Monday, September 30, 2024

Angular Access Control CanActivate Route Guard Example

In your Angular application you may need to control access to different parts of your app. To control that kind of authorization and authentication you can use route guards in Angular.

Using route guards, you can perform some action before navigating to another route and you can restrict access to routes based on the outcome of that action. In this post we’ll see example of using CanActivate route guard to restrict access to route based on whether user is authenticated or not.


Why route guards in Angular

Use of route guards to control access in your Angular app may be considered for following scenarios-

  • User is not authorized to navigate to the component rendered by the route user want to navigate to.
  • User is not authenticated (not logged in).
  • You need to fetch some data before you display the target component.
  • You want to save pending changes before leaving a component.
  • You want to ask the user if it's OK to discard pending changes rather than save them.

Sunday, September 29, 2024

How to Read File From The Last Line in Java

There are applications where you have to read huge files line by line may be using some tool like Pentaho, Camel. Let's say these files are in the format header, records and footer and you need to check something in the footer (last line of the file) and if that condition is not met you need to reject the file. Now, reading line by line in such scenario, will be wasteful as you'll anyway reject the file in the end.

So for such scenarios it is better to read the last line (or may be last N lines) of the file, to have better throughput. In this post you will see how to read a file from the last line in Java.


In Java reading file from the end can be done using RandomAccessFile which has a seek method to set the file-pointer offset, measured from the beginning of the file.

Apache Commons IO also has a ReversedLinesFileReader class which reads lines in a file reversely.

File used

Let's say you have a file aa.txt which has the following content-

This is the first line.
This is the second line.
This is the third line.
This is the fourth line.

And you want to read last line of this file using Java.

Monday, August 26, 2024

Node.js MySQL Delete Example

In the post Node.js MySQL Update Example we saw examples of updating records in a table using Node.js and MySQL. In this post we'll see examples of deleting records from table using Node.js and MySQL. We'll be using the Promise Based API provided by MySQL2 library and a connection pool to connect to database in the examples provided here.

Table used

Table used for the example is Employee table with columns as- id, name, age, join_date.


CREATE TABLE `node`.`employee` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `join_date` DATE NOT NULL,
  `age` INT NULL,
  PRIMARY KEY (`id`));

Node.js delete record MySQL example

We'll keep the DB connection configuration in a separate file that can be used wherever it is needed by importing it.

util\database.js

const mysql = require('mysql2/promise');

const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'admin',
    database: 'node',
    waitForConnections: true, 
    connectionLimit: 10,
  });

module.exports = pool;

As you can see pool object is exported here so that it can be used in other files.

app.js

In this file let's create a function to delete Employee record from employee table in MySQL DB.

const pool = require('./util/database');

async function deleteEmployee(id){
  // TODO Verify if emp with the same id exists or not.. 
  // For that select query to get by id can be used

  const sql = "DELETE FROM EMPLOYEE where id = ?";
  const values = [id];
    try{
      const conn = await pool.getConnection();
      const [result, fields] = await conn.execute(sql, values);
      console.log(result);
      console.log(fields);
      conn.release();
    }catch(err){
      console.log(err);
    }
}

deleteEmployee(1);

Important points to note here-

  • deleteEmployee() function is an async function as we are using async/await (Promise based API) rather than callback-based API.
  • We are using await with pool.getConnection() method.
  • deleteEmployee() function takes one argument where it expects an id for the employee to be deleted.
  • Delete query is created as a parameterized query, where id is passed later. By having this kind of prepared statement makes our code more generic to be used with any id and also gives better performance.
  • By using array destructuring we get the returned values for result and fields.
  • fields variable contains extra meta data about results, if available.
  • result contains a ResultSetHeader object, which provides details about the operation executed by the server.
  • After the task, connection is released using conn.release() which means connection goes back to the pool.

On running the file-

>node app.js

ResultSetHeader {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  info: '',
  serverStatus: 2,
  warningStatus: 0,
  changedRows: 0
}

undefined

That's all for this topic Node.js MySQL Delete Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Node.js MySQL Insert Example
  2. Node.js MySQL Select Statement Example
  3. Node.js - MySQL Connection Pool

You may also like-

  1. Node.js path.resolve() Method
  2. NodeJS Event Loop
  3. Node.js Event Driven Architecture
  4. How to Setup a Node.js Project
  5. Custom Async Validator in Angular Reactive Form
  6. Pre-defined Functional Interfaces in Java
  7. Java Program to Convert a File to Byte Array
  8. JavaScript let and const With Examples

Saturday, August 24, 2024

Node.js MySQL Update Example

In the post Node.js MySQL Insert Example we have seen how to do an insert in MySQL DB from Node.js application. In this post we'll see examples of updating records in a table using Node.js and MySQL. We'll be using the Promise Based API provided by MySQL2 library and a connection pool to connect to database in the examples provided here.

Refer Node.js - MySQL Connection Pool to get more information about using MySQL Connection Pool with Node.js

Table used

Table used for the example is Employee table with columns as- id, name, age, join_date.


CREATE TABLE `node`.`employee` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `join_date` DATE NOT NULL,
  `age` INT NULL,
  PRIMARY KEY (`id`));

Node.js update record MySQL example

We'll keep the DB connection configuration in a separate file that can be used wherever it is needed by importing it.

util\database.js

const mysql = require('mysql2/promise');

const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'admin',
    database: 'node',
    waitForConnections: true, 
    connectionLimit: 10,
  });

module.exports = pool;

As you can see pool object is exported here so that it can be used in other files.

app.js

In this file let's create a function to update Employee record in MySQL.

const pool = require('./util/database');

async function updateEmployee(emp){
  // Verify if emp with the same id exists or not
  // For that select query to get by id can be used

  const sql = "UPDATE EMPLOYEE set name = ?, join_date = ?, age = ? where id = ?";
  const values = [emp.name, emp.joinDate, emp.age, emp.id];
    try{
      const conn = await pool.getConnection();
      const [result, fields] = await conn.execute(sql, values);
      console.log(result);
      console.log(fields);
      conn.release();
    }catch(err){
      console.log(err);
    }
}

//calling function with employee object
updateEmployee({name:'Ishan', joinDate:'2024-04-23', age:28, id:1})

Important points to note here-

  1. updateEmployee() function is an async function as we are using async/await (Promise based API) rather than callback-based API.
  2. We are using await with pool.getConnection() method.
  3. updateEmployee() function takes one argument where it expects an employee object to be passed.
  4. Using that object, appropriate values are passed to the prepared statement to update a record.
  5. By using array destructuring we get the returned values for result and fields.
  6. fields variable contains extra meta data about results, if available.
  7. result contains a ResultSetHeader object, which provides details about the operation executed by the server.
  8. After the task, connection is released using conn.release() which means connection goes back to the pool.

On running the file-

>node app.js

ResultSetHeader {
  fieldCount: 0,
  affectedRows: 1,
  insertId: 0,
  info: 'Rows matched: 1  Changed: 1  Warnings: 0',
  serverStatus: 2,
  warningStatus: 0,
  changedRows: 1
}

Undefined

If you want to get the number of rows which are updated you can get it using result.affectedRows from the result object.

You can check the DB to see the updated values.

Node.js MySQL Update

That's all for this topic Node.js MySQL Update Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Node.js MySQL Select Statement Example
  2. Node.js MySQL Delete Example
  3. Node.js - Connect to MySQL Promise API

You may also like-

  1. Node.js path.basename() Method With Examples
  2. __dirname and __filename in Node.js
  3. Appending a File in Node.js
  4. Creating HTTP server in Node.js
  5. Service in Angular With Examples
  6. Java Stream - count() With Examples
  7. Why main Method static in Java
  8. Named Tuple in Python

Convert String to Byte Array Java Program

In this post we'll see a Java program to convert a String to byte array and byte array to String in Java.


Converting String to byte[] in Java

String class has getBytes() method which can be used to convert String to byte array in Java.

getBytes()- Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

There are two other variants of getBytes() method in order to provide an encoding for String.

  • getBytes(Charset charset)
  • getBytes(String charsetName)
import java.util.Arrays;

public class StringToByte {
 public static void main(String[] args) {
  String str = "Example String";
  byte[] b = str.getBytes();
  System.out.println("Array " + b);
  System.out.println("Array as String" + Arrays.toString(b));
 }
}

Output

Array [B@2a139a55
Array as String[69, 120, 97, 109, 112, 108, 101, 32, 83, 116, 114, 105, 110, 103]

As you can see here printing the byte array gives the memory address so used Arrays.toString in order to print the array values.

Conversion of string to byte array with encoding

Suppose you want to use "UTF-8" encoding then it can be done in 3 ways.

String str = "Example String";
byte[] b;
try {
 b = str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}
b = str.getBytes(Charset.forName("UTF-8"));
b = str.getBytes(StandardCharsets.UTF_8);

Using str.getBytes("UTF-8") method to convert String to byte array will require to enclose it in a try-catch block as UnsupportedEncodingException is thrown. To avoid that you can use str.getBytes(Charset.forName("UTF-8")) method. Java 7 onward you can also use str.getBytes(StandardCharsets.UTF_8);

Converting byte array to String in Java

String class has a constructor which takes byte array as an argument. Using that you can get the String from a byte array.

String(byte[] bytes)- Constructs a new String by decoding the specified array of bytes using the platform's default charset.

If you want to provide a specific encoding then you can use the following constructor-

String(byte[] bytes, Charset charset)- Constructs a new String by decoding the specified array of bytes using the specified charset.

public class StringToByte {
 public static void main(String[] args) {
  String str = "Example String";
  // converting to byte array
  byte[] b = str.getBytes();
  
  // Getting the string from a byte array
  String s = new String (b);
  System.out.println("String - " + s);
 }
}

Output

String - Example String

That's all for this topic Convert String to Byte Array Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Convert String to int in Java
  2. Java Program to Find The Longest Palindrome in a Given String
  3. Find All Permutations of a Given String Java Program
  4. Check Given Strings Anagram or Not Java Program
  5. Add Double Quotes to a String Java Program

You may also like-

  1. Find Duplicate Elements in an Array Java Program
  2. How to Convert Date And Time Between Different Time-Zones in Java
  3. Association, Aggregation and Composition in Java
  4. Difference Between Abstract Class And Interface in Java
  5. Multi-Catch Statement in Java Exception Handling
  6. How ArrayList Works Internally in Java
  7. Difference Between ReentrantLock and Synchronized in Java
  8. Java ThreadLocal Class With Examples

Friday, August 23, 2024

Creating Custom Exception Class in Java

In this post we'll see how to create a custom exception in Java.

custom exception in Java

Though Java's exception handling covers the whole gamut of errors and most of the time it is recommended that you should go with standard exceptions rather than creating your own custom exception classes in Java, but you might need to create custom exception types to handle situations which are specific to your application.

Tuesday, August 20, 2024

Count Number of Words in a String Java Program

Write a Java program to count the number of words in a String is asked quite frequently in Java interviews. To test the logical thinking of the candidates it is often asked to write this program without using any of the String functions.

Java Program to count number of words in a String

Here three ways are given to count number of words in a String in Java. All of these ways take care of any number of spaces in between the words even the spaces at the beginning or at the end.

  • First method countWords() uses charAt() method to get each character of the String. Logic used in the method works fine even if there are extra spaces in the passed String and the correct count of the words in the String is given.
  • Second method countWordsUsingSplit() uses the String split() method to count number of words.
  • Third method countWordsUsingStream() uses the Java Stream API to count number of words.

Let's see the Java code first and later explanation of the code logic.

public class StringWordCount {
  public static void main(String[] args) {
    System.out.println("Word Count- " + countWords("   Life    is    beautiful  "));
        
    System.out.println("Count using split logic " + countWordsUsingSplit("         Life     is       beautiful  "));
    
    System.out.println("Count using Java Stream " + countWordsUsingStream("   Life    is    beautiful  "));
  }
    
  private static int countWords(String str){        
    
    if(str.isBlank()) {
      return 0;
    }
    int c = 0;
    for(int i = 0; i < str.length(); i++){
     
      /**
       * logic here is if the current character is not a space and the character read before the 
       * current char was a space that means one whole word is read so increment the count.  
       * Or part is to ensure correct working even if there are spaces in the beginning
      */
      if((i > 0 && (str.charAt(i) != ' ') && (str.charAt(i-1) == ' ' ))
          || ((i == 0) && (str.charAt(0) != ' ')))
        c++;
    }
    return c;
  }
    
  /**
  * This method counts using String split method 
  * @param str
  * @return
  */
  private static int countWordsUsingSplit(String str){
    // here split method is used with regex pattern of any number of spaces
    // so it will retrun a string array with the words
    String[] test = str.trim().split("\\s+");
    return test.length;
  }
  
  /**
  * This method counts using Java Stream API
  * @param str
  * @return
  */
  private static long countWordsUsingStream(String str){
	  // here split method is used with regex pattern of any number of spaces
	  // trim() is used to remove spaces in the beginning and at the end
	  long count = Stream.of(str.trim().split("\\s+")).count();
	  
	  return count;
  }
}

Output

Word Count- 3
Count using split logic 3
Count using Java Stream 3

Count number of words in a String program logic

In the first method countWords() the idea is; if the current character is not a space and the character read before the current char was a space that means one whole word is read so increment the count. This is the condition doing that

(str.charAt(i) != ' ') && (str.charAt(i-1) == ' ' )

For example if program is reading the string “life is” when the index comes to 'i' (in "is") the character before 'i' would be either space or tab, that means one word is already read (which in this case would be "life") thus count will be incremented.

We may miss to count the first word, this condition (i == 0) && (str.charAt(0) != ' ')) takes care of that.

Second way of counting number of words in a String uses the split method of string. Split() method takes a regex pattern as a parameter here we are passing “//s+” which will mean any number of spaces. So the condition becomes; split the word on any number of spaces in between. It returns a String array whose length will be the count of words in a string.

In the third method, String array that is returned by the split method is used to create a Stream using Stream.of() method. Then count() method of Java Stream API is used to return the count of elements in this stream.

That's all for this topic Count Number of Words in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Check if Given String or Number is a Palindrome Java Program
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Find All Permutations of a Given String Java Program
  4. Check Given Strings Anagram or Not Java Program
  5. Java Program to Check Prime Number

You may also like-

  1. Bubble Sort Program in Java
  2. Matrix Subtraction Java Program
  3. Package in Java
  4. Encapsulation in Java
  5. Marker interface in Java
  6. Creating Custom Exception Class in Java
  7. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  8. Race Condition in Java Multi-Threading