Tuesday, March 31, 2020

Auto-Generated Field for MongoDB using Spring Boot - Step By Step

Outline:

In this tutorial, we are going to learn how to implement a sequential and auto-generated field for MongoDB in Spring Boot. If you are new to MongoDB and Spring then visit  Spring Data MongoDB Tutorial.

Understanding step by step today about "Auto-Generated Field for MongoDB using Spring Boot"

Spring Boot Tutorials

[update] Updated new errors in this article.
This is a very common scenario that arises when using MongoDB and Spring framework integration work.

When we are using MongoDB databases as part of the Spring Boot application directly we can not use @GeneratedValue annotation in our database model classes.

@GeneratedValue: Marking a field with the @GeneratedValue annotation specifies that value will be automatically generated for that field and mainly this is used on primary key fields. This annotation is available only for JPA API.



Auto-Generated Field for MongoDB using Spring Boot


The easy solution to this problem is very simple. We will create a collection or table that will store the generated sequence for other collections. During the creation of a new record, we’ll use it to fetch the next value.

How to Use Iterator in Java? Java 8 Iterator Examples on ArrayList, HashSet, HashMap

1. Introduction


In this article, We will learn the Iterator interface in java and what are its methods. Let us write examples on how to use the Iterator in java.

Iterator is used to iterate or traverse over a Collection such as ArrayList, LinkedList or HashSet. Iterator is a replacement to the Enumeration because Enumeration does not allow to remove the values from underlying collection and methods names are not readable (understandable).

In the previous post, we have discussed in detail on ConcurrentModificationException and how to avoid concurrency.

How to Use Iterator in Java? Java 8 Iterator Examples on ArrayList, HashSet, HashMap

Monday, March 30, 2020

Understand Java ConcurrentModificationException and How To Avoid ConcurrentModificationException

1. Introduction 


In this article, We'll learn when ConcurrentModificationException exception is thrown and what are the reasons java API throws this exception. This is part of java.util package.

From API: This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

Most of the collection API classes throw this exception such as ArrayList, HashMap, LinkedList classes. The main reason to throw this exception if any list or map is modified when a loop list or map through the iterator. If the collection is modified when it is looped over Iterator, iterator.next() will thorough ConcurrentModificationException exception. This exception mainly comes into existence in the multithreaded environment. If any collection produces this exception then it is fail-fast and should not be used by multiple threads.


Understand Java ConcurrentModificationException and How To Avoid ConcurrentModificationException

Understanding the differences between ArrayList and LinkedList

1. Introduction


In this tutorial, We will learn a mostly asked interview question for 2-6 years of experiences java developers. What are the differences between ArrayList and LinkedList? When to use which one ArrayList or LinkedList? What are the advantages of each one?

ArrayList and LinkedList are part of java.util package and introduced in java 1.2 version. They have made internally lots of changes during the new JDK version evolution.

Let us explore some of the aspects of the ArrayList and LinkedList.

Note: ArrayList works on the index-based and Linked list works on Node-based internally but LinkedList can be accessed by index as well.


Understanding the differences between ArrayList and LinkedList



Thursday, March 26, 2020

Program: How To Reverse ArrayList in Java + Custom Reverse

1. Introduction


In this article, we'll be learning how to reverse ArrayList in java. Reversing can be done in two ways using Collections.reverse() method and custom reverse method.
This is one of the ArrayList interview questions commonly asked.


In the end, You will decide which is the simplest way to reverse List?

Program: How To Reverse ArrayList in Java + Custom Reverse



Wednesday, March 25, 2020

Java ArrayList Examples: Collection API ArrayList Interview Questions and Answers

1. Introduction


In this tutorial, We'll be learning today's java collection API ArrayList class and its methods with examples. And also understand how ArrayList will be asked in the interview and how to solve the problems with ArrayList. Refer to Java 13 API Ref.


Java ArrayList Examples: Collection API ArrayList Interview Questions and Answers


Monday, March 23, 2020

Spring - Dynamically register beans in 4 ways At Run-Time

1. Overview

In this tutorial, We will learn about "dynamically register bean with spring" or "dynamically add the bean to spring-context" (at run time).
This can be done without restarting the application at runtime when Loading and Removing bean in Spring Application.

If the client code needs to register objects which are not managed by Spring container, then we will need to work with an instance of BeanDefinition.

A Spring application can register a BeanDefinition by using the following method of BeanDefinitionRegistry:

void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)

Here, We have used the following dependencies.
  •     Spring Context 4.3.4.RELEASE: Spring Context.
  •     JDK 1.8
  •     Maven 3.3.9
Spring - Dynamically register beans (At Run-Time)

How to Fix java.lang.UnsupportedClassVersionError

1. Introduction


In this article, We're going to learn how to fix the common runtime error java.lang.UnsupportedClassVersionError

From API: Thrown when the Java Virtual Machine attempts to read a class file and determines that the major and minor version numbers in the file are not supported.

How to Fix java.lang.UnsupportedClassVersionError?The simple cause is saying code is compiled at a higher version and running with lower java version. The solution is either run the code with the latest java version or compile the code with older JDK.

But let us see in detail what is the exact cause and how to fix it in various tools such as in command line, Eclipse and IntelliJ Idea tools.


[Fixed] Java was started but returned exit code=13 - Can't start Eclipse

Java was started but returned exit code=13 

1. Overview

In this tutorial, we''ll learn about the error while starting eclipse "Java was started but returned exit code=13" that can not start Eclipse and it's solutions.

Another similar error "java started but returned exit code 1" and same error can be seen with oxygen or neon "java started but returned exit code 13 eclipse neon" These are the common errors that we see frequently in our development process. Please see the following errors while starting up the eclipse after double click eclipse.exe file in eclipse location. 

Read more on "Troubleshooting" article.



[Fixed] Java was started but returned exit code=13 - Can't start Eclipse


We might be experiencing these errors after updating the java version or running OS or JAVA irrelevant eclipse versions.

1.1 Eclipse Error 

Java was started but returned exit code=13

We need to know about the following to solve these eclipse start up errors. All these are discussed in the further of this post.

1) Java version installed with os bit
2) Eclipse bit version
3) What is the problem coming while starting eclipse.

2. How to check java version installed

To check the java version that you are currently using, Open command prompt (cmd) using "windows + r" then then type "cmd" then command prompt appears in a new window as following.


java -version 

output:


D:\blogger>java -version
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) Client VM (build 25.131-b11, mixed mode)



[Fixed] Java was started but returned exit code=13 - java version



3. OS and Eclipse Bit Verification


We must know on which bit os is running on windows whether it is 32 bit or 64 bit and the same for eclipse whether 32 bit or 64 bit eclipse.

3.1 To know which Java bit is installed on Windows 64 bit OS

First way to check, Just see that where your java is installed in your C drive. Following are folder names. Check which directory your java installed.

Program Files (x86): This is the folder where
64-bit Windows places 32-bit programs.

Program Files: This is the folder where 64-bit Windows places
64-bit programs.

So, If your java is in  folder "Program Files (x86)" then java is 32 bit or If your java is in "Program Files" then it is java is 64 bit.

3.2 Finding the eclipse version of bitness (32 bit or 64 bit)


Second way to check the eclipse version in the location D:/eclipse/plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20120913-144807.

If you see the file name like this having "win32.x86_64" then downloaded eclipse is 64 bit or file name has "win32.x86_1.1" then eclipse is 32 bit.

3.3 eclipse.ini


Last way is Open the file eclipse.ini at eclipse root location.



plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.500.v20170531-1133 --> 32 bit.

plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20120913-144807 --> 64 bit



4. Possible errors

If there is any compatibility issues between java and eclipse then the following errors are supposed to be happen.

Java was started but returned exit code=13 - Can't start Eclipse is commonly faced by most of the developers.

4.1 Error 1


!SESSION 2017-08-06 18:47:46.019 -----------------------------------------------
eclipse.buildId=M20130204-1200
java.version=1.8.0_131
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_IN
Framework arguments:  -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product

!ENTRY org.eclipse.osgi 4 0 2017-08-06 18:47:53.020
!MESSAGE Application error
!STACK 1
java.lang.UnsatisfiedLinkError: Cannot load 64-bit SWT libraries on 32-bit JVM
    at org.eclipse.swt.internal.Library.loadLibrary(Library.java:260)
    at org.eclipse.swt.internal.Library.loadLibrary(Library.java:240)
    at org.eclipse.swt.internal.C.(C.java:21)
    at org.eclipse.swt.widgets.Display.(Display.java:138)
    at org.eclipse.ui.internal.Workbench.createDisplay(Workbench.java:653)
    at org.eclipse.ui.PlatformUI.createDisplay(PlatformUI.java:161)
    at org.eclipse.ui.internal.ide.application.IDEApplication.createDisplay(IDEApplication.java:154)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:96)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1414)

4.2 Error 2


java was started but returned exit code=13
C:\Program Files (x86)\Java\jre7\bin\javaw.exe
-Xms40m
-Xmx512m
-XX:MaxPermSize=256m
-jar C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher_1.30v20120522-1813.jar
-os win32
-ws win32
-arch x86_64
-showsplash C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins\org.eclipse.platform_4.2.0.v201206081400\splash.bmp
-launcher C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\eclipse.exe
-name Eclipse
--launcher.library C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v201205221813\eclipse_1503.dll
-startup C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher_1.30v20120522-1813.jar
--launcher.overrideVmargs
-exitdata 1e30_5c
-vm C:\Program Files (x86)\Java\jre7\bin\javaw.exe
-vmargs
-Xms40m
-Xmx512m
-XX:MaxPermSize=256m
-jar C:\Program Files\Eclipse-SDK-4.2-win32-x86_64\eclipse\\plugins/org.eclipse.equinox.launcher_1.30v20120522-1813.jar


5. Fix to Java was started but returned exit code=13 


How to fix the errors:

The following solutions work for both errors.

5.1 Solution 1

Working combinations of OS, JDK and eclipse bitness (32 bit or 64 bit). In your case, if you were using 64-bit JDK with 32-bit eclipse in a 64-bit OS, after downgrading JDK to 32-bit then eclipse will start working.

It's good to use one of the following combinations.

32-bit OS , 32-bit JDK , 32-bit Eclipse (32-bit only)
64-bit OS , 32-bit JDK , 32-bit Eclipse
64-bit OS , 64-bit JDK , 64bit Eclipse (64-bit only)

This solution should work but it is tricky. You should know the versions as described above.


5.2 Solution 2

If java is configured wrongly in Eclipse.ini file in the eclipse directory.

Eclipse.ini file must have a valid absolute java location. If you have installed many java version, select right version that compatible to the current eclipse.

-vm 
C:\Program Files (x86)\Java\jdk1.8.0_201\bin\javaw.exe



If OS is 32 bit then java and eclipse version also should be 32 bit.  Please make sure, you are having all 32 bit version.

If OS is 64 bit then there might be a chance of having two java versions 32 bit and 64 bit.

Check your eclipse version then open file "eclipse.ini" in eclipse root folder and add the following to it.


For 32 bit eclipse --> add "-vm C:\Program Files (x86)\Java\jre1.8.0_131\bin\javaw.exe"
For 64 bit eclipse --> add "-vm C:\Program Files\Java\jre1.8.0_131\bin\javaw.exe"

From eclipse.ini file:

After adding -vm arguement.

--launcher.appendVmargs
-vm 
C:\Program Files (x86)\Java\jdk1.8.0_201\bin\javaw.exe
-Dosgi.requiredJavaVersion=1.8
-Dosgi.instance.area.default=@user.home/eclipse-workspace
-XX:+UseG1GC



-vm -javaw.exe Java was started but returned exit code=13

Note: Check the location on your machine where the java installed.

5.3 Solution 3

By default, eclipse refers to the java version which is present in "PATH" variable. If you have non compatible java path is added to "PATH" then above two solutions may not work.

Please add the correct java version location or remove from "PATH".

Note: Once you are able to launch Eclipse, make sure you verify the installed JRE location under Java --> Installed JREs in the Preferences window.

Download the latest eclipse version from the official link here. (Luna, Mars, Neon, Oxygen)


New eclipse package includes

    Data Tools Platform
    Git integration for Eclipse
    Eclipse Java Development Tools
    Eclipse Java EE Developer Tools
    JavaScript Development Tools
    Maven Integration for Eclipse
    Mylyn Task List
    Eclipse Plug-in Development Environment
    Remote System Explorer
    Code Recommenders Tools for Java Developers
    Eclipse XML Editors and Tools

6. Conclusion


In this tutorial, We've seen what are the common issues that occur when we start eclipse. Most common issues are

1. java was started but returned exit code=13
2. Cannot load 64-bit SWT libraries on 32-bit JVM


Discussed what are the things needs to be checked on the initial steps and provided all possible solutions. This tutorial will provide the accurate solutions for eclipse issues.

If these are not helping, Please post your exact error what your getting in your case. We will provide you the fix.

References:

TheCrazyProgram Fix
JavaHungry Answers
StackOverFlow

Grep - Print N Lines Before and After Match: Unix Command

1. Grep Overview

In this tutorial, We'll learn how to print before and after grep command results content for each match in UNIX.

In my work some days back, I was using a UNIX grep command on the log file. My job is to find the exceptions in the log file and get the complete exception stack trace. But when we do the following command returns only the line that matches the Exception word.

grep 'Exception' apllication.log


After doing research on grep command, found useful flags that are very helpful. Before that just see the useful use case.

Print Before and After Lines Using Grep

Thursday, March 19, 2020

How to add Integer Values to ArrayList, int array Examples

1. Introduction


In this tutorial, We'll learn an ArrayList problem of how to add integer values to an ArrayList. Let us write an example program to add primitive int values and wrapper integer objects.


In the previous articles, we have discussed how to remove duplicate values in ArrayList.

In the next article, We'll learn How to Iterate ArrayList values?

How to add Integer Values to ArrayList, int array Examples

Monday, March 16, 2020

Java Switch Expressions Examples (+Java 13, 12 Vs All Java Older Versions Switch Programs)

1. Introduction


In to days article, We'll learn what is new Java 13 switch expression with example programs. In Java 13, the JEP 354: Switch Expressions extends the previous Java 12 Switch Expressions by adding a new yield keyword to return a value from switch expression. This makes the code so clear and more readable now.

This feature is part of preview features and disabled by default. This needs to be enabled for usage.

Java Switch Expressions Examples (+Java 13, 12 Vs All Java Older Versions Switch Programs)

Tuesday, March 10, 2020

Java Program to Check if a String is Number or contains at least one digit

Check If a String Is Numeric in Java

In this program, you will learn different techniques to check if a string is numeric or not in Java. Check if a String contains numbers Java.

Recommend is to isDigit() method gives the best results. while using a regular expression you may see performance issues because the first parser has to be compiled and executed.

Java Program to Check if a String is Numeric

Java Program To Count Duplicate Characters In String (+Java 8 Program)

1. Introduction


In this article, We'll learn how to find the duplicate characters in a string using a java program. This java program can be done using many ways. But, we will focus on using the Brute-force search approach, HashMap or LinkedHashMap, Java 8 compute() and Java 8 functional style.

Time complexity will be O(n) for brute force, for others will be O(nlogn).

At last, But important to know how to handle the Unicode characters. For this problem statement solution, New Java 8 String api provided the solution with the codepoints concepts.

Let us start with the HashMap first.

Coming to the problem statement, We have to find how many times each is repeated in the input string. The input may contain special characters such as '!', '#', '@', '$'.. etc. All characters must be handled by the algorithm.

Java Program To Count Duplicate Characters In String (+Java 8 Program)


Java Program To Reverse Words In String (Reverse only words in input order)

1. Overview


In this tutorial, We'll learn how to reverse the words in a string in java. The solution to this problem can be done using the StringBuilder class and using java 8 stream concepts. Many developers will be confused about whether word order needs to be reversed or each word should be reversed. You should clear on this with the interviewer. This will give a hint to the interviewer that the candidate is thinking and coming with a questionnaire.

But in this article, we will be reversing each word as it appears the order in the input as below.

Example:

String input = "Welcome to the JavaProgramTo.com blog"

Output:

emocleW ot eht moc.oTmargorPavaJ golb 

We recommend trying to solve the problem without seeing the answers. Once you come up with your own algorithm then see the different answers.

Java Program To Reverse Words In String (Reverse only words in input order)


Thursday, March 5, 2020

Java Strings - Common Working Examples and Interview Programs

1. Introduction


In this tutorial, We'll learn more about Java Strings. without String usage, there is no application in the java world. Java Strings are very crucial in defining the properties in the model classes. Java String is part of java.lang package. String class is getting added with new methods in java 8, 11, 12 versions. String API has a lot of utility methods.

In this article, we will be exploring different scenarios where String is being used always.



Java Strings - Common Working Examples and Interview Programs

Tuesday, March 3, 2020

Java 8 MinguoDate API Examples

1. Overview


In this tutorial, We'll be learning MinguoDate introduced in Java 8. This class is immutable and thread-safe. So, it can be used in multithreaded applications without explicit synchronization.

This date operates using the Minguo calendar. This calendar system is primarily used in the Republic of China, often known as Taiwan. Dates are aligned such that 0001-01-01 (Minguo) is 1912-01-01 (ISO).

Java 8 MinguoDate API Examples


Below is the class MinguoDate internal declaration in the api source code.

public final class MinguoDate
extends Object
implements ChronoLocalDate, Serializable

Now, We'll see the example programs to convert localdate to MinguoDate and from MinguoDate to local date.

2. Example to convert local date to MinguoDate


To convert the current date to the Minguo date, just subtracts the current year with number 1911, for example, 2019 (ISO) - 1911 = 108 (Minguo ROC)

package com.java.w3schools.blog.java8.date.time.api;

import java.time.LocalDate;
import java.time.chrono.MinguoDate;

/**
 * Example to convert local date to MinguoDate
 * 
 * @author venkatesh
 *
 */
public class MinguoDateToLocalDateExample {

 public static void main(String[] args) {

  LocalDate localDate = LocalDate.of(2025, 5, 7);
  MinguoDate minguo = MinguoDate.from(localDate);
  System.out.println("LocalDate 1: " + localDate); // 2025-05-07
  System.out.println("MinguoDate 1: " + minguo); // 114-05-07

  LocalDate localDate2 = LocalDate.of(2030, 5, 7);
  MinguoDate minguo2 = MinguoDate.from(localDate2);
  System.out.println("LocalDate 2: " + localDate2); // 2025-05-07
  System.out.println("MinguoDate 2: " + minguo2); // 114-05-07

 }

}

Output:

LocalDate 1: 2025-05-07
MinguoDate 1: Minguo ROC 114-05-07
LocalDate 2: 2030-05-07
MinguoDate 2: Minguo ROC 119-05-07

3. Example to convert MinguoDate to localdate


package com.java.w3schools.blog.java8.date.time.api;

import java.time.LocalDate;
import java.time.chrono.MinguoDate;

/**
 * Example to convert local date to MinguoDate
 * 
 * @author venkateshn
 *
 */
public class LocalDateToMinguoDateExample {

 public static void main(String[] args) {

  System.out.println("Example One");
  MinguoDate minguo1 = MinguoDate.of(108, 7, 15);
  // LocalDate localDate = LocalDate.ofEpochDay(minguo2.toEpochDay());
  LocalDate localDate1 = LocalDate.from(minguo1);
  System.out.println("MinguoDate 1: " + minguo1); // 108-07-15
  System.out.println("LocalDate 1: " + localDate1); // 2019-07-15

  System.out.println("\nExample Two");
  MinguoDate minguo2 = MinguoDate.of(108, 7, 15);
  // LocalDate localDate = LocalDate.ofEpochDay(minguo2.toEpochDay());
  LocalDate localDate2 = LocalDate.from(minguo2);
  System.out.println("MinguoDate 2: " + minguo2); // 108-07-15
  System.out.println("LocalDate 2: " + localDate2); // 2019-07-15

 }
}

Output:

Example One
MinguoDate 1: Minguo ROC 108-07-15
LocalDate 1: 2019-07-15

Example Two
MinguoDate 2: Minguo ROC 108-07-15
LocalDate 2: 2019-07-15

4. MinguoDate API methods


Few MinguoDate API methods with example.

now(): Obtains the current MinguoDate from the system clock in the default time-zone.
minus(long amountToAdd, TemporalUnit unit): Returns an object of the same type as this object with an amount subtracted.
plus(long amountToAdd, TemporalUnit unit): Returns an object of the same type as this object with an amount added.
with(TemporalAdjuster adjuster): Returns an adjusted object of the same type as this object with the adjustment made.

Full article on "java 8 TemporalAdjusters"

Example:


/**
 * 
 * MinguoDate now(), minus(), plus(), with() methods
 * 
 * @author venkateshn
 *
 */
public class MinguoDateExample {

 public static void main(String[] args) {

  LocalDate localDate = LocalDate.now();
  System.out.println("Local Date : " + localDate);

  MinguoDate minguoDate = MinguoDate.now();
  System.out.println("Current MinguoDate : " + minguoDate);

  MinguoDate minusDate = minguoDate.minus(10, ChronoUnit.DAYS);
  System.out.println("Minus 10 days date : " + minusDate);

  MinguoDate plusDate = minguoDate.plus(10, ChronoUnit.DAYS);
  System.out.println("Plus 10 days date : " + plusDate);

  MinguoDate firstDayOfNextMonth = minguoDate.with(TemporalAdjusters.firstDayOfNextMonth());
  System.out.println("First day of next month date : " + firstDayOfNextMonth);

 }

}

Output:

Local Date : 2019-08-15
Current MinguoDate : Minguo ROC 108-08-15
Minus 10 days date : Minguo ROC 108-08-05
Plus 10 days date : Minguo ROC 108-08-25
First day of next month date : Minguo ROC 108-09-01


5. Conclusion


In this post, We've seen how to use MinguoDate api.

Shown examples on to convert local date to MinguoDate and MinguoDate to localdate.

API useful methods to manipulate with date (now(), minus(), plus(), with()).

GitHub
MinguoDate API Ref