Skip to main content

Posts

Showing posts from 2020

Error: Could not find or load main class in IntelliJ IDE 2020.1.3

 Error Could not find or load main class in IntelliJ IDE 2020.1.3 Solution Step 1 Right-click on the source folder  src (Normal Java projects) java ( Java Maven project) scala (Scala Maven projects) Step 2 Select Mark Directory As Step 3 Select Sources Root IntelliJ Mark Directory as Sources Root Hope this post helps you to solve your problem.

How to get the length of a Collection in the JSF expression language?

 Problem How to get the length of a Collection in the JSF expression language? Solution There are two ways to get the length of a Collection i.e. List, Set, etc in the JSF expression language a) Define a method in the Bean In your bean declare a method to return the length of a collection @Named("MyBean ") @SessionScoped public class MyBean {     private List list;     .     .     .     public int getCollectionLength() {       return  list.size();     } } b) Using Facelets,the length function #{ fn:length(MyBean.list) }

How to convert Enum to List of String in Java 8?

Problem  How to convert Enum to List of String in Java 8?  Solution  Using the Java 8 Streams, its map and collect functions we can convert Enum to List of Strings  Code   import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class EnumToStringList { public enum Alpha { A,B,C,D; }  public static void main(String[] args) { List<String> strings = Stream.of(Alpha.values()).map(                                               Alpha::name).collect( Collectors.toList()); } }

Java 13 - How to Concatenate Text Blocks

Introduction If you have not tried the Text Blocks feature introduced in Java 13 then the following post will help you to get started Java 13 - Example to use Text Blocks for Multi line String literals We can concatenate TextBlocks as we do with normal String as demonstrated in the following example. Example public class TextBlock { public static void main(String[] args) { String html = """             <html>                 <body>                  """ +                 """   <h1> Header One </h1>                 <p> Paragraph One </p>               """ +                 """                 <h1> Header One </h1>                 <p> Paragraph One </p>       """ +                """                 </body>              </html>                 """; S

Java 13 - Example to use Text Blocks for Multi line String literals

Introduction Lengthy Strings in Java code becomes hard to read. Multiline String literals can be XML, JSON, HTML, SQL queries, Hibernate or JPA queries, etc. Example String html = " <html>\r\n" + " <body>\r\n" + " <p>Hello, world</p>\r\n" + " </body>\r\n" + " </html>\r\n" ; Solution Thanks to the Text blocks feature introduced in Java 13. Now, these multiline String literals are more presentable in Java code. 1. Configuring Eclipse for Text Blocks 1.1 Requirments JDK 13 Eclipse Version: 2020-03 (4.15.0) 1.2 Eclipse Error 1 String literal is not properly closed by a double-quote 1.2.1 Solution Change the source of your program to 13 as shown in the following screenshot Java Source 13 1.3 Eclipse Error 2 Text Blocks is a preview feature and disabled by default. Use --enable-preview to enable 1.3.2 Eclipse Erro

JDK 14 - Target is not a JDK root. System library was not found.

Problem When I tried to add JDK 14 to my eclipse, the following error was shown Target is not a JDK root. System library was not found. Target is not a JDK root. System library was not found. My downloaded JDK folder was named as jdk-14 Solution I simply renamed my folder from jdk-14 to jdk-14.0 and it worked. The jdk 14 was successfully added to the Eclipse. Conclusion I t seems that sometimes Eclipse is not able to locate the jdk folder, renaming the folder refreshes the cache of Eclipse and then respective folder is located by Eclipse.

How to print XML inside div on HTML page?

Problem If you try to print the following XML on the HTML page, it will not be visible <website> <name>techieshah.com</name> <url>http://techieshah.com</url> </website> Solution Replace less than sign i.e. <   with  &lt; Replace greater than sign i.e. > with  &gt;

Java - How to print Hibernate query parameters on console?

Introduction In this post, we will learn how to print Hibernate Query parameters using log4j. Requirments log4j-api-2.13.1.jar log4j-core-2.13.1.jar Step 1 Place the above two log4j jars inside the lib directory. For web applications, the lib directory is located inside the WEB-INF folder. Step 2 Create a file by the name of  log4j2.xml and place it inside your src folder. Step 3 Place the following XML code inside the  log4j2.xml file <configuration status="WARN"> <appenders> <console name="LogToConsole" target="SYSTEM_OUT"> <patternlayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"> </patternlayout></console> </appenders> <loggers> <logger additivity="false" level="debug" name="org.myapp"> <appenderref ref="LogToConsole"> &

JQuery - Uncaught ReferenceError: $ is not defined at

Exception Uncaught ReferenceError: $ is not defined     at timer.js:14 Solution  Please make sure that JQuery JS file is added in the HTML file  JQuery JS file should be declared first than other JS files like <script src='https://code.jquery.com/jquery-3.4.1.min.js'></script>      <script src='js/app.min.js'></script> <script src='js/timer.js'></script>

Java - How to convert an array of bytes i.e. byte[] to String ?

Introduction In this post, we will explore how to convert an array of bytes i.e. byte[] to String in Java. For this functionality, we will use the following constructor of java.lang.String class String (byte[] bytes,  String  enc) Example import java.nio.charset.StandardCharsets; public class ByteArrayToString { public static void main(String[] args) { byte[] bytes = "a quick fox jumps over the lazy dog".getBytes(); // convert the bytes to String System.out.println("bytes = " + bytes); System.out.println( "bytes.toString() = " + bytes.toString()); String myString = new String ( bytes , StandardCharsets.UTF_8); System.out.println("myString = " + myString); } } Output bytes = [B@41a4555e bytes.toString() = [B@41a4555e myString = a quick fox jumps over the lazy dog Conclusion In this post, we learned how to convert an array of bytes to String.

Java - How to convert String to InputStream?

Introduction In this post, we will learn how to convert String to InputStream in Java. Example import java.io.ByteArrayInputStream; import java.io.InputStream; public class StringToInputStream { public static void main(String[] args) { String text = "A quick fox jumps over a lazy dog"; try ( InputStream inputStream = convertToInputStream(text) ) { //TODO you business logic goes here } catch (Exception e) { e.printStackTrace(); } } private static InputStream convertToInputStream(String text) throws Exception { return new ByteArrayInputStream(text.getBytes()); } } Conclusion This is the simplest and shortest way to convert a String to InputStream in Java.

Oracle 12 C - JDBC connection string to connect through Service Name

Introduction Mostly we make a connection to Oracle using JDBC through SID. Recently I have to make a connection to Oracle using Service Name. I am writing this post to share my experience. SID Connection String  jdbc:oracle:thin:@IP:1521:SID Service Name connection String  jdbc:oracle:thin:@(description=(address=(host=IP)(protocol=tcp)(port=1521))(connect_data=(service_name=UR_SERVICE_NAME))) Replace Service Name and host address per your configuration These strings work both for plain JDBC and hibernate. For hibernate configuration, put the above string inside <property name="connection.url">Above connection String</property> tag of hibernate.cfg.xml. Conclusion In this post, we learn how to connect to Oracle using both SID and Service Name. Happy learning

Java - How to convert InputStream to String?

Introduction In this tutorial, we will learn how to convert InputStream to String in Java. Example import java.io.InputStream; import java.net.URL; public class InputStreamToString { public static void main(String[] args) { //very frequent asked question in interview , regarding closable interface try(InputStream inputStream = new URL("https://www.oracle.com/index.html").openStream()){ System.out.println(convertToString(inputStream)); }catch (Exception e) { // TODO: handle exception } } private static String convertToString(InputStream inputStream) throws Exception{ return new String(inputStream.readAllBytes()); } } Conclusion Above example is the simplest method to convert an Inpustream to String in Java. There are alternate solutions available like using commonio jar and converting InputStream to ByteStream etc. Hope you enjoy this tutorial. Happy learning 

Java - How to escape % in String.format?

Introduction In this tutorial, we will learn how to skip or display % in a String using String.format MyStringFormatter .java  public class MyStringFormatter { public static void main(String[] args) { System.out.println(String.format( "Your score is %d % " ,65) ); } } Output Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = ' ' at java.base/java.util.Formatter.checkText(Formatter.java:2732) at java.base/java.util.Formatter.parse(Formatter.java:2718) at java.base/java.util.Formatter.format(Formatter.java:2655) at java.base/java.util.Formatter.format(Formatter.java:2609) at java.base/java.lang.String.format(String.java:2897) at MyStringFormatter.main(MyStringFormatter.java:4) Solution To display a % in String when using String.format , you have to escape a % with % i.e. %% public class MyStringFormatter { public static void main(String[] args) { System.out.println(String.fo

spark-submit java.lang.NoClassDefFoundError: scala/runtime/java8/JFunction1$mcII$sp

Exception  Exception in thread "main" java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: scala/runtime/java8/JFunction1$mcII$sp         at SparkPi$.main(SparkPi.scala:14)         at SparkPi.main(SparkPi.scala)         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) Problem: It seems that you have compiled and generated your jar file with an upper version of the Scala compiler than the one spark is using. Solution Step 1 Run the following command from spark-installed-directory\bin spark-shell.cmd (or.sh) and note the Scala version, My Spark version was 2.4.3 and Scala version 2.11.12 Step 2 Change the scala version into your build.sbt to 2.11.12 (per your configuration). My build.sbt is name := "SparkPi Project" version := "1.0" scalaVersion := "2.11.12" val sparkVersion = "2.4.5&qu

Set default JAVA_HOME path for Apache Spark

Introduction  Currently, Apache Spark does not support JAVA 11 and later versions. When you try to run the Spark application, you may get the following exception Exception pyspark.sql.utils.IllegalArgumentException: 'Unsupported class file major version 55' Solution There are different ways to fix this exception like Set environmental variable for JAVA_HOME Modify Apache spark environment configuration file i.e. spark-env.sh or spark-env.cmd In this post, I will help you to set JAVA_HOME using Spark's configuration file Windows Environment  Go to the spark-directory\ conf Create a file by the name of spark-env.cmd  Paste the following line spark-env.cmd                   set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_201 Linux and Mac Go to the spark-directory\ conf Open spark-env.sh Paste the following line spark-env.cmd        export JAVA_HOME=$(user/Java/jdk1.8.0_201 -v 1.8) Note : Change the installed Java directory accordingly.