Categories
java properties

how to write properties file in java

In this tutorial, we will learn how to write properties file in java

we are going to use FileOutputStream to write in file. It is going to write on classpath

Syntax
properties.store(new FileOutputStream("database.properties"), "Comments: Updated from java");
Example Create new property file
import java.io.FileOutputStream;
import java.util.Properties;

public class WriteProperties {

	public static void main(String[] args) {
		try {

			Properties properties = new Properties();
			properties.setProperty("database.url", "jdbc:mysql://localhost:3306/beginnersbug");
			properties.setProperty("database.username", "root");
			properties.setProperty("database.password", "password");
			properties.store(new FileOutputStream("database.properties"), "Comments: Updated from java");
			System.out.println("File has writen successfully");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Output
File has writen successfully
Github

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

Related Articles

how to load property file in java

 

Categories
java

java.sql.SQLTimeoutException Query Timeout

In this tutorial, we will learn about java.sql.SQLTimeoutException Query Timeout

It is always good to do proactive coding. As part of database connection configuration we need to take care of certain parameters

Timeout is one of those properties. If don’t configured well you might get below exception

java.sql.SQLTimeoutException The Query has Timed Out
Root Cause for query timeout

Your application runs a long query with database. you will have this exception.

Solution
  • setQueryTimeout
    • Sets the number of seconds the driver will wait for a Statement object to execute to the given number of seconds.
    • default value is 0. which means infinite
  • setSelectMethod cursor
    • By setting the property to “cursor,”. you can create a server-side cursor that can fetch smaller chunks of data at a time
    • default value is direct.
  • setSendStringParametersAsUnicode false 
    • Set to false string parameters are sent to the server in an ASCII/MBCS format, not in UNICODE
    • default value is true
Reference

https://github.com/Microsoft/mssql-jdbc/issues/634

Categories
java properties

how to load property file in java

In this post, we will learn how to load property file in java. Properties file is used to store and retrieve values from file.

It is stored as key and value pair. Below is an sample property file

database.properties
database.url=jdbc:mysql://localhost:3306/beginnersbug
database.username=root
database.password=password
Read properties from absolute path
import java.io.FileReader;
import java.util.Properties;

public class LoadProperty {

	public static void main(String[] args) {
		try {
			FileReader reader = new FileReader("D:\\BB\\Workspace\\database.properties");

			Properties p = new Properties();
			p.load(reader);

			System.out.println(p.getProperty("database.url"));
			System.out.println(p.getProperty("database.username"));
			System.out.println(p.getProperty("database.password"));

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

	}

}
Output
jdbc:mysql://localhost:3306/beginnersbug
root
password
Read properties from class path

Please make sure you have database.properties in class path. else you will get Please check the file present in classpath

Syntax
LoadPropertyFromClassPath.class.getResourceAsStream("database.properties");

import java.io.InputStream;
import java.util.Properties;

public class LoadPropertyFromClassPath {

	public static void main(String[] args) {
		try {
			Properties prop = new Properties();
			InputStream stream = LoadPropertyFromClassPath.class.getResourceAsStream("database.properties");
			if (stream != null) {
				prop.load(stream);
				System.out.println(prop.getProperty("database.url"));
				System.out.println(prop.getProperty("database.username"));
				System.out.println(prop.getProperty("database.password"));
			} else {
				System.err.println("Please check the file present in classpath");
			}

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

	}

}
Output
jdbc:mysql://localhost:3306/beginnersbug
root
password
Print all the values from property file
Syntax
prop.keySet().stream().map(key -> key + ": " + prop.getProperty(key.toString()))
						.forEach(System.out::println);
Example
import java.io.InputStream;
import java.util.Properties;

public class PrintPropertis {

	public static void main(String[] args) {
		try {
			Properties prop = new Properties();
			InputStream stream = LoadPropertyFromClassPath.class.getResourceAsStream("database.properties");
			if (stream != null) {
				prop.load(stream);
				prop.keySet().stream().map(key -> key + ": " + prop.getProperty(key.toString()))
						.forEach(System.out::println);
			} else {
				System.err.println("Please check the file present in classpath");
			}

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

}
Output
database.password: password
database.url: jdbc:mysql://localhost:3306/beginnersbug
database.username: root
Github

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

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

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

Related Articles

how to read a file from java with example

delete a file from java code

Categories
java

how to get the hostname in java code

In this post, we will learn how to get the hostname in java code

In this example we are using InetAddress to get the hostname

Syntax
InetAddress.getLocalHost().getHostName();
Example
import java.net.InetAddress;

public class Hostname {

	public static void main(String[] args) {
		try {

			String hostName = InetAddress.getLocalHost().getHostName();
			System.out.println(hostName);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
DESKTOP-U9R6O19
Github

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

Related Articles

Run shell script from java with Example

 

Categories
ansible devops

multiple hosts in ansible playbook

In this tutorial, we will learn about using multiple hosts in ansible playbook

In below example, we configured separate host for each task.

mutiplehost.yml
---
- hosts: 10.118.225.56
  tasks:
    - name: first server
      shell: "mkdir /home/host1"	
- hosts: 10.118.225.56
  tasks:
    - name: first server
      shell: "mkdir /home/host1"
- hosts: 10.118.225.56
  tasks:
    - name: first server
      shell: "mkdir /home/host1"
- hosts: 10.118.225.56
  tasks:
    - name: first server
      shell: "mkdir /home/host1"
Command
ansible-playbook mutiplehost.yml
Related Articles

when condition in ansible playbook

Categories
Interview java matrix

multiply two matrix using java with example

In this post, we will learn about multiply two matrix in java with example

We are declaring two matrix named as a,b and one more variable mul to store the multiplication of a&b matrix

Example
public class MatrixMultiplication {

	public static void main(String[] args) {
		try {

			int a[][] = { { 50, 60 }, { 20, 15 } };
			int b[][] = { { 25, 20 }, { 10, 5 } };

			// Declaring the diff matrix
			int[][] mul = new int[a.length][b.length];

			// multiply 2 matrices
			for (int i = 0; i < a.length; i++) {
				for (int j = 0; j < b.length; j++) {
					mul[i][j] = 0;
					for (int k = 0; k < 2; k++) {
						mul[i][j] += a[i][k] * b[k][j];
					}
					System.out.print(mul[i][j] + " ");
				}
				System.out.println();
			}

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

}
Output
1850  1300 
650   475 
Github

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

Related Articles

subtracting two matrix in java with example

Categories
Interview java matrix

subtracting two matrix in java with example

In this post, we will learn about subtracting two matrix in java with example

We are declaring two matrix named as a,b and one more variable diff to store the subtraction of a&b matrix

Example
public class SubtractingMatrix {

	public static void main(String[] args) {
		try {

			int a[][] = { { 50, 60 }, { 20, 15 } };
			int b[][] = { { 25, 20 }, { 10, 5 } };

			// Declaring the diff matrix
			int[][] diff = new int[a.length][b.length];

			// Subtracting two matrix
			for (int i = 0; i < a.length; i++) {

				for (int j = 0; j < b.length; j++) {
					diff[i][j] = a[i][j] - b[i][j];
				}
			}

			// Printing the diff matrix
			for (int i = 0; i < diff.length; i++) {
				for (int j = 0; j < diff[i].length; j++) {
					System.out.print(diff[i][j] + " ");
				}
				System.out.println();
			}

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

	}
}
Output
25 40 
10 10 
Github

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

Related Articles

adding two matrix in java with example

Categories
Interview java matrix

adding two matrix in java with example

In this post, we will learn about adding two matrix in java with example

In below example,We are using two dimensional array for this operations.

Here we are declaring two matrix named as a,b and one more variable sum to store the addition of a&b matrix

The first for loop is used to add two matrix and the second for loop used to print the addition value

Example
public class AddingMatrix {

	public static void main(String[] args) {
		try {

			int a[][] = { { 54, 67 }, { 45, 56 } };
			int b[][] = { { 25, 56 }, { 85, 96 } };

			// Declaring the sum matrix
			int[][] sum = new int[a.length][b.length];

			// Adding two matrix
			for (int i = 0; i < a.length; i++) {

				for (int j = 0; j < b.length; j++) {
					sum[i][j] = a[i][j] + b[i][j];
				}
			}

			// Printing the sum matrix
			for (int i = 0; i < sum.length; i++) {
				for (int j = 0; j < sum[i].length; j++) {
					System.out.print(sum[i][j] + " ");
				}
				System.out.println();
			}

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

	}

}
Output
79 123 
130 152 
Github

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

Related Articles

create 2×2 matrix using java

Categories
java matrix

create 2×2 matrix using java

In this post, we will learn to create 2×2 matrix using java

We all know that In mathematics Matrix is a two dimensional array with rows and column as like above image. Here we are going to create that matrix using java

Java have a feature to create two dimensional array as like below

Two dimensional array Syntax
			int a[][] = { { 1, 2 }, { 2, 4 } };

The above array will convert as like below image

Example
public class CreateMatrixExample {
	public static void main(String[] args) {
		try {

			// Creating 2x2 matrix
			int a[][] = { { 1, 2 }, { 2, 4 } };

			// printing above 2d array in matrix format
			for (int i = 0; i < a.length; i++) {
				for (int j = 0; j < a[i].length; j++) {
					System.out.print(a[i][j] + " ");
				}
				System.out.println();
			}

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

}
Output
1 2 
2 4 
Github

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

Categories
ansible devops

when condition in ansible playbook

In this tutorial, we will learn about when condition in ansible playbook

We don’t have If condition here. Instead of that we can use when condition

Syntax
when: {condition}
when: inventory_hostname == "local"

In below example we are using when condition based on host

Example
---
- hosts: 127.0.0.1
  tasks:
  - name:  Make a directory  
    shell: "mkdir sample"
    when: inventory_hostname == "127.0.0.1"
    
  - name: make directory
    shell: "mkdir sample"
    when: inventory_hostname == "10.118.226.25" or inventory_hostname == "10.118.225.65"
Execute Command
ansible-playbook whenexample.yml
Output
PLAY [127.0.0.1] *************************************************************************************************************************************

TASK [Gathering Facts] *******************************************************************************************************************************
ok: [127.0.0.1]

TASK [Make a directory] ******************************************************************************************************************************
[WARNING]: Consider using the file module with state=directory rather than running 'mkdir'.  If you need to use command because file is insufficient
you can add 'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.

changed: [127.0.0.1]

TASK [make directory] ********************************************************************************************************************************
skipping: [127.0.0.1]

PLAY RECAP *******************************************************************************************************************************************
127.0.0.1                  : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   

when condition matches you can see the changed: [127.0.0.1]in result.
Else it will skip the task skipping: [127.0.0.1] in result

Reference

Below is Ansible documentation for conditions https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html

Related Articles

ignore warning message in ansible

Ignore Error in Ansible playbook