SlideShare a Scribd company logo
UTILITIES @ WORK
           - don’t reinvent when it is ready to use
AGENDA
 Discussion on apache commons utilities
 Java Concurrency Framework

 Mutable vs. Immutable




                                           2
APACHE COMMONS UTILITIES
 Configuration
 Lang

 IO

 BeanUtils




                           3
APACHE COMMONS - CONFIGURATION
 org.apache.commons.configuration
 To load a properties file:

  PropertiesConfiguration config = new
       PropertiesConfiguration(“usergui.properties”);
 If we do not specify an absolute path, the file will be
  searched automatically in the following locations:
     in the current directory
     in the user home directory
     in the classpath

   If a property is named “include” and the value of that
    property is the name of a file on the disk, that file will   4
    be included into the configuration.
APACHE COMMONS – CONFIGURATION (CONT..)
                            Example Properties files


         usergui.properties                            color.properties



    window.width = 500                            colors.background = #FFFFFF
    window.height = 300                           colors.foreground = #000080
    include = color.properties
                                                  # chart colors
    colors.background = #FFFFFF                   colors.pie = #FF0000, #00FF00
    colors.foreground = #000080

    # chart colors
    colors.pie = #FF0000, #00FF00




                                                                                  5
APACHE COMMONS – CONFIGURATION (CONT..)
Sample Code




                                          6
7
APACHE COMMONS – LANG
 StringUtils
 ToStringBuilder

 ArrayUtils




                        8
APACHE COMMONS – LANG - STRINGUTILS
 org.apache.commons.lang.StringUtils
 Methods:
    1.   isEmpty :- Checks if a String is empty (“”) or null.
    2.   isBlank :- Checks if a String is whitespace, empty or null.
    3.   isAlpha :- Checks if a String contains only alphabets
    4.   isNumeric :- Checks if a String contains only nuerics
    5.   defaultIfEmpty(String str, String defString) :- If str is
         empty or null, “defString” is returned else “str” is
         returned
    6.   reverseDelimited :-Reverses a String that is delimited by
         a specific character
    7.   leftPad / rightPad                                            9
APACHE COMMONS – LANG – STRINGUTILS (CONT…)
String str1 = null;
boolean result = false;

result = StringUtils.isEmpty(str1); // true

str1 = "str123";
result = StringUtils.isAlphanumeric(str1); //true
result = StringUtils.isNumeric(str1); //false

str1 = "7";
str1 = StringUtils.leftPad(str1, 3, '0'); //007

str1 = "172.168.1.44";
str1 = StringUtils.reverseDelimited(str1, '.'); //44.1.168.172
                                                                 10
APACHE COMMONS – LANG - TOSTRINGBUILDER
public class ToStringBuilderDemo {
  public static void main(String args[]){
    System.out.println(new Emp(7,"Java",99.99));
  }
}
class Emp{
  int id;
  String name;
  double salary;
  public Emp(int id, String name, double salary){
    this.id = id; this.name = name; this.salary = salary;
  }
  /* here comes accessors and mutators */

    public String toString(){
      return ToStringBuilder.reflectionToString(this);
                                                                   11
    }
}
OUTPUT: com.commons.examples.Emp@10b30a7[id=7,name=Java,salary=99.99]
APACHE COMMONS – LANG - ARRAYUTILS
import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;
public class ArrayUtilsDemo {
  public static void main(String args[]){
    String weekends[] = {"friday","saturday","sunday"};
    String weekdays[] = {"monday", "tuesday", "wednesday", "thursday"};

        String days[] = (String[])ArrayUtils.addAll(weekends, weekdays);
        System.out.println(ArrayUtils.isEmpty(days));
        System.out.println(ArrayUtils.isSameLength(weekends, weekdays));

        Integer values[] = new Integer[10];
        Arrays.fill(values, 1);
        int intValues[] = ArrayUtils.toPrimitive(values,0);
    }
}
                                                                           12
I I I I O O O
  I II
I I       I O O O
        I O O O
 I II I I O O O O


 Input Output       13
APACHE COMMONS – IO
 IOUtils
 FileUtils

 FileSystemUtils

 FileFilter

 LineIterator




                      14
APACHE COMMONS – IO (CONT…)
Task of reading bytes from a URL:




                                    TRADITIONAL


                                                  15

                                    IOUtils
APACHE COMMONS – IO (CONT…)




   File dir = new File(".");
   String[] files = dir.list( new
                  PrefixFileFilter("Test") );

   for ( int i = 0; i < files.length; i++ ) {   16
   System.out.println(files[i]);
   }
17
Executor
Framework
            18
SEQUENTIAL WEB SERVER
class SingleThreadWebServer{
  public static void main(String args[]){
    ServerSocket socket = new ServerSocket(80);
    while(true){
      Socket connection = socket.accept();
       handleRequest(connection);
    }
  }
}


Drawback: thread “main” is responsible for handling all
requests one after the other
                                                          19
WEB SERVER THAT STARTS A NEW THREAD FOR EACH REQUEST
class ThreadPerTaskWebServer{
  public static void main(String args[]){
    ServerSocket socket = new ServerSocket(80);
    while(true){
      final Socket connection = socket.accept();
      Runnable r = new Runnable(){
                  public void run(){
                        handleRequest(connection);
                  }
            };
      new Thread(r).start();
    }
}
}
                                                       20
Drawback: may cause “OutOfMemory” error as there is
no boundary on thread creation.
WEB SERVER USING A THREAD POOL
class TaskExecutionWebServer{
  private static final int NTHREADS = 100;
  private static final Executor exec =
            Executors.newFixedThreadPool(NTHREADS);
  public static void main(String args[]){
    ServerSocket socket = new ServerSocket(80);
    while(true){
      final Socket connection = socket.accept();
      Runnable task = new Runnable(){
                  public void run(){
                        handleRequest(connection);
                  }
            };
      exec.execute(task);
    }                                              21
  }
}
synchronization
        volatile
        atomic
                   22
SYNCHRONIZATION
   Synchronization is built around an internal entity known as the
    intrinsic lock or monitor lock. Intrinsic lock play a role in both
    aspects of synchronization: enforcing exclusive access to an object’s
    state and establishing happens-before relationships that are
    essential to visibility.

   Drawbacks:
        Locking
        Blocking
        Context Switching
        Possibility of Deadlock

                                                                            23
VOLATILE
 A volatile variable is not allowed to have a local copy
  of a variable that is different from the value currently
  held in “main” memory.
 Volatile variables cannot be used to construct
  atomic compound actions(i++). This means that
  volatile variables cannot be used:
     when one variable depends on another
     when the new value of a variable depends on its old value.




                                                                   24
ATOMIC INTEGER
public class Counter {
          private AtomicInteger count = new AtomicInteger(0);

         public void incrementCount() {
                   count.incrementAndGet();
         }
          public int getCount() {
                    return count.get();
         }
}




                                                                25
MUTABLE VS. IMMUTABLE
 Mutable: When we have a reference to an instance of
  an object, the contents of that instance can be altered.
  For Ex: class
  Person, Employee, java.math.BigInteger, etc.
 Immutable: When you have a reference to an instance
  of an object, the contents of that instance cannot be
  altered.
  For Ex: all wrapper classes (Integer,String,etc)



                                                             26
BUILDING AN IMMUTABLE CLASS
 Make all fields private.
 Don’t provide mutators (setter methods)

 Ensure that methods can't be overridden by either
  making the class final (Strong Immutability) or
  making your methods final (Weak Immutability).
 If a field isn't primitive or immutable, make a deep
  clone on the way in and the way out.




                                                         27
public final class BetterPerson{
         private String firstName;
         private String lastName;
         private Date dob;

         public BetterPerson( String firstName, String lastName, Date dob){
                   this.firstName = firstName;
                   this.lastName = lastName;
                   this.dob = new Date( dob.getTime() ); //way in
         }
         public String getFirstName(){
                   return this.firstName;
         }
         public String getLastName(){
                   return this.lastName;
         }
         public Date getDOB(){
                   return new Date( this.dob.getTime() ); //way out
         }

         //No mutators at all i.e., setter methods
                                                                              28
}
29
- PRAMOD

           30

More Related Content

What's hot

Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVE
Uehara Junji
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
Ganesh Samarthyam
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Uehara Junji
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
Ganesh Samarthyam
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
Andrzej Grzesik
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Sungchul Park
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic courseTran Khoa
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
Iram Ramrajkar
 
Java Generics
Java GenericsJava Generics
Java Generics
Zülfikar Karakaya
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
Rafael Winterhalter
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Susan Potter
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
DEVTYPE
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
DEVTYPE
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
Ganesh Samarthyam
 
Java Basics
Java BasicsJava Basics
Java Basics
Sunil OS
 

What's hot (20)

Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVE
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
 
Java Generics
Java GenericsJava Generics
Java Generics
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Java Basics
Java BasicsJava Basics
Java Basics
 

Similar to Use of Apache Commons and Utilities

Java design patterns
Java design patternsJava design patterns
Java design patterns
Shawn Brito
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Writing code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongWriting code that writes code - Nguyen Luong
Writing code that writes code - Nguyen Luong
Vu Huy
 
TechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen LuongTechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
Grokking VN
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
Hithem Ahmed
 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
Leandro Coutinho
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
Alex Miller
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
Sandeep Kr. Singh
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
Марія Русин
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
MuhammadTalha436
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
Nikunj Parekh
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
Nikunj Parekh
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
Paul King
 
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
WebStackAcademy
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
caswenson
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
TechMagic
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
Rafael Winterhalter
 
Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced
Flink Forward
 

Similar to Use of Apache Commons and Utilities (20)

Java design patterns
Java design patternsJava design patterns
Java design patterns
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Thread
ThreadThread
Thread
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Writing code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongWriting code that writes code - Nguyen Luong
Writing code that writes code - Nguyen Luong
 
TechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen LuongTechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced Apache Flink Training: DataStream API Part 2 Advanced
Apache Flink Training: DataStream API Part 2 Advanced
 

Recently uploaded

Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 

Recently uploaded (20)

Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 

Use of Apache Commons and Utilities

  • 1. UTILITIES @ WORK - don’t reinvent when it is ready to use
  • 2. AGENDA  Discussion on apache commons utilities  Java Concurrency Framework  Mutable vs. Immutable 2
  • 3. APACHE COMMONS UTILITIES  Configuration  Lang  IO  BeanUtils 3
  • 4. APACHE COMMONS - CONFIGURATION  org.apache.commons.configuration  To load a properties file: PropertiesConfiguration config = new PropertiesConfiguration(“usergui.properties”);  If we do not specify an absolute path, the file will be searched automatically in the following locations:  in the current directory  in the user home directory  in the classpath  If a property is named “include” and the value of that property is the name of a file on the disk, that file will 4 be included into the configuration.
  • 5. APACHE COMMONS – CONFIGURATION (CONT..) Example Properties files usergui.properties color.properties window.width = 500 colors.background = #FFFFFF window.height = 300 colors.foreground = #000080 include = color.properties # chart colors colors.background = #FFFFFF colors.pie = #FF0000, #00FF00 colors.foreground = #000080 # chart colors colors.pie = #FF0000, #00FF00 5
  • 6. APACHE COMMONS – CONFIGURATION (CONT..) Sample Code 6
  • 7. 7
  • 8. APACHE COMMONS – LANG  StringUtils  ToStringBuilder  ArrayUtils 8
  • 9. APACHE COMMONS – LANG - STRINGUTILS  org.apache.commons.lang.StringUtils  Methods: 1. isEmpty :- Checks if a String is empty (“”) or null. 2. isBlank :- Checks if a String is whitespace, empty or null. 3. isAlpha :- Checks if a String contains only alphabets 4. isNumeric :- Checks if a String contains only nuerics 5. defaultIfEmpty(String str, String defString) :- If str is empty or null, “defString” is returned else “str” is returned 6. reverseDelimited :-Reverses a String that is delimited by a specific character 7. leftPad / rightPad 9
  • 10. APACHE COMMONS – LANG – STRINGUTILS (CONT…) String str1 = null; boolean result = false; result = StringUtils.isEmpty(str1); // true str1 = "str123"; result = StringUtils.isAlphanumeric(str1); //true result = StringUtils.isNumeric(str1); //false str1 = "7"; str1 = StringUtils.leftPad(str1, 3, '0'); //007 str1 = "172.168.1.44"; str1 = StringUtils.reverseDelimited(str1, '.'); //44.1.168.172 10
  • 11. APACHE COMMONS – LANG - TOSTRINGBUILDER public class ToStringBuilderDemo { public static void main(String args[]){ System.out.println(new Emp(7,"Java",99.99)); } } class Emp{ int id; String name; double salary; public Emp(int id, String name, double salary){ this.id = id; this.name = name; this.salary = salary; } /* here comes accessors and mutators */ public String toString(){ return ToStringBuilder.reflectionToString(this); 11 } } OUTPUT: com.commons.examples.Emp@10b30a7[id=7,name=Java,salary=99.99]
  • 12. APACHE COMMONS – LANG - ARRAYUTILS import java.util.Arrays; import org.apache.commons.lang.ArrayUtils; public class ArrayUtilsDemo { public static void main(String args[]){ String weekends[] = {"friday","saturday","sunday"}; String weekdays[] = {"monday", "tuesday", "wednesday", "thursday"}; String days[] = (String[])ArrayUtils.addAll(weekends, weekdays); System.out.println(ArrayUtils.isEmpty(days)); System.out.println(ArrayUtils.isSameLength(weekends, weekdays)); Integer values[] = new Integer[10]; Arrays.fill(values, 1); int intValues[] = ArrayUtils.toPrimitive(values,0); } } 12
  • 13. I I I I O O O I II I I I O O O I O O O I II I I O O O O Input Output 13
  • 14. APACHE COMMONS – IO  IOUtils  FileUtils  FileSystemUtils  FileFilter  LineIterator 14
  • 15. APACHE COMMONS – IO (CONT…) Task of reading bytes from a URL: TRADITIONAL 15 IOUtils
  • 16. APACHE COMMONS – IO (CONT…) File dir = new File("."); String[] files = dir.list( new PrefixFileFilter("Test") ); for ( int i = 0; i < files.length; i++ ) { 16 System.out.println(files[i]); }
  • 17. 17
  • 19. SEQUENTIAL WEB SERVER class SingleThreadWebServer{ public static void main(String args[]){ ServerSocket socket = new ServerSocket(80); while(true){ Socket connection = socket.accept(); handleRequest(connection); } } } Drawback: thread “main” is responsible for handling all requests one after the other 19
  • 20. WEB SERVER THAT STARTS A NEW THREAD FOR EACH REQUEST class ThreadPerTaskWebServer{ public static void main(String args[]){ ServerSocket socket = new ServerSocket(80); while(true){ final Socket connection = socket.accept(); Runnable r = new Runnable(){ public void run(){ handleRequest(connection); } }; new Thread(r).start(); } } } 20 Drawback: may cause “OutOfMemory” error as there is no boundary on thread creation.
  • 21. WEB SERVER USING A THREAD POOL class TaskExecutionWebServer{ private static final int NTHREADS = 100; private static final Executor exec = Executors.newFixedThreadPool(NTHREADS); public static void main(String args[]){ ServerSocket socket = new ServerSocket(80); while(true){ final Socket connection = socket.accept(); Runnable task = new Runnable(){ public void run(){ handleRequest(connection); } }; exec.execute(task); } 21 } }
  • 22. synchronization volatile atomic 22
  • 23. SYNCHRONIZATION  Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. Intrinsic lock play a role in both aspects of synchronization: enforcing exclusive access to an object’s state and establishing happens-before relationships that are essential to visibility.  Drawbacks:  Locking  Blocking  Context Switching  Possibility of Deadlock 23
  • 24. VOLATILE  A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in “main” memory.  Volatile variables cannot be used to construct atomic compound actions(i++). This means that volatile variables cannot be used:  when one variable depends on another  when the new value of a variable depends on its old value. 24
  • 25. ATOMIC INTEGER public class Counter { private AtomicInteger count = new AtomicInteger(0); public void incrementCount() { count.incrementAndGet(); } public int getCount() { return count.get(); } } 25
  • 26. MUTABLE VS. IMMUTABLE  Mutable: When we have a reference to an instance of an object, the contents of that instance can be altered. For Ex: class Person, Employee, java.math.BigInteger, etc.  Immutable: When you have a reference to an instance of an object, the contents of that instance cannot be altered. For Ex: all wrapper classes (Integer,String,etc) 26
  • 27. BUILDING AN IMMUTABLE CLASS  Make all fields private.  Don’t provide mutators (setter methods)  Ensure that methods can't be overridden by either making the class final (Strong Immutability) or making your methods final (Weak Immutability).  If a field isn't primitive or immutable, make a deep clone on the way in and the way out. 27
  • 28. public final class BetterPerson{ private String firstName; private String lastName; private Date dob; public BetterPerson( String firstName, String lastName, Date dob){ this.firstName = firstName; this.lastName = lastName; this.dob = new Date( dob.getTime() ); //way in } public String getFirstName(){ return this.firstName; } public String getLastName(){ return this.lastName; } public Date getDOB(){ return new Date( this.dob.getTime() ); //way out } //No mutators at all i.e., setter methods 28 }
  • 29. 29
  • 30. - PRAMOD 30