DronaBlog

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, January 3, 2024

Configuring Java Version with the -vm Argument: A Comprehensive Guide

 Introduction:

Java applications are widely used across various industries and platforms, and ensuring the correct Java version is crucial for optimal performance and compatibility. One way to specify the Java version for your application is by using the -vm (Virtual Machine) argument. This article will guide you through the process of adding the -vm argument to ensure your Java application runs on the desired Java version.





Understanding the -vm Argument:

The -vm argument allows you to specify the Java Virtual Machine (JVM) executable that your application should use. This is particularly useful when you have multiple Java installations on your system, and you want to ensure that your application runs on a specific version.

Step-by-Step Guide:

  1. Identify the Java Version:

    • Before adding the -vm argument, you need to identify the path to the Java executable of the desired version on your system. You can do this by running the following command in the terminal or command prompt:

    • java -version

    • Note the installation path of the desired Java version.


  2. Locate Eclipse.ini or STS.ini (for Eclipse-based IDEs):

    • If you are using an Eclipse-based IDE like Eclipse or Spring Tool Suite (STS), locate the configuration file named eclipse.ini or STS.ini. This file is usually found in the root directory of your IDE installation.
  3. Edit the Configuration File:

    • Open the eclipse.ini or STS.ini file in a text editor of your choice.

  4. Add the -vm Argument:

    • Add the following lines to the configuration file, replacing the path with the actual path to the Java executable of the desired version:

    • -vm /path/to/java/executable

    • Make sure to add these lines before any other -vmargs or -XX options in the file.


  5. Save and Restart:

    • Save the changes to the configuration file and restart your IDE.





  6. Verify the Configuration:

    • After restarting the IDE, verify that it is using the correct Java version by checking the version information in the IDE or running the following command:

    • java -version

    • Ensure that the displayed version matches the desired Java version.


Configuring the Java version for your application using the -vm argument is a straightforward process that ensures your code runs on the intended Java Virtual Machine. Whether you are working on an Eclipse-based IDE or another Java development environment, following these steps will help you set up the correct Java version for your projects, avoiding compatibility issues and ensuring optimal performance.





Thursday, November 9, 2023

What is JMS (Java Message Service) ?

JMS, or Java Message Service, is a Java-based API that allows applications to create, send, receive, and read messages in a loosely coupled, reliable, and asynchronous manner. It's commonly used for communication between distributed systems or components.



Here's a brief overview of how JMS works: Messaging Models:

  • JMS supports two messaging models: Point-to-Point (P2P) and Publish/Subscribe (Pub/Sub).
  • P2P involves sending messages to a specific destination where only one consumer can receive the message.
  • Pub/Sub involves sending messages to a topic, and multiple subscribers can receive the message.

Components:

  • JMS involves two main components: Message Producers and Message Consumers.
  • Message Producers create and send messages to a destination.
  • Message Consumers receive and process messages from a destination.

Connections and Sessions:

  • JMS uses ConnectionFactory to establish a connection to a JMS provider (like a message broker).
  • Sessions are created within a connection to manage the flow of messages. They provide a transactional boundary for message processing.

Destinations:

  • Destinations represent the place where messages are sent or received. In P2P, it's a queue, and in Pub/Sub, it's a topic.

Messages:

  • JMS messages are used to encapsulate data being sent between applications. There are different types of messages, such as TextMessage, ObjectMessage, etc.

Message Listeners:

  • Message Consumers can register as message listeners to asynchronously receive messages. When a message arrives, the listener's onMessage method is invoked.

Acknowledgment:



  • Acknowledgment is the mechanism by which the receiver informs the JMS provider that the message has been successfully received and processed.

Transactions:

  • JMS supports transactions, allowing multiple messaging operations to be grouped together. Either all operations succeed, or they all fail.

JMS provides a flexible and robust way for Java applications to communicate through messaging, facilitating reliable and asynchronous communication between different components in a distributed system.

Learn more about Java here




Wednesday, April 5, 2023

What is Bug, Error and Issue?

In the world of software development, terms like "bug," "error," and "issue" are often used interchangeably. However, there are subtle differences between these terms that can be important to understand, especially when communicating with other developers or stakeholders. In this article, we'll explore the differences between these three terms and how they relate to software development.






A. Bug:

A bug is a defect or flaw in the software that causes it to behave in an unintended way. This can result from a coding mistake or a problem with the software's design. Bugs can range in severity from minor glitches to major issues that prevent the software from working at all. They are typically discovered during testing or after the software has been released and are often fixed by the development team through a software update or patch.


B. Error:

An error is a mistake made by a programmer during the coding process. Errors can be syntax errors, where the code does not conform to the language's rules, or logic errors, where the code does not perform the intended function. Errors can occur during development or after the software has been released and can lead to bugs or other issues. Programmers can use debugging tools to identify and fix errors in their code.


C. Issue:

An issue is a problem or challenge that arises during the software development process. Issues can include bugs, errors, or other obstacles that affect the software's functionality, performance, or usability. Issues can also arise from external factors, such as hardware or network problems. Tracking issues is an important part of software development, as it allows developers to identify areas for improvement and ensure that the software meets the needs of its users.






In summary, bugs, errors, and issues are all related to software development, but they represent different aspects of the process. Bugs are defects in the software that cause unintended behavior, errors are mistakes made during the coding process, and issues are problems or challenges that arise during development. Understanding these differences can help developers communicate more effectively and improve the quality of their software. 


Learn more



Tuesday, January 24, 2023

What is Null Pointer Error in Java and How to fix it?

Are you looking for what is best way to fix Null Pointer error in your Java code? Are also would like to know what causes Null Pointer error. If so, then you reached at right place. In this article, we will understand what is root cause of Null Pointer error and how to fix it. Let's start.


 A null pointer error, also known as a "null reference exception," occurs when a program attempts to access an object or variable that has a null value. In other words, the program is trying to access an object that doesn't exist. This can happen when a variable is not initialized or is set to null, but the program tries to access it as if it has a value.






The error message will typically indicate the specific location in the code where the error occurred, and it will look something like this: "java.lang.NullPointerException at [classname].[methodname]([filename]:[line number])".


There are several ways to fix a null pointer error, but the most common solution is to check for null values before trying to access an object. This can be done by using an if statement to check if the variable is null, and if so, assign a value to it or handle the error in a specific way.


Another way is to use the "Optional" class introduced in Java 8, it allows to avoid null pointer exceptions. It can be used with any type of variable and it wraps the variable and it can check if it's present or not.


For example, if the error occurs when trying to access an object called "objectName," the following code can be used to fix it:


if (objectName != null) {

    // code to access objectName

} else {

    // handle the error or assign a value to objectName

}






Additionally, you should check that the objects that you're using are not null, it's also important to check that the objects that the object you're using is not null. To avoid this error, it's important to initialize variables and objects properly and to be aware of the scope of the variables and objects that you're using in your code.

In summary, a null pointer error occurs when a program tries to access an object or variable that has a null value. The error can be fixed by checking for null values before trying to access an object and handling the error properly. It is important to initialize the variables and objects properly, check for the scope of the variables and objects, and to be aware of the potential of null values.

Learn more about Java usage here-




Wednesday, January 4, 2023

How to connect to Database in Java?

 To connect to a database using Java, you will need to use the JDBC (Java Database Connectivity) API. This API provides a standard set of interfaces for connecting to a database, executing queries, and processing the results.





 

Here is an example of Java code that demonstrates how to connect to a database using JDBC:

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

 

public class DatabaseConnection {

 

    public static void main(String[] args) {

 

        // Load the JDBC driver

        try {

            Class.forName("com.mysql.jdbc.Driver");

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

            return;

        }

 

        // Establish a connection to the database

        Connection connection = null;

        try {

            connection = DriverManager.getConnection(

                "jdbc:mysql://localhost:3306/mydatabase", "username", "password");

        } catch (SQLException e) {

            e.printStackTrace();

            return;

        }

 

        // Do something with the connection, such as executing a query

        // (omitted for brevity)

 

        // Close the connection

        try {

            connection.close();

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

 

 





In this example, we first load the JDBC driver for MySQL using the Class.forName() method. Then, we use the DriverManager.getConnection() method to establish a connection to the database. Finally, we close the connection using the Connection.close() method.

 

Note that this example uses MySQL as the database, but you can use a different database by simply changing the JDBC driver class and the connection URL. You will also need to provide the appropriate username and password for the database.

Saturday, November 6, 2021

What is difference between HTTPS , SSL and TLS ?

                  Are you looking for details about HTTPS protocol? Are you also interested in knowing the differences between HTTPS, SSL, and TLS? If so, then you reached the right place. In this article, we will learn more about HTTPS, SSL, and TLS. Let's start.


A) Understand the speed of the data 

               The data sent over the internet is very fast. It is faster than traditional channels such as wires, optic fiber, air. It will not be an exaggeration if we say data send over the internet with speed of light. Even speed of data sent over the internet is fast, but it still has to go through multiple devices during its journey over the network and that is where criminals target data.






B) What is HTTPS?

                The internet consists of distributed client and server information systems. When we access any application using a computer or mobile or any other type of device, ( these devices act as the client ) we send the request to the server. The server can accept or reject the request. If the request is accepted then a connection is created over a specific protocol. In order to establish a communication set of rules which are implemented with the protocol.

                 HTTP stands for Hypertext Transfer Protocol used on the worldwide web(www). This commonly used protocol defines 

                                   1. How data is formatted

                                   2. What type of data is to be transmitted 

                                   3. How the server should respond to the specific command 

                  However, HTTP is not secure as it does not have data encryption and authentication functionalities. In order to achieve security especially transmitting data over the network, Hypertext Transfer protocol secure (HTTPS) protocol can be used.

                                  Though HTTPS is a safer solution for the client and server models, this added security isn't automatic. In order to maintain security standards, we need to purchase SSL/TLS certificates from a trusted certificate authority.


C) What is SSL? 

                The SSL stands for Secure Socket Layer. The internet connections are maintained safely by SSL encryption and decryption method. These connections can be between client to client or client to server or server to server. As SSL is an older protocol, the updated TLS was released in 1999 and it is being commonly used nowadays.






D) What is TLS?

                 TLS stands for Transport Layer Security. TLS is a cryptographic protocol used for achieving better privacy, data integrity, and authentication compared to SSL. It supports stronger, secure cipher suites and algorithms.

                TLS is more commonly used in computer networks, web browsing, instant messaging, email etc. 


                     Learn more about Java here 




Saturday, October 30, 2021

How does TLS or SSL Decryption work ?

              Would you like to know how does TLS or SSL decryption work? Would you be also interested in knowing Symmetric and Asymmetric cryptography? If so, then you reached the right place. In this article, we will explore decryption with TLS or SSL. Let's start.

A) What TLS or SSL? 

               As discussed in what is the difference between HTTPS, SSL, and TLS  ? article, TLS or SSL is a cryptographic protocol for achieving privacy, data integrity over the network.






B) How does TLS/SSL decryption work? 

               The TLS and SSL both use asymmetric cryptography. TLS /SSL provides reliable security with high performance.

                a) Symmetric Cryptography :

                     Symmetric cryptography uses a secret key to encrypt data. The generated secret key is shared with the sender and receiver. The secret key should be 128 bits in length in order to achieve security.

                 b) Asymmetric Cryptography :

                      Asymmetric cryptography uses private and public keys. The public and private keys are mathematically designed. It requires higher bandwidth. The key length should be a minimum of 1024 bits.

                c) Secure session key : 

                     The secure session key is generated by SSL /TLS by using asymmetric cryptography. The secure session key is used to decrypt and encrypt the data transmitted over the network. secure session the TLS handshake is achieved with the secure session key.






C) What TLS handshake? 

               The TLS handshake is a process to achieve communication between server and client to achieve the below Functionalities -

               1. Acknowledge one another 

               2. Verify each other's authenticity 

               3. Designate encryption algorithms 

               4. Agree on session keys. 




                

Tuesday, October 12, 2021

What are new feature in Java -17 part 2

                Are you interested in knowing what are the new featured introduced in Java 17? Are you also interested in knowing what are the deprecated features in Java 17? If so, then reached the right place. This is the second part of the feature in java 17. You can access the first part of the features of Java 17 here.

A) Introduction 

              In the previous article, we explored the Java 17 features such as JEP 412: Memory API and Foreign Function, JEP 411: Deprecate the Security  Manager, JEP 414: Vector API, JEP 415: Deserialization Filters.

             In this article, we will focus on the features below in Java 17 

           1. JEP 409: Sealed classes 

           2. JEP 406: Pattern Matching for switch 

           3. JEP 403: Strongly Encapsulate JDK internals 

           4. JEP 398: Deprecate Applet API for removal 





B ) JEP 409: Sealed classes 

            A sealed class that restricts other classes may extend it. This also applies to interface as well i.e a sealed class can be an interface that restricts another interface may extend it. 

           With Java 17, new sealed, non-sealed character sequences are introduced and it allows them as contextual keywords.






C ) JEP 406: Pattern Matching for switch 

             With this change, all existing expressions and statements compile with identical semantics. It performs then without any modification.

              There are two new patterns are introduced 

          1. Guarded Pattern: It is used to refine the pattern matching logic using a boolean expression 

          2. Parenthesized Pattern: It is used to get rid of parsing ambiguities 


D ) JEP 403: Strongly Encapsulate JDK internals 

             All the internal elements of JPK are strongly encapsulated. Here only exception is sun.misc.unsafe.


E ) JEP 398: Deprecate Applet API for Removal 

              As we know Applet APIs were deprecated since Java 9 but these were never removed. With Java 17, these will be removed there not be much impact because these Applet APIs are no longer in use as we use more advanced web technologies for it.


                    Learn more about Java here -

            


Sunday, October 10, 2021

What are new Features in Java 17 - Part 1

               Are you looking for detailed information about all the interesting features introduced in JDK 17? Are you also would like various terminologies such as LTS or JEP? If so, then you reached the right place. In this article, we will explore new features in JDK 17 release.

A) What is LTS in Java?

               LTS is an abbreviation for Long-term Support. It is a product life cycle management policy. With this policy, the software edition is supported longer than the software standard edition.






B) What is JEP in Java? 

               JEP is an abbreviation for JDK Enhancement Proposal. Oracle Corporation has drafted this process to collect proposals for enhancements to the Java Development kit i.e. JDK. 


C)  What are the new features in Java 17? 

                Java 17 is one of the major releases and comes with various interesting features. In this article we will explore the features below :

          1. JEP 411: Deprecate the security manager 

         2. JEP 412: Memory API and Foreign Function 

         3. JEP 414: Vector API

        4. JEP 415: Deserialization Filters


1 . JEP 411: Deprecate the security manager 

                  The security manager API which was used to define security policy for an Application is deprecated with JDK 17  release. The security manager is deprecated as this API is not commonly used. one of the basic features of a security manager is a blocking system:: exit. If applications continue to use the security manager then an alert message will be issued.





2. JEP 412: Memory API and Foreign function

                   With JEP 412 the new API is introduced and these are Foreign Memory Access API and the foreign linker API with these API'S we can invoke code outside of the JVM and also security access foreign memory Here, foreign memory means the memory which is not handled by JVM. 

3. JEP 414: Vector API 

                    These Vector APIs are part of JDK 16 are also enhanced in JDK 17 to express vector computations on supported CPU architecture at runtime. These are reliable for compilation and performance on AArch 64 and x64 architectures.

4. JEP 415: Deserialization Filters 

                    With a JVM-wide filter factory, we can allow applications to configure context-specific and dynamically selected deserialization filters. This will be helpful to prevent serialization attacks.


                      Learn more about Java here -



Tuesday, July 7, 2020

How to setup Task Reminder with Popup using Java in Windows System

In this article, we will see how to set up a Task reminder with Popup message in the Windows system. We need to have some basic understanding of Java and Windows shell scripting.





Step 1: Setup up Java project

Use any IDE e.g. Eclipse to create a Java project. We need below external jar files. Download the jar files below and set up in the classpath:



Step 2: Write Java class

Use below code snippet to read an excel file and show popup message using Jpanel class.


import java.awt.Graphics;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JPanel;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadFile extends JPanel {
public void paint(Graphics g){
ReadFile rc = new ReadFile(); // object of the class
// reading the value of 2nd row and 2nd column
ArrayList<String> vOutput = rc.ReadCellData(2, 5);
int k = 10;
if (vOutput != null) {
if (vOutput.size() <=0) {
g.drawString("No reminder today! Enjoy!!!", 10, k);
} else {
for (int i = 0; i < vOutput.size() ; i++) {
g.drawString(vOutput.get(i), 10, k);
k = k + 20;
}
}
}
}

public static void main(String[] args) {
JFrame frame= new JFrame("Customer Reminder!");
frame.getContentPane().add(new ReadFile());
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}

// method defined for reading a cell
public ArrayList<String> ReadCellData(int vRow, int vColumn) {
ArrayList<String> al = new ArrayList<>();
Workbook wb = null; // initialize Workbook null
try {
// reading data from a file in the form of bytes
FileInputStream fis = new FileInputStream("D:\\sample.xlsx");
// constructs an XSSFWorkbook object, by buffering the whole stream into the
// memory
wb = new XSSFWorkbook(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Sheet sheet = wb.getSheetAt(0); // getting the XSSFSheet object at given index
int j = 0;
for (int i = 1; i < 1000; i++) {
Row row = sheet.getRow(i); // returns the logical row
if (row != null) {
Cell cell = row.getCell(7); // getting the cell representing the given column
if (cell != null) {
Date dueDate = cell.getDateCellValue();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date currentDate=java.util.Calendar.getInstance().getTime();

if (dueDate != null && (dateFormat.format(dueDate)).equals(dateFormat.format(currentDate))) {
Cell customerName = row.getCell(6);
String custName = null;
if (customerName != null) {
custName = customerName.getStringCellValue();
}
Cell phoneNum = row.getCell(8);
String phone = null;
if (phoneNum != null) {
phone = phoneNum.getStringCellValue();
}
if (custName != null) {
al.add("Call: [ " + custName + " : " + phone + "] ");
}
}
}
}
}
return al; // returns the cell value
}

}

Step 3: Create a runnable jar file

Use Eclipse -> Export option to create Runnable jar file and name it as reminder_project.jar (You can provide any name)




Step 4: Create a batch file

Create CMD file with the content below

java -jar D:\reminder_project.jar

Step 4: Setup Task using Task Scheduler in Windows system


Use Task Scheduler in the Windows system. Provide the name of the task, Trigger details (daily, weekly), and Actions.




Provide CMD file name in the schedular





What is CRM system?

  In the digital age, where customer-centricity reigns supreme, businesses are increasingly turning to advanced technologies to manage and n...