How to load property file in java

Overview

Application mostly require a file to store the configuration or data oustide the complied code. Most commonly used method is to store in properties file in the form of key value pair. In the below example. we’ll see how to read those properties file using Java.

Java has in-built support in java.util.Properties class to perform read/write operations on the properties file.

Properties file

config.properties

1
2
name=tutorialflix
description=loading properties from file

Reading properties file from classpath or resources folder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.tutorialflix.example.properties.file;

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

public class LoadPropertyFileFromClasspath {

public static void main(String[] args) {

try (InputStream input = LoadPropertyFileExample.class.getClassLoader().getResourceAsStream("config.properties")) {

Properties prop = new Properties();

// load a properties file
prop.load(input);

// get the property value and print it out
System.out.println(prop.getProperty("name"));
System.out.println(prop.getProperty("description"));

} catch (IOException ex) {
ex.printStackTrace();
}

}

}

Reading properties file from disk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.tutorialflix.example.properties.file;

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

public class LoadPropertyFileFromPath {

public static void main(String[] args) {

try (InputStream input = new FileInputStream("path/to/config.properties")) {


Properties prop = new Properties();

// load a properties file
prop.load(input);

// get the property value and print it out
System.out.println(prop.getProperty("name"));
System.out.println(prop.getProperty("description"));

} catch (IOException ex) {
ex.printStackTrace();
}

}

}

How to create a WSDL file

Introduction

WSDL stands for Web Services Description Language. WSDL is used to describe web services and also known as Contract. It is the base building block to create a SOAP webservice in Contract-First Approach.

Creation of WSDL consist of following:

  • Schema Design
  • WSDL Design

In the below example, we are creating a WSDL which contain a single operation createCustomer. You can follow the similar approach to add more operation in the WSDL.

Schema Design

First of all, we will create a schema file to define the request, response and fault structure.

XML Definition

Create a file of .xsd extension, in this case we are using customer-service.xsd

1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://service.customer.com/types/v1"
xmlns:tns="http://service.customer.com/types/v1" elementFormDefault="qualified">

<!-- Schema Content here -->

</xs:schema>

Request structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<xs:element name="createCustomerRequest" type="tns:CreateCustomerRequest" />
<xs:complexType name="CreateCustomerRequest">
<xs:sequence>
<xs:element name="customerName" type="xs:normalizedString"/>
<xs:element name="customerAge" type="xs:int" />
<xs:element name="customerPhoneNumber">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="10" />
<xs:whiteSpace value="collapse" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>

Response structure

1
2
3
4
5
6
<xs:element name="createCustomerResponse" type="tns:CreateCustomerResponse" />
<xs:complexType name="CreateCustomerResponse">
<xs:sequence>
<xs:element name="customerID" type="xs:integer" />
</xs:sequence>
</xs:complexType>

Fault structure

1
2
3
4
5
6
7
<xs:element name="createCustomerFault" type="tns:CreateCustomerFault" />
<xs:complexType name="CreateCustomerFault">
<xs:sequence>
<xs:element name="errorMessage" type="xs:normalizedString" />
<xs:element name="errorCode" type="xs:int" />
</xs:sequence>
</xs:complexType>

WSDL Design

Definitions

Create a file of .wsdl extension, in this case we are using customer-service.wsdl

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<wsdl:definitions
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="customer-service"
xmlns:tns="http://service.customer.com/v1"
xmlns:cs="http://service.customer.com/types/v1" targetNamespace="http://service.customer.com/v1">

</wsdl:definitions>

Schema Import

Import the schema which we have created in above example.

1
2
3
4
5
6
<wsdl:types>
<xsd:schema>
<xsd:import namespace="http://service.customer.com/types/v1" schemaLocation="schemas/customer-service.xsd"/>
</xsd:schema>
</wsdl:types>

Messages

Defines the data elements for each operation

1
2
3
4
5
6
7
8
9
<wsdl:message name="createCustomerRequest">
<wsdl:part name="createCustomerRequest" element="cs:createCustomerRequest"></wsdl:part>
</wsdl:message>
<wsdl:message name="createCustomerResponse">
<wsdl:part name="createCustomerResponse" element="cs:createCustomerResponse"></wsdl:part>
</wsdl:message>
<wsdl:message name="createCustomerFault">
<wsdl:part name="createCustomerFault" element="cs:createCustomerFault"></wsdl:part>
</wsdl:message>

PortType

Describes the operations that can be performed and the messages involved.

1
2
3
4
5
6
7
<wsdl:portType name="CustomerServicePort">
<wsdl:operation name="createCustomer">
<wsdl:input message="tns:createCustomerRequest" name="createCustomerRequest" />
<wsdl:output message="tns:createCustomerResponse" name="createCustomerResponse" />
<wsdl:fault message="tns:createCustomerFault" name="createCustomerFault"></wsdl:fault>
</wsdl:operation>
</wsdl:portType>

Binding

Defines the protocol and data format for each port type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<wsdl:binding name="CustomerServiceBinding" type="tns:CustomerServicePort">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
<wsdl:operation name="createCustomer">
<soap:operation soapAction="createCustomer" style="document" />
<wsdl:input name="createCustomerRequest">
<soap:body use="literal" />
</wsdl:input>
<wsdl:output name="createCustomerResponse">
<soap:body use="literal" />
</wsdl:output>
<wsdl:fault name="createCustomerFault">
<soap:fault name="createCustomerFault" use="literal" />
</wsdl:fault>
</wsdl:operation>
</wsdl:binding>
  • binding element has two attributes - name and type. The name attribute (you can use any name you want) defines the name of the binding, and the type attribute points to the port for the binding, in this case the “CustomerServicePort” port.

  • soap:binding element has two attributes - style and transport. The style attribute can be “rpc” or “document”. In this case we use document. The transport attribute defines the SOAP protocol to use. In this case we use HTTP.

  • operation element defines each operation that the portType exposes. For each operation the corresponding SOAP action has to be defined. You must also specify how the input and output are encoded. In this case we use “literal”.

Service

Defines the port and binding with the address where you want to expose your service.

<wsdl:service name="CustomerService">
    <wsdl:port name="CustomerServicePort" binding="tns:CustomerServiceBinding">
        <soap:address location="http://0.0.0.0:8181/cxf/customerservice/v1"/>
    </wsdl:port>
</wsdl:service>

You can download the WSDL and XSD file for your reference

SOAP - Simple Object Access Protocol

What is SOAP ?

Simple Object Access Protocol is a messaging protocol specification for exchanging structured information. Its purpose is to provide extensibility, neutrality and independence.

  • SOAP uses XML for its message format.
  • SOAP relies on application layer protocols such as HTTP, SMTP, TCP, UDP, or JMS for message negotiation and transmission.

SOAP consists of three parts

  • an envelope, which defines the message structure and how to process it
  • a set of encoding rules for expressing instances of application-defined datatypes
  • a convention for representing procedure calls and responses

SOAP building blocks

A SOAP message is an ordinary XML document containing the following elements:

Element Description Required
Envelope Identifies the XML document as a SOAP message Yes
Header Contains header information No
Body Contains call, and response information Yes
Fault Provides information about errors that occurred while processing the message No

Request Format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://service.customer.com/types/v1">
<soapenv:Header>
<wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-F434D320D890F7CF1715251639631263">
<wsse:Username>admin</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">admin</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<v1:deleteCustomerRequest>
<v1:customerID>123321</v1:customerID>
</v1:deleteCustomerRequest>
</soapenv:Body>
</soapenv:Envelope>

Response Format

1
2
3
4
5
6
7
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://service.customer.com/types/v1">
<soapenv:Body>
<v1:deleteCustomerResponse>
<v1:message>Customer Deleted Successfully</v1:message>
</v1:deleteCustomerResponse>
</soapenv:Body>
</soapenv:Envelope>

Fault Format

1
2
3
4
5
6
7
8
9
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd=="http://www.w3.org/1999/XMLSchema">
<soapenv:Body>
<soapenv:Fault>
<faultcode xsi:type="xsd:string">SOAP_FAULT_DELETECUSTOMER</faultcode>
<faultstring xsi:type="xsd:string">Customer not present</faultstring>
<faultactor>CustNotFound</faultactor>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>

Create a Web Application with Spring 5

Overview

The tutorial illustrates how to Create a Web Application with Spring. We’ll look into the Spring Boot solution for creating the application.

We’ll primarily use Java configuration in this tutorial.

Pre-requisties

  • JDK 1.8
  • Maven
  • IDE (for ease of use)

Creating Web app using Spring Boot

First, we’ll add the required dependencies and plugins in pom.xml

We will use the dependencyManagement to define a standard version of an artifact to use across multiple projects.

We will import version of artifacts defined in spring-boot-starter-parent.

1
2
3
4
5
6
7
8
9
10
11
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

Now we’ll add the spring-boot-starter-web dependency.

Spring Boot Starter Web includes:

  • spring-web module
  • spring-webmvc module
  • tomcat starter

Spring-web & Spring-webmvc are required for spring appplication while tomcat starter is required to run web application directly without explicitly installing any server.

1
2
3
4
5
6
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

Spring Boot Maven Plugin provides Spring Boot support in Maven, letting you package executable jar or war archives and run an application “in-place”.

1
2
3
4
5
6
7
8
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

Creating a Spring Boot Application

Create a class with main method. Annotate the class with @SpringBootApplication. Call the run method of SpringApplication class

1
2
3
4
5
6
7
8
9
10
11
12
package com.tutorialflix.spring.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootWebApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBootWebApplication.class, args);
}
}

@SpringBootApplication includes the functionality of following annotations:

  • @Configuration
  • @EnableAutoConfiguration
  • @ComponentScan.

** By default, it will perform the component scan in base package. So make sure SpringBootWebApplication class is present in the base package.**

Creating a Web Controller

Create a class with a meaningful name based on your requirement & annotate the class with @Controller.

1
2
3
4
5
6
7
8
9
package com.tutorialflix.spring.web.contrroller;

import org.springframework.stereotype.Controller;

@Controller
public class MyWebController {


}

Create a method to accept requests

Create a method named home to accept the request on ‘/‘ url and show the index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.tutorialflix.spring.web.contrroller;

import org.springframework.stereotype.Controller;

@Controller
public class MyWebController {

@GetMapping("/")
public String home() {
return "index.html";
}

}

Create a webpage to display

Create a public folder inside resources folder of application and create a file named index.html.

1
2
3
4
5
<html>
<body>
<h1>Welcome to TutorialFlix.</h1>
</body>
</html>

Configure application using properties file

Create a file application.properties inside resources folder of application and following properties.

1
2
server.port=8081
logging.level.org.springframework.web=DEBUG

server.port : to change the default port 8080 to any other port number.

logging.level.org.springframework.web : to change the log level default INFO to DEBUG

Run the web application

1
$ mvn spring-boot:run

Test

Goto http://localhost:8081/