Skip to main content

Posts

Showing posts with the label java

Gradle : How to make a custom War file

Points to Remember War task extends Jar You can create war files with any configuration defined in configurations { } closure You can also add files to an existing war file. You can select the files that needs to be included or excluded while creating a war file How to create a War file in Gradle To create a war file you have to create a task of type War as shown below // include java plugin apply plugin : 'java' task createWar(type : War){ destinationDir = file ( "$buildDir" ) baseName = "my-war" version = "1.1" caseSensitive = true classifier = "SNAPSHOT" from "src" } Run the above task with command gradle -q createWar , this will create a war file named my-war-1.1-SNAPSHOT.war in the build folder. See Full Documentation of War Task How to create a War file and exclude some files Now ...

Java 9 : How to Terminating or Destroy a Running Process

Points To Remember You cannot destroy or terminate the current process not even forcefully. You can destroy a process by using the methods destroy() or forcefully using destroyForcibly() . Read More Java 9 Feature List all processes running on the OS Get the information of the current process Start a new Process and get its Process Id How to get Process Information from Process Id Destroy a running process Destroy a Process There are two methods in interface ProcessHandle that can be used to destroy a process. destroy() - to destroy a process noramally destroyForcibly() - to destroy a process forcefully. However the process may not be terminatted instantly since operating system access controls may prevent the process from being killed thus resulting in case where isAlive() method may return true for a brief period after destroyForcibly() is called. In the example below we will first create a process and then kill it forcefully. import java.io.IOException; import java.lang.Pro...

Java 9 : How to get Process Information from Process Id in Java

Points to Remember You need to run this code with Java 1.9 ProcessHandle.of(Long processId) method will return an object of Optional<ProcessHandle> . Optional is a class introduced in java 8 which is a container object which may or may not contain a non-null value . It has methods boolean isPresent() which returns true if a value is present else returns false. T get() method returns the object if present or else throws NoSuchElementException . Read More Java 9 Feature List all processes running on the OS Get the information of the current process Start a new Process and get its Process Id How to get Process Information from Process Id Destroy a running process Get Process Information from Process Id If we have the process id of a process, then we can get the information about the process as shown in the following code. import java.io.IOException; import java.lang.ProcessHandle; import java.lang.Process; /** * @author ekiras */ public class DestroyProcess { publ...

Java 9 : How to start a new Process and get process id

Points to Remember This post used Java 1.9 since ProcessHandle was introduced in Java 1.9. Read More Java 9 Feature List all processes running on the OS Get the information of the current process Start a new Process and get its Process Id How to get Process Information from Process Id Destroy a running process Get the Current Process Information. In this example we will try to get information about the current process. For this we will use the m import java.io.IOException; /** * @author ekiras */ public class StartProcess { public static void main (String[] args) { try { Process process = startProcess( "tail -F /dev/null" ); printProcessInfo(process.toHandle()); } catch (IOException e) { e.printStackTrace(); } } public static void printProcessInfo (ProcessHandle processHandle) { System.out.println( "---Process Info---" ); System.out.println( " Process Id :...

Java 9 : How to get Current Process Information

Points to Remember Java 9 introduced the new Process Api in java.lang package. ProcessHandle interface can be used to perform operations with processes like start, destroy, list processes. Read More Get the information of the current process Create a new process and then terminate it Terminating the current process Destroy a process forcefully Get children of a process Get the Current Process Information. In this example we will try to get information about the current process. For this we will use the method ProcessHandle.current() method, this will return the object ProcessHandle which can be used to get the information of the process. import java.io.IOException; import java.lang.ProcessHandle; /** * @author ekiras */ public class CurrentProcess { public static void main (String[] args) throws IOException { currentProcessInfo(); } public static void currentProcessInfo () { System.out.println( "Current Process : " ); ...

Java 9 : How to list all processes running on the OS

Points to Remember Java 9 introduced the new Process Api in java.lang package. ProcessHandle interface can be used to perform operations with processes like start, destroy, list processes. Read More Java 9 Feature List all processes running on the OS Get the information of the current process Start a new Process and get its Process Id How to get Process Information from Process Id Destroy a running process List all Processes running on the OS. To get all the processes running on the OS you can use the static method allProcesses() of the ProcessHandle , this will return a Stream<ProcessHandle> stream of process handles which can be used to get information about each process. The below example shows how we can list all the running processes. import java.lang.ProcessHandle; import java.util.stream.Stream; /** * @author ekiras */ public class ListAllProcesses { public static void main (String[] args) { allProcesses(); } public static void allPr...

Java 9 : How to use Java 9 Process Api

Introduction to Java 9 Process Api The New Java 9 Processes API will help provide Identifies the processess Control of Native processes Monitoring of processes List Children of processess Start a new Process Destroy a running process Access to the process input,output and error streams. On Exit Handle when a process is destroyed or completed. Testing Process API operations In this post java program we are testing the following operations List all processess running in the OS. Print the information of the current process. Create a new process and then terminate it. Do some action when the process is destroyed or completed. Try to terminate the current process. Destroy a process forcefully Get children of a process. List all Processess ProcessHandle.allProcesses() is a static method in ProcessHandle interface that returns Stream<ProcessHandle> object. We will iterate this stream to print the information of all the processess running. package com.ekiras.java9.processapi; import ...

Java : How to create a Jar with single or multiple files

How to create a jar file. We can make a jar file with a single class using the following commands Here can be replaced by the name of the jar file you want. 1. Create a jar file with single file jar --create --file=<FileName> <file-1> 2. Create a jar file with multiple files jar --create --file=<FileName> <file-1> <file-2> 3. Create a jar file with all files in a directory jar --create --file="<FileName> -C /path/to/dir/ ." Here -C specifies the directory and . specifies that it need to include all the files in te directory. Some of the shorthands for the above commands Option Shorthand --create -c --file -f --module-path -p --verbose -v --list -t --extract -x How to extract a jar file jar -xf <FileName> How to list the contents of a jar file jar -tf <FileName>

Design Patterns : Builder Pattern

Points To Remember It is a Creational Design Pattern It must be used when you have multiple overloaded constructors or setters Its main purpose it to hide from the user, how the object is to be created . It is advised to make your constructors private when you are using Builder Design Pattern. What is Builder Design Pattern It is a creational design pattern. So it is only responsible for how an object must be created. There may be scenarios where there is a class with many instance variables that may be needed to create an object of the class. For this you might have to create many overloaded constructors. For Example we have a class NutritionFacts that has following instance variables private int servingSize; private int servings; private int calories; private int fat; private int sodium; private int carbohydrate; Then to create the object of the class we can have constructors as follows NutritionFacts cocaCola = new NutritionFacts( 240 , 8 , ...

Arrays : Finding the Element in array where next element is +1, +0 or -1

Problem Statement You are given an array where each element follows the rule that given any index, the number at that index will either be  +1 of the number at that index. +0 of the number at that index. -1 of the number at that index. Suppose the array is  Sample Input arr       = {1,2,3,2,3,4,5,6,7,6,5,4,5,6,4,4,4,4}; search = 5 Sample Output 6  (First occurrence of search ) Sample Input arr       = {1,2,1,2,1,2,1,2,1,2}; search = 5 Sample Output 1  ( Element is not found in the array) Algorithm Star iterating from start of the array. Check if the value at the index is same as the search value if yes, then return the index if no, then increment the index counter by modulus of difference of value to search and value at index return -1 if value to search does not exist in the array. Java Program view plain copy to clipboard print ? package  com.ekiras.arrays;      public   class  SearchEl...

Java : How to sort Array List based on Custom Order

How to sort Array List using Custom Order On many occasions we need to sort an array list or linked list based on custom logic. Suppose you have a Quiz application and you want to return questions based on a custom question id. e.g Request : ids = [ 88, 21, 43, 15, 64, 35 ] When you will fetch the Questions from Database you will be using a query something like below select * from question where id in (?) This will give you questions ordered by id by default. So to covert it in same order as requested order you can use view plain copy to clipboard print ? // ids = [ 88, 21, 43, 15, 64, 35 ]    // questions = new ArrayList<Question>();     Collections.sort(questions,  new  Comparator<Question>() {         @Override          public   int  compare(QuestionDto q1, QuestionDto q...

Java : How to generate a random number between two given numbers

How to find a Random Number Between two given Numbers Suppose we want to generate a number between two given numbers X and Y then we can use the following two approaches. Approach 1 Generate a random number between 0 to (Y - X ) just add this to X. i.e X+N For, example if we have to calculate a random number between 100 and 150, then in that case X = 100 , Y = 150, Then we calculate a number between 0 to (150-100)  i.e  0 to 50. Thus, we just need to add this to 100 to get a number in range of 100 to 150. Approach 2 Generate a number N using the Math.random() method such that ( N < X< Y ) If N <= Y - X  then result is X+N else, we add the difference of N from the difference of X and Y i.e X + ( N - ( Y - X )) For, example if we have to calculate a random number between 100 and 150, then in that case X = 100 , Y = 150, Case 1 : N = 24 ( less than Y- X) In this case result will be X + N that is 24 + 100 = 124 Case 2 : N = 88 ( greater than Y-X ) In this case resul...

Java : How to Make a Http GET request and read response

How to Make a Http GET request and read response Steps to make a HTTP GET request Make URL object. Make HttpURLConnection object from URL object and type cast it to  HttpURLConnection Set Request method to GET. Add Headers using method setRequestProperty()  if required. Use BufferedReader to read the input stream of the connection. Read the response from buffered reader object. The code to implement the above steps is shown below.

Java : How to make enums inside java class

How to make enums inside java class You can use enums inside a class as shown in the code below. User.Gender.MALE or FEMALE  is always associated with the user property. However if you need Gender to be generic and u want to use it with animals also, then you might want to keep this enum in a separate class. package com.ekiras.demo; public class User { public enum Gender{ MALE, FEMALE } private String name; private String address; private String email; private String password; private Gender gender = Gender.MALE; } You can also use the enums with parameters inside class as shown below. package com.ekiras.demo; public class User { public enum Gender{ MALE("male"), FEMALE("female"); String value; Gender(String value){ this.value=value; } } private String name; private String address; private String email; private String password; private Gender gender = Gender.MALE; }

Java : How to write a File in Java using FileWriter

Write a File in Java using FileWriter You can write a file using FileWriter as shown in the code below. package com.ekiras.demo; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Date; class FileDemo { public static void main(String args[]) { readFile(); } public static void readFile() { System.out.println(" Start :: writing file"); try { File file = new File("/home/ekansh/myFile.txt"); FileWriter fileWriter = new FileWriter(file); fileWriter.write("hello, this file is created at :: " + new Date()); fileWriter.flush(); fileWriter.close(); System.out.println(" End :: writing file"); } catch (IOException e) { e.printStackTrace(); } } } You can write the data using the write() method and then call the flush() method to force the os to write to the file, finally close() method to close the file writer object, so that it can be garbage collected.

Java : How to check if the field of a class is STATIC by Reflection

Points To Remember You can use Reflection  to check if the field of a class is static or not. You need to get the modifiers of the field to check if the field is static. How to check if the field of a class is static by Reflection The following is the only way to check if the field is static or not field.getModifiers()& Modifier.STATIC) == Modifier.STATIC Following program shows how to get the static fields from a class. package com.ekiras.demo; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class Test { public static void main(String args[]){ Field[] fields = Person.class.getDeclaredFields(); for(Field field : fields){ if((field.getModifiers()& Modifier.STATIC) == Modifier.STATIC ){ System.out.println("final field :: " + field.getName()); } } } } class Person{ public static final int someConstant = 2; private String name; private String email; public String getName() { return name; } public void setName(String...

Java : How to check if the field of a class is FINAL by Reflection

Points To Remember You can use Reflection  to check if the field of a class is final or not. You need to get the modifiers of the field to check if the field is final How to check if the field of a class is final by Reflection The following is the only way to check if the field is final or not field.getModifiers()& Modifier.FINAL) == Modifier.FINAL Following program shows how to get the final fields from a class. package com.ekiras.demo; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class Test { public static void main(String args[]){ Field[] fields = Person.class.getDeclaredFields(); for(Field field : fields){ if((field.getModifiers()& Modifier.FINAL) == Modifier.FINAL ){ System.out.println("final field :: " + field.getName()); } } } } class Person{ public static final int someConstant = 2; private String name; private String email; public String getName() { return name; } public void setName(String name) { th...

Java : Exception in thread "main" java.util.ConcurrentModificationException

When Exception in thread "main" java.util.ConcurrentModificationException occurs. package com.ekiras.demo; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String args[]){ // create a new list List<String> list = new ArrayList<String>(); // add 50 items to the list for(int itr=0;itr<50;itr++) list.add("user-"+(itr+1)); // try to remove item from list while iterating the list for(String str : list){ if(str.equals("user-15")){ list.remove(str); } } } } The above code will give the following error. Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859) at java.util.ArrayList$Itr.next(ArrayList.java:831) at testing.Test.main(Test.java:18) How to avoid ConcurrentModificationException Create the list of type CopyOnWriteArrayList , this will create a new copy of list for ...

How to find all Permutations and Combinations of a String

Algorithm Used We will be using the following algorithm to find all the permutations of a string Take the first letter as a prefix and find all the permutations of the remaining string. Each of the prefix will also be a permutation itself. If you want to find all the permutations of string with same length as the original string then skip the prefix's as the combination. public class Permute { static String codes = "eki"; static int count; public static void main(String args[]) { permute("", codes); System.out.println(">>>>>>>" + count); } public static void permute(String prefix, String str) { System.out.println(prefix); count++; int n = str.length(); if (n == 0) { System.out.println(prefix); } else { for (int i = 0; i < n; i++) permute(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n)); } } } The above code will give the following output e ek eki eki ei eik eik k ke kei kei ki...