Use of Apache Commons and Utilities
-
Upload
pramod-kumar -
Category
Technology
-
view
2.794 -
download
3
Transcript of Use of Apache Commons and Utilities
![Page 1: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/1.jpg)
UTILITIES @ WORK- don’t reinvent when it is ready to use
![Page 2: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/2.jpg)
2
AGENDA
Discussion on apache commons utilities Java Concurrency Framework Mutable vs. Immutable
![Page 3: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/3.jpg)
3
APACHE COMMONS UTILITIES
Configuration Lang IO BeanUtils
![Page 4: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/4.jpg)
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 be included into the configuration.
![Page 5: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/5.jpg)
5
APACHE COMMONS – CONFIGURATION (CONT..)
usergui.properties color.properties
window.width = 500 window.height = 300include = color.properties
colors.background = #FFFFFF colors.foreground = #000080
# chart colors colors.pie = #FF0000, #00FF00
Example Properties files
colors.background = #FFFFFF colors.foreground = #000080
# chart colors colors.pie = #FF0000, #00FF00
![Page 6: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/6.jpg)
6
APACHE COMMONS – CONFIGURATION (CONT..)
Sample Code
![Page 7: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/7.jpg)
7
null
blank (“”)
whitespace(“ “)
![Page 8: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/8.jpg)
8
APACHE COMMONS – LANG
StringUtils ToStringBuilder ArrayUtils
![Page 9: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/9.jpg)
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 alphabets4. isNumeric :- Checks if a String contains only nuerics5. 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
![Page 10: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/10.jpg)
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
![Page 11: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/11.jpg)
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); }}OUTPUT: com.commons.examples.Emp@10b30a7[id=7,name=Java,salary=99.99]
![Page 12: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/12.jpg)
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); }}
![Page 13: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/13.jpg)
13
II
II
II
II
II I
II I
II
OO
O O
O
O OO
O
O
OO
O
Input Output
![Page 14: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/14.jpg)
14
APACHE COMMONS – IO IOUtils FileUtils FileSystemUtils FileFilter LineIterator
![Page 15: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/15.jpg)
15
APACHE COMMONS – IO (CONT…)
Task of reading bytes from a URL:
TRADITIONAL
IOUtils
![Page 16: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/16.jpg)
16
APACHE COMMONS – IO (CONT…)
File dir = new File("."); String[] files = dir.list( new
PrefixFileFilter("Test") ); for ( int i = 0; i < files.length; i++ ) { System.out.println(files[i]); }
![Page 17: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/17.jpg)
17
![Page 18: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/18.jpg)
18
Executor Framework
![Page 19: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/19.jpg)
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
![Page 20: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/20.jpg)
20
WEB SERVER THAT STARTS A NEW THREAD FOR EACH REQUEST
20
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(); }}}
Drawback: may cause “OutOfMemory” error as there is no boundary on thread creation.
![Page 21: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/21.jpg)
21
WEB SERVER USING A THREAD POOLclass 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); } }}
![Page 22: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/22.jpg)
22
synchronization
volatile
atomic
![Page 23: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/23.jpg)
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
![Page 24: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/24.jpg)
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.
![Page 25: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/25.jpg)
25
ATOMIC INTEGER
public class Counter { private AtomicInteger count = new AtomicInteger(0);
public void incrementCount() {
count.incrementAndGet(); } public int getCount() {
return count.get(); }
}
![Page 26: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/26.jpg)
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)
![Page 27: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/27.jpg)
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.
![Page 28: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/28.jpg)
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}
![Page 29: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/29.jpg)
29
![Page 30: Use of Apache Commons and Utilities](https://reader035.fdocuments.us/reader035/viewer/2022062405/554fba86b4c9053d018b46f7/html5/thumbnails/30.jpg)
30
- PRAMOD