Posts

Showing posts from 2022

Source code search Engines

If you don't want to spend more time in writing code instead just want to use already written code for the same feature that you are looking for then here are the list for few popular search code engines. S.No. Code Engine Description 1 https://github.com/ Code repository, contains many opensource projects 2 http://www.javased.com/ Search engine for Java code search 3 https://searchcode.com/ General code search engine. 4 https://you.com General code search engine. 5 https://publicwww.com/ Crawl web for code snippit.

The great list of Java Developers' Blogs

Here, I found the list of blogs for Java developers. The list is originally published on www.programcreek.com .You can also suggest a blog by posting a comment below. Name (Site/People) Country Specific Area 0 Code Search America #1 code search tool (Advertising) 1 Adam Bien Germany Java EE 2 Antonio Goncalves France Author of Java EE 7 3 Henrik Warne Sweden Thoughts on programming 4 Billy Yarosh America Coding Cures 5 Lars Vogel Germany Android and Eclipse 6 Peter Verhas Hungary Pure Java 7 Martin Fowler America Author, Speaker 8 Bozhidar Bozhanov Bulgaria Java EE 9 Richard Warburton UK Java 8 Lambdas 10 Bear Giles America Java EE 11 Marginally Interesting Germany Machine Learning 12 Pascal Alma America Java EE 13 Dror Helper America Consultant 14 Juri Strumpflohner Italy JavaScript 15 Reza Rahman America Java EE/Glassfish 16 Phil Whelan Canada Web 17 Brett Porter Australia Co-author of Apache Maven 2 18 Ben McCann America Co-founder at Connectifier 19 Java Posse America Some usef...

Why you need Mockito?

## Table of Contents 1. [Mockito](#mockito) 2. [Important Jargon](#important-jargon) 3. [How to get Mockito](#how-to-get-mockito) 4. [Annotations in Mockito library](#annotations-in-mockito-library) 5. [Mockito Exceptions](#mockito-exceptions) 6. [Mocking best practices](#mocking-best-practices) 7. [Drawbacks of Mocking](#drawback-of-mocking) ## Mockito [Mockito](https://site.mockito.org/) is an Open Source Mocking framework. It is a Java library mostly used for unit testing of Java application. The Mockito library enables mock **creation**, **verification** and **stubbing**. It simplifies the process of testing by creating mock objects and avoiding external dependencies like connecting to database. At present, Mockito frameworks consists of following set of libraries: * **mockito-all** - It consist of mockito core library and other dependencies like *hamcrest*. This is <mark>outdated library with no future release</mark>. Developer should use mockito-core instead. * ...

What is CORS ?

As a security reasons, web browsers implement same-origin policy, which means requesting data from same domain is allowed. Data requested using different domain will throw an error. CORS (Cross-Origin Resource Sharing) is a http-based mechanism that enables the browser to access resources outside a given domain. When a browser makes a cross-origin request, it will add an http Origin header that states the protocol and port number. The server responds and add an "Access-Control-Allow-Origin" header in the response to browser. If the header's origin is the same as the origin sent in the request then access to the resourse is granted. The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers. ### What kind of requests uses CORS ? CORS enable the cross origin requests like: 1. Access CSS resource like web-fonts , images etc. 2. Invocations of the XMLHttpRequest or Fetch APIs (The Fetch API provides an interface for f...

Eclipse MicroProfile configuration

Microprofile config, helps application to read the configurations from different configurations sources. Different sources for configuration could be: 1. Operating system environment variables ( mostly used in cloud native environment) 2. JVM system properties. 3. Database, LDAP or any other key-value store ( example: [HasiCorp vault] (https://www.hashicorp.com/products/vault) ) 4. External configuration files. #### Reading config properties ##### Programmatic: An application can obtain its configuration programmatically via the `ConfigProvider`. ``` Config config = ConfigProvider.getConfig(); ConfigValue databaseName = config.getConfigValue("myapplication.databaseName"); connect(dbUsername.getValue()); ``` ##### Dependency Injection: MicroProfile Config also provides ways to inject configured values into your beans using the `@Inject` and the `@ConfigProperty` qualifier ``` @Inject @ConfigProperty(name="myapplication.propertyname", def...

JavaEE CDI - Contexts and Dependency Injection

CDI (Contexts and Dependency Injection) is a standard dependency injection framework included in Java EE 6 onwards. CDI is also part of the Eclipse MicroProfile project, a framework use for development of Microservice application. ### CDI Releases | CDI Version | Release Year| |:-----------:|:-----------:| | CDI 1.0 | 2009 | | CDI 1.1 | 2013 | | CDI 1.2 | 2014 | | CDI 2.0 | 2017 | | CDI 3.0 | 2020 | | CDI 4.0 | 2022 | ### New Features - Removal of deprecated code Ex - **@New** qualifier which was deprecated in version 1.1 - Change in Bean discovery Mode CDI 4.0 bean discovery mode is by default Annotated - Support for Java Module system ( introduced in Java v9) - Introducing CDI Lite #### The “beans.xml” File First, we must place a **beans.xml** file in the - **src/main/resources/META-INF/** folder with **bean-discovery-mode** set to ```all``` or ``annotated`` Even if this file doesn't contain any sp...

Microservices using Eclipse Microprofile

Image
## What is MicroProfile ? MicroProfile is enterprose Java for Microservices development. It is an Open source framework. Initial version released in year 2016 with: - CDI - JAX-RS - JSON-P Over the years MicroProfile is evolving to solve the challenges in Microservice development. Given below are few features added to MicroProfile in recent release. - Configuration - Fault Tolerance - JWT Propogation - Health Check - Metrics - Open Tracing - Open API - Rest Client ## Why we need MicroProfile? MicroProfile evolved due to slowdown in JavaEE innovation. JavaEE was not prepared for Microservices development. ## MicroProfile Implementation - RedHat WildFly (https://www.wildfly.org/) - IBM WebSphere Liberty (https://www.ibm.com/products/websphere-liberty) - Open Liberty ( https://openliberty.io) - TomEE (https://tomee.apache.org/) - Payara Micro (https://www.payara.fish/) - ThornTail - Quarkus ( https://quarkus.io/) ### CDI - Contexts and Dependency Injection - Bean...

Executing Store procedure without out parameters and input parameters in Spring

Sometime, we have store procedures which do not have any input and output parameters. We can execute such store procedures using Spring *[SimpleJdbcCall](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/simple/SimpleJdbcCall.html)* class You might get the following exception message: ``` Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: Unable to determine the correct call signature - no procedure/function/signature for 'MY_STORE_PROCEDURE' ``` In such situation, We can bypass checking the signature of store procedure in metadata using method *withoutProcedureColumnMetaDataAccess* ``` SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(jdbcTemplate) .withProcedureName("MY_STORE_PROCEDURE") .withoutProcedureColumnMetaDataAccess(); simpleJdbcCall.execute(); ``` By calling the method withoutProcedureColumnMetaDataAccess we are bypassing any processing of the metadata lookups for potential param...

Java Stream Examples

### Problem #1: Given an integer array sorted in increasing order, return an array of the squares of each number sorted in increasing order. ### Solution: ``` public static int[] sortedSquaresArray(int[] numbers) { return Arrays.stream(numbers).boxed() .map(val -> val * val) .sorted() .mapToInt(value -> value.intValue()) .toArray(); } ``` If you want to return the squares of each number sorted in descending order then you can use *.sorted(Collections.reverseOrder())* ### Problem #2: Given ArrayList of Employee (name, age) object. Print the names of employees having age greater than 20 saperated with comma. ### Solution: ``` String str = employeeList.stream() .filter(e -> e.age >20) .map(e -> e.name) .collect(Collectors.joining(",")); System.out.println(str); ``` ### Problem#3: Create a reverse map...

Tricky Java Questions

Image
Java is most popular programming language. It is widely used programming languange and has many job opportunities. Interviewers often ask tricky questions to check the candidate knowldege about Java programming language. Sometimes experienced programmers also fail to answer tricky questions. In this post, I have picked few conceptual questions that will helped you to have better understanding of Java language. #### Q-1: what will be output of following code ? ``` public static void main(String[] args) { Integer number1 = 100; Integer number2 = 100; if (number1 == number2) { System.out.println("number1 == number2"); } else { System.out.println("number1 != number2"); } ``` #### Answer: ``` number1 == number2" ``` We have compared the references of two Integers. The result is surprising !!!. This is because of the autoboxing. Java uses IntegerCache to suppor...

Generate Custom Identifier in Hibernate

Image
Sometimes, we want to generate our table's primary key with more custom information. Custom Identifiers contains more information for us which helps us to distinguish and identify the records. It adds more meaning to an identifier. For example, an event Identifier like - 20220219000045 has two parts, the first part is the date and the second part is the sequence generated number.  YYYYMMDD + 6 digit number generated by the sequence This type of identifier tells us that this event is created on the date: 21/02/2022 . Similarly, we might have different requirements to generate custom Identifiers.  In the post, I will show how can we generate simple sequence based custom identifier in Hibernate. The custom Identifier can be generated in Hibernate by defining our own Identifier generator which implements the Hibernate  IdentifierGenerator interface. However, if you have a database that supports sequences like Oracle RDBMS then you can use SequenceStyleGenerator class in ...

SQL*Loader - Load data into table from CSV file

In this article, I am going to show how we can use Oracle SQL *Loader to insert data into the Oracle table. We will create one simple table and create the necessary files required to load the data from the CSV file into the table using Oracle SQL*Loader. The example given in this article is very basic and it will help beginners to understand the SQL*Loader concept. SQL*Loader has various options to load data and support multiple input data formats. Step-1: Lets first create a table Employee. CREATE TABLE EMPLOYEE ( EMPLOYEE_ID NUMBER(8,0), NAME VARCHAR2(40), EMAIL VARCHAR2(60) NOT NULL, DOB DATE, PRIMARY KEY (EMPLOYEE_ID) ); Step-2: Create SQL*Loader control file - "employee.ctl" The control file is a text file that SQL*Loader uses to understand where to find the data file, how to parse the data and how to insert the data into the oracle table and many other options. Given below is the sample format of the control file which...

Convert Java Keystore JKS into PEM format

Java Keystore or a JKS file is a store of security certificates ( private keys, signer certificates). The JKS file is created using keytool utility that shipped with JDK. The JKS file format is proprietary and used by Java applications. Many application on windows uses PEM ( Privacy-Enhance Mail) format for storing and sending certificates and keys. The PEM format is generally used to send the certificate via emails as it is base64 encoded. We can use keytool command to export key entry into PEM file format . keytool -exportcert -alias mykey -keystore MyKeystore.jks -rfc -file mykey_cert.pem After executing the above command the certificate will be exported and stored into mykey_cert.pem file. By default "keytool -exportcert" command export the certificate as binary encoding i.e Distinguished Encoded Rules (DER) file format. DER format is not suitable for transmitting the certificate file and hence, we need to convert the file as PEM format. The -rfc switch...

Sample bash script to start and stop Java application on Linux

Image
Do you have trouble running your Java/Springboot applications on Linux? How do you start and stop your Java applications on a Linux server? Executing a standalone Java application or Springboot executable jar in your local machine is simple and easy. You can use any of the Java IDE like Eclipse, Idea IntelliJ, NetBeans, etc. during development. If you have developed a Java application that you need to execute on a Linux machine then you need a shell script to start your Java executable jar file. Without a proper shell script, it is a big pain to provide all required arguments in a command prompt every time to execute your Java application. Here is a sample script that I prepared during my college days to execute my college project which I developed in Java. I have used this script for various other projects and I still found it helpful to execute my Springboot applications.  It is one of the traditional approaches not suitable for the applicat...

Creating simple Maven multi module project in Java

Image
In this post, I will discuss how to create a simple Maven multi-module project. In multi-module projects, we have multiple modules to be built using Maven. We have external dependencies as well as internal dependencies between different modules. Let's figure out how we can create multi-modules projects in Maven and how the internal and external dependencies are handled by Maven during the build process?. Technologies used: Maven 3.3.3 JDK 1.6 Simple Structure for Multi-Module Project There are multiple ways to create the structure for multi-module maven projects. It depends on the project requirements, code repository structure, and project lifecycle (need for parent pom release, packaging, etc.). One of the simplest structures is given below: Sample Project - RoketApp In order to understand in a better way, let us create a sample multi-module project - RocketApp , similar to the above structure. RocketApp consist of two module - rocket-core & rocket-ut...

How to update existing CCDT file (AMQCLCHL.TAB) for successful MQueue connection

The client channel definition table ( CCDT) file contains the MQ channels definitions and authentication information used by the client program/application to connect to the queue manager. It is a binary file so we cannot modify using any text editor. Change in the channel properties like SSLCIPH, USERID, etc. in Queue manager also required change in the CCDT file. Otherwise, it will break the application MQ connection. From IBM MQ v8.0 onwards we can create and modify the CCDT file on client machines directly. Below are the steps to modify the existing CCDT file. Set the necessary environment properties First set the location of CCDT on the client machine. You can do it using the following environment variables: MQCHLLIB – Specify the directory path where the CCDT file is located. MQCHLTAB – Specify the file name of CCDT (a default name – AMQCLCHL.TAB) #Only path (exclud...