SlideShare a Scribd company logo
1 of 398
Download to read offline
Presented By Amirhossein Sadr
AP SPRING 2024 Course Lectured By Dr. Mojtaba Vahidi Asl
1. You are a programmer
2. You want to be a better programmer
Robert C. Martin
Uncle Bob
I like my code to be elegant
and efficient
Clean code does one thing
well
Bjarne Stroustrup
Clean code is simple and
direct
Clean code reads like
well-written prose
Grady Booch
Clean code can be read
Clean code should be
literate
Dave Thomas
Clean code always
looks like it was written
by someone who cares
Michael Feathers
Reduced Duplication,
High Expressiveness
and early building of
simple abstractions
Ron Jeffries
You know you are
working on clean code
when each routine you
reads turns out to be
pretty much what you
expected
Ward Cunnigham
Use Intention-Revealing Names
Use Intention-Revealing Names
Avoid Disinformation
Make Meaningful Distinctions
Use Pronounceable Names
Use Pronounceable Names
Use Searchable Names
Use Searchable Names
Member Prefixes (Avoid encodings)
Hungarian Notation (Avoid encodings)
Member Prefixes (Avoid encodings)
Hungarian Notation (Avoid encodings)
Avoid Mental Mapping
Class Names
Avoid Mental Mapping
Class Names
Method Names
Pick One Word Per Concept
Don’t Pun
Use Solution Domain Names
Add Meaningful Context
Don’t Add Gratuitous Context
Small!
Do One Thing
One Level of Abstraction per Function
Reading Code from Top to Bottom
Switch Statements
Switch Statements
Use Descriptive Names
Function Arguments
Common Monadic Forms
Flag Arguments
Common Monadic Forms
Flag Arguments
Dyadic Functions
Triads
Argument Objects
Verbs and Keywords
Have No Side Effects
Don’t Repeat Yourself (DRY)
Structured Programming
Comments Do Not Make Up for Bad Code
Explain Yourself in Code
Legal Comments
Informative Comments
Explanation of Intent
Clarification
Warning of Consequences
TODO Comments
Amplification
Mumbling
Redundant Comments
Redundant Comments
Mandated Comments
Journal Comments
Noise Comments
Scary Noise
Position Markers
Closing Brace Comments
Attributions and Bylines
Commented Out Code
Nonlocal Information
Too Much Information
Inobvious Connection
Function Headers
The Purpose of Formatting
The Newspaper Metaphor
Vertical Openness Between Concepts
Vertical Density
Vertical Distance
Horizontal Openness and Density
Horizontal Alignment
Horizontal Alignment
Breaking Indentation
Breaking Indentation
Team Rules
Prefer Exceptions to returning Error Codes
Prefer Exceptions to Returning Error Codes
Extract Try/Catch Blocks
Error Handling Is One Thing
Define the Normal How
Define the Normal How
Don’t Return Null
Don’t Return Null
Don’t Pass Null
The Three Laws of TDD
Keeping Tests Clean
Clean Tests
One Assert per Test
Single Concept per Test
F.I.R.S.T
Class Organization
Classes Should Be Small!
The Single Responsibility Principle (SRP)
Cohesion
Simple Design Rule 1: Runs All the Tests
Simple Design Rules 2: No Duplication
Simple Design Rules 3: Expressive
Simple Design Rules 4: Minimal Classes and Methods
Robert C. Martin, Clean Code (Prentice Hall, 2008)
Based on Arturo Herrero Slides
GIT
Advanced programming
Dr.Mojtaba Vahidi Asl
Hoda attari
Spring 403
(part 1)
WHAT IS GIT ?
• undo on steroids
• Transfer code (allow you to collaborate with others )
• Merge codes
WHAT IS GIT ?
• Created by Linus Torvalds, April 2005.
• A command line version control program
• Distributed version control
• Cross platform (including Windows)
• Open source, free
Git is a distributed version control system
What is distributed version control?
• “if you're not distributed, you're not worth using” –Linus Torvalds
• No need to connect to central server
• Can work without internet connection
• No single failure point
• Developers can work independently and merge their work later
• Every copy of a git repository can serve either as the server or as a client
• Git tracks changes, not versions
• Branch of little change sets floating around
Terminal commands
Terminal commands
GIT commands
installation
https://git-scm.com/downloads
Check installation and change author identity
$ git –version
$ git config –-global user.name “HodaAttari”
$ git config –-global user.email “hoda.attari@gmail.com”
What is repository ?
• Turn the current folder into a git repo by creating a hidden .git folder inside it.
$ git init
• Get the overall status of the git repository (to be explained later)
$ git status
$ git status --short : The short version
• Change default branch name:
$ git config –-global init.defaultBranch main
• Check all of your git config
• $ git config –-list
• $ git config <key name> e.g. $git config user.name
• Local Vs remote repository
Important components
In order to save the repo’s state at a certain moment (equivalent to copying it into another directory
so you can bring it back if you break it), we make commits. So each repo consists of many commits.
There is a pointer called HEAD which refers to a certain commit. Git regards this commit as the “last
save”. So it calculates your files’ changes relative to their “image” in this commit. The equivalent of
copying into another directory would be that HEAD refers to the copied folder of the project.
*The three state of git files
Working directory:
1. Unchanged (committed)
2. Untracked (All the other types are
technically “tracked”)
3. Modified
4. Deleted
Also called the “Git Index”
or simply “Index”
Commands To Move Files Between States
$ git add <filename> : stage modified/untracked file
$ git add . : stage all modified/untracked files
$ git add --all : stage modified/untracked file
$ git commit –m “commit message” : commit the entire staging area
$ git commit : commit the entire staging area ,but write
“extended” commit message in editor.
$ git commit –a –m “commit message” : stage and commit the entire
staging area (does not track untracked files
• Checking commit history
$ git log
• Use Enter Key to scroll down when the content does not fit in the terminal.
• Use Q key to exit the scroll area.
• Checking commit history (short version)
$ git log --oneline
• Change the editor git commit takes commit messages in
Nano:
$ git config –global core.editor “nano”
VS Code:
$ git config –global core.editor “code --wait”
• Check What git’s current core editor is:
$ git config –global core.editor
$ git config core.editor
Undoing things in git
Restoring working directory changes
• Use restore to do all types of restorations
Unstage a staged file:
$ git restore –-staged <filename>
Restore a modified/deleted file (restores it from the stage, NOT from the last commit)
$ git restore <filename>
IDEs like VSCode and Intellij have git extensions that simplify the restoration
process
index head
Working
tree
index
Undoing things in git
Restoring working directory changes
$ git restore –-staged <filename>
Working directory
stage
head
Undoing things in git
Restoring working directory changes
$ git restore <filename>
Working Dir
stage
head
Undoing things in git
Restoring working directory changes
• Use restore to do all types of restorations
Do both of the previous ones:
$ git restore –-staged --worktree <filename>
Head
Working Dir
index
Undoing things in git
Undoing Commits
• Each commit is linked to the previous, parent commit. The differences made to
the files between the two commits can easily be calculated by Git.
• Use revert to undo the changes made in a specific commit
$ git revert <ref>
<ref> can be a commit hash (read from git log), or other things which we
do not yet cover.
Note that git revert undoes the changes in exactly the commit specified
and does not work if you want to undo several commits at once
An example will be covered in Project 2
What is tag?
Tag types:
1. Annotated: hold information about the author, date created, message,
etc.
2. Lighweight: Only holds info about the commit it’s pointing to.
• Creating and deleting Tags:
$ git tag <tag name>
Creates a lightweight tag on the most recent commit (HEAD) with the specified name
$ git tag <tag name> <commit hash>
Creates a lightweight tag on any commit (specified by hash) with the specified name
$ git tag -a <tag name> -m “tag message”
Creates an annotated tag on the most recent commit (HEAD)with the specified message
and name.
$ git tag -a <tag name> -m “tag message” <commit hash>
Creates an annotated tag on the hash-specified commit with the specified message and
name.
$ git tag -d <tag name>
Deletes a tag locally.
• Reading tags
$ git tag
Lists the names of all tags
$ git show <tag name>
Show all the data the tag holds (including commit, message, author, date, etc.)
• Pushing tags : git push origin does NOT push tags
$ git push origin <tag name>
Push the specified tag
$ git push origin --tags
Push all tags
$ git push origin --delete <tag name>
Delete tag from origin (git push does not sync tags)
• Checking out tags
$ git checkout <tag name>
Check out the tag’s commit
Git ignore
• Creating .gitignore
$ touch .gitignore
Create the .gitignore file
You can use the wildcard * in your .gitignore directives:
*.txt => ignores all txt files (in ANY directory)
You can ignore entire directories:
hello/ => ignores the contents of hello/ directory ANYWHERE in the repo
/hello/ => ignores the contents of hello/ directory ONLY in the root
To prevent .gitignore’s recursive behavior, you can create .gitignores INSIDE of
directories. The rules specified in those will not apply to parent directories.
List of complete gitignore rules can be found here
Thanks for your attention
GIT
Advanced programming
Dr.Mojtaba Vahidi Asl
Hoda attari
Spring 403
(part 2)
Branches
Git Stores “Snapshots” of the files in each commit
But it’s also easy for
Git to see the changes
between any two commits
Git stores commits as a DAG (a directed acyclic graph) in which each commit “points” to its parent commit(s).
Its structure is very similar to linked lists.
Git branches, and tags (and in specific cases HEAD) are references (pointers) to certain commits in the history
Head, branches, and tags
simply “point to commits”
and also hold some
metadata
Last commit
As we have already mentioned,
branches are simply “pointers to
commits”. When you make the
first commit in your repository, a
default branch, (names master
or main) is automatically
created and points to the
commit you made.
Master here is a
branch: it points to
the commit with the
hash f30ab
Branch Commands
$ git branch
List all branches. Puts a * beside the branch that HEAD currently points to. If HEAD
is detached, will print the commit hash that HEAD points to.
$ git branch <branch name>
Creates a new branch with the given name to point to whatever commit HEAD is
pointing to.
$ git checkout -b <branch name> <commit hash>
Checks out the given commit and also creates a new branch with the given
name to point to it (the HEAD will point to the newly created branch, NOT the
commit, so it will not be detached)
$ git branch –d <branch name>
Deletes the given branch name.
$ git log --all
Show commits and branches and tags for ALL branches, not just the current
one’s
What are branches for?
• Better understanding reset: we have introduced used git reset
here. Git reset is a simple git checkout with the difference that if
HEAD is in normal state, the HEAD won’t be updated to point to
the specified commit, but the branch that HEAD is pointing to
will be updated to point to the specified commit
1 2
1 2
1 2
head
master
head master
head
master
merging
merging
$ git merge <branch name>
Merges <branch name> “into” whatever branch HEAD is pointing to.
There are 2 types of merging:
1. Fast-Forward Merge
2. Three-Headed Merge
We will first consider the simpler case: fast-forward merge
c2
c1
If HEAD is on branch B1 pointing to commit C1 and there is a branch B2 that points to
commit C2 such that C1 is an ancestor of C2 (meaning C1 was turned into C2 through a
series of commits):
Then calling the command
$ git merge B2
Will result in a fast-forward merge. In this type of merge, the branch that the head points to will simply be
updated to point to the same commit as the branch that has been merged into it (in this case B2) See the
result on the next page
B1 head B2
Earliest commit Most recent commit
merging
c2
c1
B1 head
B2
Earliest commit Most recent commit
Result
Fast forwarding
c2
c1
B1 head
B2
c1
Earliest commit Most recent commit
conflict
Suppose you have created a branch and have made a few commits to it. Meanwhile, the
master branch has also advanced by a few commits (maybe another developer committed
to master or you merged another branch into it.) Your repo will look like this:
A
B Master
HEAD
Branch
Conflict
If you make a mistake in the conflict resolution process and want to undo all
changes you made in the process of merging, use:
$ git merge --abort
General conflict
Note that merging is not the only place you will encounter conflicts. We will see
later on that conflicts arise when we are pulling from remotes as well.
Merge conflicts are not based on line numbers: Git is pretty smart about
comparing files and changes. It is incorrect to think that the only way git
compares to see if two branches have a merge conflict is by comparing their
changes to identical line numbers in files. The Project on the next page will
illuminate this concept.
Gitignore
• Blank lines are ignored • Lines starting with # are ignored (comments)
• Wildcards are used!
• *.file → All files withe .file extention
• !name.file → ! specifies a negation or exception. All files withe .file
extention, except name.file
Note: ignore large files, passwords, unnecessary files, etc.
GitHub
• remote: where should I upload my git projects
git remote add origin <link of repo> Find repo link on GitHub page
• push: the act of uploading the git project
git push origin master Master → any other branch
• clone: download the whole git project
git clone <repo link>
• pull: check for updates in the remote git
git pull origin master • Fetch and merge! • pull = fetch + merge
Revert and reset
• revert vs. reset
• Revert: take a previous commit and add it as a new commit, keeping the log intact.
• Reset: move back to a previous commit, discarding any changes made after that commit.
• git revert [commit_id or hash]
• git reset --hard [commit_hash]
• we can find commit hash from : git log --oneline
Note: (undo reset!) Even though the commits are no longer showing up
in the log, it is not removed from git. → If you know the commit hash you can
reset to it.
Last tips
• search & use help & read documentation
• don’t panic
• everything messed up: re-clone!
• test new commands in a toy repository
• don't commit large files
• don't re-write public history
• pull before push, even better, pull before starting coding
Thanks for your attention
Strings are
immutable in Java :
Regular Expression Patterns
ü username@domain.com
ü user.name@domain.com
ü user-name@domain.com
ü username@domain.co.in
ü user_name@domain.com
× username.@domain.com
× .user.name@domain.com
× user-name@domain.com.
× username@.com
OOP Review
Slides and Presentation by Farzin Haj Gholamrezaei
Instructor: Dr.Vahidi Asl
Advanced Programming Workshop
1402 Spring semester
OOP Review
Why Object Oriented Programming?
Faster and easier to execute
Clear structure for programming
Easier to maintain, modify and debug
Reusability with less code and shorter development time
OOP Review
Class attributes
OOP Review
Class methods
OOP Review
Class methods
Return type Method’s
name
Method’s parameters
OOP Review
Class methods
OOP Review
Class constructor
OOP Review
Class constructor
OOP Review
modifiers
OOP Review
modifiers
OOP Review
modifiers
OOP Review
UML
UML
Temporary association
(Dependency)
Composition association
Direct association
Aggregation association
Sources:
https://stackoverflow.com/questions/21967841/aggregation-vs-composition-vs-association-vs-direct-association:
https://www.tutorialspoint.com/object_oriented_analysis_design/ooad_uml_basic_notation.htm
https://app.diagrams.net/
https://www.geeksforgeeks.org/unified-modeling-language-uml-introduction/#6-tools-for-creating-uml-diagrams
https://www.w3schools.com/java/
Thank you
for your
attention
Unit Test
Instructor: Dr.Vahidi Asl
Mohammad-Moein Arabi
1
Table of contents
● The Importance of testing softwares
● Unit Test
● JUnit in Java
● Best practices in writing tests
● Advance JUnit
● Additional topics
○ GitHub workflows
○ Code coverage
2
Naive Approach
● Print the program’s state to standard output!
● Check the output of each method one by one manually.
● Before releasing software, add Main class to test each function and then
remove it! (Not reusing tests)
3
The problem with this way
● Low speed developing.
● Not cover all lines of code.
● Not reusing tests.
● The programmer must run tests manually.
● The programmer himself must ensure the test passes or not.
4
Benefits of Auto Testing
Let a program tests the program!
● High speed developing
● More accurate
● Debug easier after finding bugs
● Reuse tests
● Reports how many tests pass and fails
5
What is Unit Test?
● An automated test code
● Written and maintained by the developer
● Tests a function or an small section
● The result of every test is pass or fail
6
7
Type of Testing
Editor Supportings
Intellij:
8
Write your first unit
tests
9
Unit Test in Java
JUnit framework
Not officially packed with JVM. Should be installed as a
dependency.
JUnit4 last release was v4.13.2 on Feb 2021
JUnit5 is the last major update.
10
Download Junit
1. The official GitHub page
2. Dependency management in Intellij
11
Class Calculator
class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
}
12
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
13
1. Create CalculatorTest class
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
14
1. Create CalculatorTest class
2. Add a new method to test add
method
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
15
1. Create CalculatorTest class
2. Add a new method to test add
method
3. Invoke add method in the test
method assert the result
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
16
1. Create CalculatorTest class
2. Add a new method to test add
method
3. Invoke add method in the test
method assert the result
4. Add Test annotation to the test
method
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
17
1. Create CalculatorTest class
2. Add a new method to test add
method
3. Invoke add method in the test
method assert the result
4. Add Test annotation to the test
method
Junit will only run methods with
Test annotation.
How JUnit knows which method has
Test annotation? Reflection
class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
}
18
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
5. Run tests…
19
Good Test
The properties of a good test:
1. Use meaningful names for test methods.
2. Each test method should test only one thing (Single Responsibility)
3. Tests should be independent of another test.
4. Use meaningful messages for fail reason.
20
Advanced JUnit
21
Assert methods
22
assertThrows assertThrows(ArithmeticException.class, () -> calculator.divide(1, 0));
assertTimeout assertTimeout(ofMinutes(2), () -> {
// Perform task that takes less than 2 minutes.
});
assertTrue assertTrue(5 > 3);
assertFalse
assertNotNull assertNotNull(getPersonName());
Startup &
Teardown Method
23
Before and after each test, these
methods will be executed.
public class BeforeAndAfterAnnotationsUnitTest {
private List<String> list;
@BeforeEach
public void init() {
System.out.println("startup");
list = new ArrayList<>(Arrays.asList("test1", "test2"));
}
@AfterEach
public void teardown() {
System.out.println("teardown");
list.clear();
}
}
Startup &
Teardown Method
24
Executes only once. Before any tests
and after all tests.
class BeforeAllAndAfterAllAnnotationsUnitTest {
@BeforeAll
static void setup() {
System.out.println("startup - creating DB connection");
}
@AfterAll
static void tearDown() {
System.out.println("closing DB connection");
}
}
Compare JUnit v4 vs v5
25
JUnit 4 @Before @After @BeforeClass @AfterClass
JUnit 5 @BeforeEach @AfterEach @BeforeAll @AfterAll
Other Annotations
26
@DisplayName Declares a custom display name for the
test class or test method.
@Disabled Used to disable a test class or test
method
@Timeout lifecycle method if its execution exceeds
a given duration.
Additional Topics
27
Test in GitHub
A GitHub workflow is a configurable, automated process that executes one or
more actions after each event (e.g. after pushing, after merging, …)
GitHub can run our repository tests on its virtual machines!
Shows passing or failing result to users.
28
Code Coverage
measures how many of your lines of code are
executed when you run automated tests.
Many tools are exists. One of them is Codecov
29
1. Create Model.
Student.java :
2. Create Controller.
StudentController.java :
3. Create View.
StudentView.java :
4. Use the StudentController methods to
demonstrate MVC design pattern usage.
MVCPatternDemo.java :
Output :
Abstraction, interfaces & classes
Advanced programming
Dr. Mojtaba Vahidi Asl
Seyed Sadra Mousavi
Spring 1403
What is abstraction?
• Hiding implementation and showing only functionality to the user.
• Example: Sending SMS.
• You don’t know how SMS goes to the destination. You just know it goes
where you want.
• Another example: Driving a car.
• You just push a pedal and it accelerates. You don’t know the details of this
process.
• Another example: Turning on the lights.
• You don’t know the details of getting electricity to your home. You just
know that if you push the button, the light will turn on.
Abstraction in java
• Abstraction can be achieved by abstract classes and interfaces.
Abstract class Interface
Abstract classes
• They must be declared with an “abstract” keyword.
• They can’t be instantiated. (we can’t make objects from them.)
• They can have abstract and non-abstract methods.
• They can have constructors and static methods.
• They can have final methods that will force the subclass not to
change the body of the method.
Example
Why we use abstract class?
• It can be used as a template class for subclasses.
• It can hold some common methods and their functionality so
we don’t have to implement them every time.
Interfaces
• They must be declared with an “interface” keyword.
• They are not class. So we can’t make objects of them.
• Their fields modified as final. So we can’t change them with a
setter or anything else.
• All methods are abstract by default (unless you determine
something else), So it isn’t necessary to write “abstract”
keyword.
• From Java 8, default and static methods were added to them.
• From Java 9, private methods were added to them.
• We use them for multiple inheritance.
Example 1
Example 2
Example 3
Example 4
Why we use interface?
• Interface help us in multiple inheritance which is a very big
favor.
• It holds the signatures of the methods which we need to be
implemented.
• It gives us loose coupling.
• This means with interfaces, we make classes independent
from each other.
• Polymorphism is supported through interface.
Difference between abstract class and
interface
• Abstract class is a class that can’t be instantiated and it can
have abstract and non-abstract methods.
• On the other hand, interface is something that makes the
target class to implement a set of methods.
• In abstract class we can implement some methods but we can’t
do such thing in interface.
• A class can inherit just one abstract class. But it can implement
multiple interfaces.
Interesting example for abstract classes and
interfaces
• You can use a general abstract class for walking and extend it for every hero instead
of writing a walking method 114 times.
• Also you can use an interface for every type of hero and put a set of methods there
so that every hero from that type implements those methods.
Inner classes (nested classes)
• As it occurs from its name, these classes are in other classes.
• There are 3 types of these classes:
• 1) classes which are defined in other class.
• 2) classes which are statically defined in other class.
• 3) classes which are defined in a method from other class. (They
aren’t popular.)
• They all have some weird syntax.
Example 1
Example 2
Example 3
Object class
• every class in java extends object class by default.
• This class has some useful methods for itself.
• Methods like: equals, getHashCode, toString, etc.
• Equals and toString are the most useful methods of this class.
• Equals returns result of comparing hash codes of two
object.(You can override it to something else.)
• toString returns this: class name + @ + hash code of the
argument object.(You can override it to something else.)
Polymorphism
• It is one of the most important features of object-oriented
programming.
• It means doing an action in multiple ways.
• there are 2 types of polymorphism.
• 1) compile-time polymorphism which happens when you
overload a static method in Java.
• 2) run-time polymorphism which happens when you override
a method.
Example of compile-time polymorphism
Example of run-time polymorphism
Binding
• Determining type of a variable or connecting a method call to
the right body method is called binding.
• There are two types of binding.
• 1) static binding: when the type is determined at compiled
time. If there is any private, static, final methods in class, there
is static binding.
• 2) dynamic binding: when the type is determined at run time.
Example of static binding
Example of dynamic binding
Cloning
• It means creating an exact copy of an object.
• We have 2 ways to do such a thing.
• 1) using the assignment operator to create a copy of that object. (It isn’t safe.)
• 2) using clone() method to copy. This method is in cloneable interface and we
should implement it first.
• There are 2 types of cloning.
• 1) Shallow copy which is not completely safe.
• 2) Deep copy which is completely safe.
• For more information check out https://www.geeksforgeeks.org/clone-method-in-
java-2/.
Sources
• https://stackoverflow.com/questions/22085985/why-do-we-
need-abstract-classes-in-java.
• https://www.javatpoint.com/runtime-polymorphism-in-java.
• https://www.w3schools.com/java/java_inner_classes.asp.
• https://www.geeksforgeeks.org/clone-method-in-java-2/.
• https://www.javatpoint.com/static-binding-and-dynamic-
binding.
• https://www.digitalocean.com/community/tutorials/abstract
-class-in-java.
Thanks for your attention
Java 8
and Generics
Why is
Java 8
important?
Why is Java 8 important?
Why is
Java 8
important?
Lambda
Expressions
Lambda Expressions
Parameter Expression
->
Lambda Expressions
Parameter Expression
->
AnotherParameter
( , )
Lambda Expressions
Parameter {code block}
->
AnotherParameter
( , )
Lambda Expressions
Parameter {code block}
->
AnotherParameter
( , )
x -> x * x * 3.14
(x, y) -> x + y
(x, str) -> {
for(int i=0; i<x; i++)
System.out.println(str);
}
Lambda
Expressions
Functional
interfaces
Functional interfaces
Functional interfaces is an interface with
exactly one abstract method
Java 8 and later support non-abstract methods
in an interface called default methods.
Runnable and Comparator are some functional
interfaces.
A lambda can be used as a functional interface
Functional interfaces
Available on java.util.function.*
new
Consumer
Functional
interface
Parameters Return type
Consumer One parameter Void
BiConsumer Two parameter Void
LongConsumer
One long
parameter
Void
Consumer
Use .accept(…) to do the function
BiConsumer can be useful in maps and pairs
Since its void better to be used when
outputting something to screen.
Function
Functional
interface
Parameters Return type
Function One parameter Generic
BiFunction Two parameter Generic
DoubleFunction
One double
parameter
Generic
UnaryOperator One parameter
Same as
parameter
BinaryOperator
Two parameters
of same type
Same as
parameter
Function
Use .apply(…) to do the function
Use .andThen(…) to concat them
BiFunction can be useful in maps and pairs
Because it returns an object we can use ::
(method refrence) and various functions.
Supplier
Functional
interface
Parameters Return type
Supplier - Object
IntSupplier - int
BooleanSupplier - boolean
Supplier
Use .get(…) to do the function
Because it returns an object we can use ::new
Predicate
Functional
interface
Parameters Return type
Predicate One Parameter boolean
BiPredicate Two Parameter boolean
LongPredicate
One long
Parameter
boolean
Predicate
Use .test(…) to do the function
Use .and(…) .or(…) and .negate()
BiFunction can be useful in maps and pairs
Useful in conditions
Streams
Streams
We can use .stream() on all collections
Has one terminal operation
Use .foreach() to process each element
Can have a few intermediate operation
.filter(), .sorted(), .skip(), .limit(), .map(),
.parallel(), .reduce(), .count(), .collect(), …
Streams
Generics
Generics
Imagine a list implementation in Java
Does the type of content matter in the
implementation?
Why can’t we implement a list for each type?
Why can’t we just use Object class?
Generics
This is how they did it.
Generics
This is how they did it.
Can be useful when we don’t know or care
about the type.
Can use more than one generic
Generics can extend something to be more
limited
Generics
How to use?
This future is called type inference and was
introduced in java 7
The <> is called the diamond operator
Generics
A method can be generic too.
A generic method does not need to be inside a
generic class
Controlling generic stuff is only at compile
time
There is no difference in byte code
All types compile into their raw type
This java behavior is called erasure
Generics
Sources:
https://www.w3schools.com/java/java_lambda.asp
https://docs.oracle.com/javase/tutorial/java/generics/methods.html
https://www.geeksforgeeks.org/functional-interfaces-java/
https://livebook.manning.com/book/java-8-in-action/chapter-1/11
https://javacup.ir/javacup-training-videos/
Thank you
for your
attention
Exceptions
ADVANCED PROGRAMMING COURSE
LECTURED BY DR.VAHIDI
SPRING 1403
PRESENTER : SARA AKBARZADEH
UNIVERSITY OF SHAHID BEHESHTI
What IS THE PROBLEM HERE??
What IS THE PROBLEM HERE??
For Special, Unusual, And Uncommon Cases, It
Does Not Work Properly!!!!
• The parameter "day" may be an incorrect value, such
as “Hi" which is not a date.
• The parameter "day" may not be in the desired
format, like "29 Nov 2010."
• The parameter "day" may be an empty string ("").
• The parameter "day" may be null.
We call these special cases exceptions.
Handling exceptions
What should we do with an exception?
• For example, if the parameter of a method is not as we expect:
u Should we terminate the program?
• Imagine a wrong input causing the whole program to crash!
• Should the method continue its execution and return a specific value (e.g., -1)?
• Maybe it shouldn't return any value (void).
• Can we determine a specific value as output?
• Should we display the error as output?
ANSWER : NONE!!!!!!!
What is an Exception
AN EXCEPTION IS AN UNUSUAL EVENT THAT OCCURS DURING THE EXECUTION OF A PROGRAM. IT
DISRUPTS THE NORMAL FLOW OF THE PROGRAM.
EXAMPLES:
• INVALID INPUT
• DIVISION BY ZERO
• ACCESSING AN INDEX OUTSIDE THE BOUNDS OF AN ARRAY
• HARD DISK FAILURES
• OPENING A FILE THAT DOES NOT EXIST
Default Behavior of Java When an Exception
Occurs:
By default, if an error or exception occurs during runtime:
• The exception is detected by the Java Virtual Machine (JVM).
• Some information about this exception is printed in the output.
• The program execution is terminated abruptly.
• However, this default behavior is usually not suitable.
example
When an exception occurs, what happens?
1- An "exception object" is created.
2- The exception object is handed over to the Java Virtual Machine (JVM).
This action is called "throwing an exception."
The exception object contains information such as:
• Error message
• Details about the type of error
• Line number in the program where the exception occurred
3- The normal execution flow of the program is halted.
And also:
4- The JVM looks for a responsible entity to handle the exception (the "catch" block).
• This responsible entity is called an exception handler.
• The method call stack is traversed in order to find this block.
• If such a block (exception handler) is found:
• The thrown exception object is caught by this block.
• Program execution continues from this block (normal execution is interrupted).
• The information available in the exception object is used for better management of this
specific situation.
• If such a block is not found:
• The "default Java behavior" in dealing with exceptions is executed.
• (An error message is printed in the standard output, and the program execution
terminates.)
getYear again
Rewriting the getYear method with exception handling
How to use it
Java keywords in the exception handling
• THROW
THROWS AN EXCEPTION.
• THROWS
IF A METHOD MAY THROW AN EXCEPTION, IT MUST DECLARE IT.
• TRY
BEGINS A BLOCK FOR EXCEPTION HANDLING.
• CATCH
RECEIVES AND HANDLES AN EXCEPTION.
example
Separation of Error handling
Codes
CONSIDER THE PSEUDO-CODE BELOW:
IT CALLS THE ENTIRE CONTENT OF A FILE INTO
MEMORY.
Error handling
Concept of Stack Trace
WHEN CATCHING AN EXCEPTION, THE FOLLOWING INFORMATION IS AVAILABLE IN THE
EXCEPTION OBJECT:
• THE ORIGINAL LOCATION WHERE THE EXCEPTION WAS THROWN.
• THE STACK OF METHODS THAT THE EXCEPTION HAS PASSED THROUGH.
A STACK TRACE IS A REPORT OF THE ACTIVE STACK FRAMES AT A PARTICULAR POINT IN
TIME DURING THE EXECUTION OF A PROGRAM. IT CONTAINS INFORMATION ABOUT THE
SEQUENCE OF METHOD CALLS THAT LED TO AN EXCEPTION OR ERROR, TYPICALLY
INCLUDING:
1.THE CLASS AND METHOD NAMES.
2.THE FILE NAME AND LINE NUMBER IN THE SOURCE CODE WHERE EACH METHOD WAS
CALLED.
3.ADDITIONAL CONTEXTUAL INFORMATION SUCH AS VARIABLE VALUES OR STATE OF THE
PROGRAM.
Example
Exception Classes
• EVERY EXCEPTION HAS A TYPE.
• FOR INSTANCE, THE TYPE OF "ERROR WHEN READING A FILE" AND
"DIVISION BY ZERO ERROR" ARE DIFFERENT.
• EACH EXCEPTION IS AN OBJECT (EXCEPTION OBJECT).
• EACH OBJECT HAS A TYPE (TYPE OR CLASS).
• THE TYPE OF EXCEPTIONS HELPS IN BETTER MANAGEMENT.
• JAVA HAS DIFFERENT CLASSES FOR THIS PURPOSE. SUCH AS
NULLPOINTEREXCEPTION OR CLASSCASTEXCEPTION.
• WE CAN ALSO CREATE NEW EXCEPTION CLASSES.
example
example
How to Create a New Exception Class
• THE NEW CLASS MUST BE A SUBCLASS OF EXCEPTION.
• There is a class named java.lang.Exception in Java.
• Subclasses of Exception can be thrown or caught.
• EXCEPTION CLASSES ARE USUALLY SIMPLE CLASSES.
• They have few and concise methods and attributes.
• However, like all classes, they can have various constructors, attributes, and methods.
• Typically, they have a parameterless constructor and a constructor with a string
parameter that specifies the error message.
java.io.IOException
create a new exception class in Java
finally
• The part that comes in finally is executed at the end of the try-
catch execution, no matter what.
• Whether an error is thrown or not, the execution of the finally
section is guaranteed at the end of the process.
In any situation
• Normal completion of the execution within the try block without throwing an
error.
• Forced exit from the try block (e.g., with return, break, or continue).
• An error is thrown within the try block and caught in the catch block.
• An error is thrown within the try block and not caught in any of the catch
blocks.
• ...
The finally block is suitable for releasing acquired resources in the try block. For
example, closing a file or terminating a connection to a database. However, every
resource except memory is automatically released by garbage collection.
example
Exception Classes and Hierarchies
IN A TRY-CATCH STATEMENT:
• IF WE CATCH A SPECIFIC TYPE OF EXCEPTION IN ONE CATCH BLOCK, WE
CANNOT CATCH ITS SUBCLASS IN A SUBSEQUENT CATCH BLOCK.
• IN THIS CASE, THE COMPILER REPORTS AN ERROR: UNREACHABLE CATCH
BLOCK.
Exception Inheritance
Suppose a method f() is overridden in a subclass.
u f() in the subclass cannot throw more exceptions than f() in the superclass.
u The types of exceptions thrown in a method in a subclass must be a subset
of or equal to the exceptions declared in the method in the superclass.
(This refers to the exceptions specified with the throws clause.)
u Otherwise, the compiler encounters errors.
Why can't a method in a subclass
throw more exceptions?
• IF THIS RULE DIDN'T EXIST, DEFINING THE CLASS CHILD WITHOUT ERROR WOULD
BE IMPOSSIBLE:
• IN THIS DEFINITION, THE IS-A RELATIONSHIP BETWEEN CHILD AND PARENT WOULD BE
VIOLATED IN SOME WAY.
• FOR EXAMPLE, THE COMPILER CANNOT FORCE THE METHOD "EXAMPLE" TO
CATCH OR THROW IOEXCEPTION.
Your turn!
Your turn!
Answer: compile error!!!!
What about this one
No error!!!
Thank you
Reflection
Instructor: Dr.Vahidi Asl
Mohammad-Moein Arabi
1
Table of Contents
● What is Reflection
● Examples
● Class Object
○ Method Object
○ Annotation Object
○ Field Object
● Examples of Reflection
● Dynamic Binding
● Dynamic Loading
● Generic
2
What is Reflection?
Sometimes the program need to know properties of itself at runtime.
● Number of class A methods
● The annotations of an specific method
● Invoke methods by knowing its name
● …
3
Example: RPC
Remote Procedure Call
4
Example: RPC
Bad smell code!
5
MyRPCServer rpcServer = new MyRPCServer();
if (input == "login")
rpcServer.login();
else if (input == "logout")
rpcServer.logout();
else if (input == "function1")
rpcServer.function1();
else if (input == "function2")
rpcServer.function2();
else if (input == "function3")
rpcServer.function3();
...
Example: Junit
Remember?
How JUnit knows which method
is a test method?
6
public class CalculatorTest {
@Test
public void testAdditionMethod() {
Calculator calculator = new Calculator();
int result = calculator.add(1, 1);
assertEquals(2, result);
}
}
How reflection can help us? :(
7
Class Object
Each class has only and only one object.
Properties:
● Class name
● What are the class methods
● Annotations of methods
● Which method is private and which is public
8
Get Class Object
String s1 = "ABC";
String s2 = "Java";
Person p1 = new Person("Ali Alavai");
Person p2 = new Person("Taghi Taghavi");
9
ABC
Java
Ali Alavai
Taghi Taghavi
String class object
Person class object
Get Class Object
10
How to get the class object?
1. <class name>.class
Class c1 = Person.class;
2. Pass the full name of class to forename method:
Class c2 = Class.forName("ir.javacup.Person");
3. Invoke getClass method on the class’s objects
Object o = new Person();
Class c3 = o.getClass();
c1 == c2?
c2 == c3?
Get Method
Call getMethod() on the class object.
Get a method object by specifying its name and parameters.
Then call that method with invoke() method.
11
Get Method
class Authenticate {
public void login(String username, String password){}
...
}
Authenticate authenticate = new Authenticate();
Class classObject = Authenticate.getClass();
Method login1 = classObject.getMethod("login", String.class, String.class);
login1.invoke(authenticate, "ali1383", "abc@1234");
12
Why getMethod() also gets parameters?
Get Method
class Authenticate {
public void login(String username, String password){}
public void login(String username, String email, String password){}
...
}
Authenticate authenticate = new Authenticate();
Class classObject = Authenticate.getClass();
Method login1 = classObject.getMethod("login", String.class, String.class);
Method login2 = classObject.getMethod("login", String.class, String.class, String.class);
13
What about primitive types?
14
Method method =
String.class.getMethod("substring", int.class);
Method m = Person.class.getMethod("f");
if(m.getReturnType().equals(void.class))
...
15
● int.class
● long.class
● void.class
Primitive data types reflection
Now we have a clean code solution for
the RPC implementation problem :)
16
Pass methods as parameter
In high level languages (e.g. Python) we can pass functions as parameter to
another function.
Also possible in C++ with pointers.
There is not a direct way to do this in Java. But Reflection… :)
Pass method object as parameter to another method!
17
Get Constructor
Get a constructor by calling getConstructor() method on the class object.
Like getMethod(), gets parameters.
Then calling newInstance() on the constructor object will create a new
object.
18
Get Constructor
Person() {
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
Person(String name) {
this.name = name;
}
19
Class personClass = Person.class;
Constructor cons = personClass.getConstructor(String.class);
Object o = cons.newInstance("Ali");
Person c = (Person) o;
Why newInstance return an Object class
object?
We will talk about it in generic section.
Get Annotations
Invoke getAnnotations() method:
● On class object to get an array of all class annotations.
● On method object to get an array of all method annotations.
getAnnotations() returns An array of Annotation objects
20
Get Annotations
@WebService
class Authenticate{
@HTTP500
@WebMethod
public void handle500(){}
21
Annotation[] annotations = Authenticate.class.getAnnotations();
for (Annotation annotation : annotations)
System.out.println(annotation.annotationType());
annotations= Authenticate.class.getMethod("handle500").getAnnotations();
for (Annotation a : annotations)
System.out.println(a.annotationType().getSimpleName());
Get Field
Invoke getFields() method. On class object to get an array of all class fields.
getFields() returns An array of Fields objects.
Change the value by calling set() method on a field object.
22
Get Field
class Person {
String name;
int age;
}
23
Person person = new Person();
Field[] fields = Person.class.getFields();
for(Field field:fields)
if(field.getName().equals("age")) {
Object value = field.get(circle);
field.set(person, 20);
}
Review: Dynamic Binding
Polymorphism…
animal.walk()
animal can be either Cat or Fish. At
runtime one of the walk methods will
be selected.
This is called Dynamic Binding.
24
Animal
abstract walk()
Cat
walk()
Fish
walk()
Dynamic Loading
When the class objects created?
● All of the class objects are not created and stored in memory
● If the program access the class, it will load in memory.
In other words, when the first instance is created, the class object created.
We call this Dynamic Loading in Java
25
Generic type tips
26
Generic & Reflection
public final class Constructor<T> extends Executable
public final class Class<T> implements Serializable,...
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, ...
27
Class personClass = Person.class;
Constructor cons = personClass.getConstructor(String.class);
Object new_person = cons.newInstance("Ali");
Person new_person = (Object) o;
Class<Person> personClass = Person.class;
Constructor<Person> cons =
personClass.getConstructor(String.class);
Person new_person = cons.newInstance("Ali");
Generic & Reflection
28
Calling .class on generic types is not
possible.
Why?
Because Type parameters will be removed at
runtime.
class GenericType<T> {
private T element;
public void f() {
Class c2 = element.getClass();
Class c1 = T.class;
}
}
Multithread cheat sheet
Dr. Mojtaba Vahidi Asl
Seyed Sadra Mousavi
Spring 1403
Constructors
1) Thread(Runnable target)
Exp. Thread t = new Thread(runnable);
2) Thread(Runnable target, String name)
Exp. Thread t = new Thread(runnable, firstThread);
3) Thread(ThreadGroup group, Runnable target)
Exp. Thread t = new Thread(g1, runnable);
4) Thread(ThreadGroup group, Runnable target, String name)
Exp. Thread t = new Thread(g1, runnable, t1);
2
Methods
1) start(): With this method, thread starts its work.
Exp. exampleThread.start();
2) run(): Thread will do the body of this method.
3) getState(): This method returns the state of this thread.
Exp. exampleThread.getState();
4)isAlive(): This method returns true if this thread is alive.
Exp. exampleThread.isAlive();
3
Methods
5) getName(): It returns the name of the thread.
Exp. exampleThread.getName();
6) setName(String name): It changes the name of this thread to
argument String.
Exp. exapleThread.setName(“test”);
7) join(): Wait for this thread to die.
Exp. exampleThread.join();
8) interrupt(): This method interrupts this thread.
Exp. exampleThread.interrupt();
4
Methods
9) isInterrupted(): Checks whether this thread is interrupted or not.
Exp. exampleThread.isInterrupted();
10) getPriority(): This method returns the priority of this thread.
Exp. exampleThread.getPriority();
11) setPriority(int p): This method changes the priority of this thread to
p. p should be an integer between 1 and 10.
Exp. exampleThread.setPriority(7);
12) setDaemon(Boolean on): Set this thread as either daemon or user
thread.
Exp. exampleThread.setDaemon(true);
5
Methods
13) isDeamon(): Checks whether this thread is daemon or not.
Exp. exampleThread.isDeamon();
14) sleep(long miliSec): Makes this thread to sleep for miliSec.
Exp. exampleThread.sleep(1000);
15) wait(): Causes this thread to wait until another thread call notify or
notifyAll.
Exp. exampleThread.wait();
16) notify(): Wakes up a single thread that is waiting on this object’s monitor.
Exp. exampleThread.notify();
PRESENTATION TITLE 6
Methods
17) notifyAll(): Wakes up all threads that are waiting on this object’s
monitor.
Exp. exampleThread.notifyAll();
PRESENTATION TITLE 7
sources
https://www.geeksforgeeks.org/java-lang-thread-class-java/.
https://www.developer.com/java/java-thread-methods/.
https://www.baeldung.com/java-wait-notify.
PRESENTATION TITLE 8
Thanks for your
attention
Java Socket Programming
Amirhossein Sadr
Course: AP SPRING 2024
Instructor: Dr. Mojtaba Vahidi Asl
1
Recap: Client-Server Communication Paradigm
Typical network app has two
pieces: client and server
application
transport
network
data link
physical
application
transport
network
data link
physical
Client:
initiates contact with server
(“speaks first”)
typically requests service from
server
request
reply
Server:
provides requested service to client
2
How do clients and servers communicate?
API: application programming interface
• defines interface between application
and transport layer
• socket: Internet API
• two processes communicate by sending
data into socket, reading data out of
socket
Question: how does a process “identify”
the other process with which it wants
to communicate?
• IP address of host running other process
• “port number” - allows receiving host to
determine to which local process the
message should be delivered
… more on this later.
3
Recap: IP & Ports
• In computer networking, a port or port number is a number assigned
to uniquely identify a connection endpoint and to direct data to a
specific service. At the software level, within an operating system, a
port is a logical construct that identifies a specific process or a type
of network service. A port at the software level is identified for
each transport protocol and address combination by the port number
assigned to it. The most common transport protocols that use port
numbers are the Transmission Control Protocol (TCP) and the User
Datagram Protocol (UDP); those port numbers are 16-bit unsigned
numbers. port numbers lower than 1024 identify the historically
most commonly used services and are called the well-known
port numbers.
4
Recap: IP & Ports
• The Internet Protocol (IP) is the network layer communications
protocol in the Internet Protocol Suite for relaying datagrams across
network boundaries.
• IP has the task of delivering packets from the source host to the
destination host solely based on the IP addresses in the
packet headers.
• An Internet Protocol address (IP address) is a numerical label such
as 192.0.2.1 that is assigned to a device connected to a computer
network that uses the Internet Protocol for communication. IP
addresses serve two main functions: network interface identification,
and location addressing.
5
Additional: Wireshark
How to install?
https://www.geeksforgeeks.org/how-to-install-wireshark-on-windows/
6
Additional: Wireshark
7
Sockets
Socket: a door between application process and end-to-end
transport protocol (UCP or TCP)
process
kernel
buffers,
variables
socket
controlled by
application
developer
controlled by
operating
system
host or
server
process
kernel
buffers,
variables
socket
controlled by
application
developer
controlled by
operating
system
host or
server
internet
8
Decisions
• Before you go to write socket code, decide
• Do you want a TCP-style reliable, full duplex, connection oriented channel?
Or do you want a UDP-style, unreliable, message oriented channel?
• Will the code you are writing be the client or the server?
• Client: you assume that there is a process already running on another machines that you
need to connect to.
• Server: you will just start up and wait to be contacted
9
Socket Programming is Easy
• Create socket much like you open a file
• Once open, you can read from it and write to it
• Operating System hides most of the details
10
Socket Programming
Two socket types for two transport services:
• UDP: unreliable datagram
• TCP: reliable, byte stream-oriented
Application Example:
• client reads a line of characters (data) from its keyboard and sends
data to server
• server receives the data and converts characters to uppercase
• server sends modified data to client
• client receives modified data and displays line on its screen
11
Socket Programming: Basics
• The server application must be running before the client can send
anything.
• The server must have a socket through which it sends and receives
messages. The client also need a socket.
• Locally, a socket is identified by a port number.
• In order to send messages to the server, the client needs to know the
IP address and the port number of the server.
Port number is analogous to an apartment number. All doors (sockets)
lead into the building, but the client only has access to one of them,
located at the provided number.
12
OVERVIEW: TCP vs UDP
TCP service:
• connection-oriented: setup
required between client, server
• reliable transport between sending
and receiving process
• flow control: sender won’t
overwhelm receiver
• congestion control: throttle sender
when network overloaded
• does not provide: timing or
minimum bandwidth guarantees
UDP service:
• unreliable data transfer
between sending and receiving
process
• does not provide: connection
setup, reliability, flow control,
congestion control, timing, or
bandwidth guarantee
13
Socket Programming with TCP
client must contact server
• server process must first be running
• server must have created socket
(door) that welcomes clientʼs
contact
client contacts server by:
• Creating TCP socket, specifying IP
address, port number of server
process
• when client creates socket: client
TCP establishes connection to server
TCP
14
Socket Programming with TCP
• when contacted by client, server
TCP creates new socket for server
process to communicate with that
particular client
• allows server to talk with
multiple clients
• source port numbers used to
distinguish clients (more in
Chap 3)
TCP provides reliable, in-order
byte-stream transfer (“pipe”)
between client and server
application viewpoint:
15
Pseudo code TCP server
• Create socket (doorbellSocket)
• Bind socket to a specific port where clients can contact you
• Register with the kernel your willingness to listen that on socket for client to
contact you
• Loop
Listen to doorbell Socket for an incoming connection, get a connectSocket
Read and Write Data Into connectSocket to Communicate with client
Close connectSocket
• End Loop
• Close doorbellSocket
16
Pseudo code TCP client
• Create socket, connectSocket
• Do an active connect specifying the IP address and port number of
server
• Read and Write Data Into connectSocket to Communicate with server
• Close connectSocket
17
Socket Programming with UDP
UDP: no “connection” between client & server
• no handshaking before sending data
• sender explicitly attaches IP destination address and port # to each packet
• receiver extracts sender IP address and port# from received packet
UDP: transmitted data may be lost or received out-of-order
Application viewpoint:
UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server
18
Pseudo code UDP server
• Create socket
• Bind socket to a specific port where clients can contact you
• Loop
(Receive UDP Message from client x)+
(Send UDP Reply to client x)*
• Close Socket
19
Pseudo code UDP client
• Create socket
• Loop
(Send Message To Well-known port of server)+
(Receive Message From Server)
• Close Socket
20
Two Different Server Behaviors
• Iterative server
• At any time, only handles one client request
• Concurrent server
• Multiple client requests can be handled
simultaneously
• create a new process/thread to handle
each request
for (;;) {
accept a client request;
handle it
}
for (;;) {
accept a client request;
create a new process / thread to
handle request;
parent process / thread continues
}
21
Concurrent/Multithreaded TCP Servers
• What good is the doorbell socket? Can’t accept new connections until
call accept again anyway?
• Benefit comes in ability to hand off processing to another process or
thread
• Parent process creates the “door bell” or “welcome” socket on well-known
port and waits for clients to request connection
• When a client does connect, fork off a child process or pass to another thread
to handle that connection so that parent can return to waiting for
connections as soon as possible
22
Pseudo code concurrent TCP server
• Create socket doorbellSocket
• Bind
• Listen
• Loop
Accept the connection, connectSocket
Fork
If I am the child
Read/Write connectSocket
Close connectSocket
exit
• EndLoop
• Close doorbellSocket
23
Related Links
• https://www.geeksforgeeks.org/design-a-concurrent-server-for-
handling-multiple-clients-using-fork/
• https://www.geeksforgeeks.org/introducing-threads-socket-
programming-java/
• https://www.geeksforgeeks.org/multithreaded-servers-in-java/
24
Related Links
25
TCP vs UDP
• TCP can use read/write (or recv/send) and source and destination are
implied by the connection; UDP must specify destination for each
datagram
• Sendto, recevfrom include address of other party
• TCP server and client code look quite different; UDP server and client
code vary mostly in who sends first
26
Java Sockets Programming
• The package java.net provides support for sockets programming (and
more).
• Typically you import everything defined in this package with:
import java.net.*;
27
Java Socket Programming API
• Class InetAddress
• Represents an Internet Protocol (IP) Address
• Class ServerSocket
• Connection-oriented server side socket
• Class Socket
• Regular connection-oriented socket (client)
• Class DatagramSocket
• Connectionless socket
28
InetAddress class
• static methods you can use to create new InetAddress objects.
• getByName(String host)
• getAllByName(String host)
• getLocalHost()
InetAddress x = InetAddress.getByName(
“cse.unr.edu”);
• Throws UnknownHostException
29
Sample Code: Lookup.java
• Uses InetAddress class to lookup hostnames found on
command line.
> java Lookup cse.unr.edu www.yahoo.com
cse.unr.edu:134.197.40.9
www.yahoo.com:209.131.36.158
30
try {
InetAddress a = InetAddress.getByName(hostname);
System.out.println(hostname + ":" +
a.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("No address found for " +
hostname);
}
31
Socket class
• Corresponds to active TCP sockets only!
• client sockets
• socket returned by accept();
• Passive sockets are supported by a different class:
• ServerSocket
• UDP sockets are supported by
• DatagramSocket
32
Java TCP Sockets
• java.net.Socket
• Implements client sockets (also called just “sockets”).
• An endpoint for communication between two machines.
• Constructor and Methods
• Socket(String host, int port): Creates a stream socket and connects it to
the specified port number on the named host.
• InputStream getInputStream()
• OutputStream getOutputStream()
• close()
33
Java TCP Sockets
• java.net.ServerSocket
• Implements server sockets.
• Waits for requests to come in over the network.
• Performs some operation based on the request.
• Constructor and Methods
• ServerSocket(int port)
• Socket Accept(): Listens for a connection to be made to this
socket and accepts it. This method blocks until a connection is
made.
34
Socket Constructors
• Constructor creates a TCP connection to a named TCP server.
• There are a number of constructors:
Socket(InetAddress server, int port);
Socket(InetAddress server, int port,
InetAddress local, int localport);
Socket(String hostname, int port);
35
Socket Methods
void close();
InetAddress getInetAddress();
InetAddress getLocalAddress();
InputStream getInputStream();
OutputStream getOutputStream();
• Lots more (setting/getting socket options, partial close, etc.)
36
Socket I/O
• Socket I/O is based on the Java I/O support
• in the package java.io
• InputStream and OutputStream are abstract classes
• common operations defined for all kinds of InputStreams,
OutputStreams…
37
InputStream Basics
// reads some number of bytes and
// puts in buffer array b
int read(byte[] b);
// reads up to len bytes
int read(byte[] b, int off, int len);
Both methods can throw IOException.
Both return –1 on EOF.
38
OutputStream Basics
// writes b.length bytes
void write(byte[] b);
// writes len bytes starting
// at offset off
void write(byte[] b, int off, int len);
Both methods can throw IOException.
39
ServerSocket Class (TCP Passive Socket)
• Constructors:
ServerSocket(int port);
ServerSocket(int port, int backlog);
ServerSocket(int port, int backlog,
InetAddress bindAddr);
40
ServerSocket Methods
Socket accept();
void close();
InetAddress getInetAddress();
int getLocalPort();
throw IOException, SecurityException
41
Example: Java server (TCP)
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket doorbellSocket = new ServerSocket(6789);
while(true) {
Socket connectSocket = doorbellSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new
InputStreamReader(connectSocket.getInputStream()));
Create
welcoming socket
at port 6789
Wait, on welcoming
socket for contact
by client
Create input
stream, attached
to socket
42
Example: Java server (TCP), cont
DataOutputStream outToClient =
new DataOutputStream(connectSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + 'n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
Read in line
from socket
Create output
stream, attached
to socket
Write out line
to socket
End of while loop,
loop back and wait for
another client connection
43
Example: Java client (TCP)
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket connectSocket = new Socket("hostname", 6789);
DataOutputStream outToServer =
new DataOutputStream(connectSocket.getOutputStream());
Create
input stream
Create
client socket,
connect to server
Create
output stream
attached to socket
44
Example: Java client (TCP), cont.
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(connectSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + 'n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
connectSocket.close();
}
}
Create
input stream
attached to socket
Send line
to server
Read line
from server
45
Client/server socket interaction: TCP (Java)
wait for incoming
connection request
connectSocket =
welcomeSocket.accept()
create socket,
port=x, fincoming request:
or
doorbellSocket =
ServerSocket()
create socket,
connect to hostid, port=x
connectSocket =
Socket()
close
connectSocket
read reply from
connectSocket
close
connectSocket
Server (running on hostid) Client
send request using
connectSocket
read request from
connectSocket
write reply to
connectSocket
TCP
connection setup
46
TCP Server vs Client
• Server waits to accept connection on well known port
• Client initiates contact with the server
• Accept call returns a new socket for this client connection, freeing
welcoming socket for other incoming connections
• Read and write only (addresses implied by the connection)
47
Sample Echo Server
TCPEchoServer.java
Simple TCP Echo server.
Based on code from:
TCP/IP Sockets in Java
48
UDP Sockets
• DatagramSocket class
• DatagramPacket class needed to specify the payload
• incoming or outgoing
49
Java UDP Sockets
• In Package java.net
• java.net.DatagramSocket
• A socket for sending and receiving datagram packets.
• Constructor and Methods
• DatagramSocket(int port): Constructs a datagram socket and binds it to the specified
port on the local host machine.
• void receive( DatagramPacket p)
• void send( DatagramPacket p)
• void close()
50
DatagramSocket Constructors
DatagramSocket();
DatagramSocket(int port);
DatagramSocket(int port, InetAddress a);
All can throw SocketException or SecurityException
51
Datagram Methods
void connect(InetAddress, int port);
void close();
void receive(DatagramPacket p);
void send(DatagramPacket p);
Lots more!
52
Datagram Packet
• Contain the payload
• (a byte array)
• Can also be used to specify the destination address
• when not using connected mode UDP
53
DatagramPacket Constructors
For receiving:
DatagramPacket( byte[] buf, int len);
For sending:
DatagramPacket( byte[] buf, int len
InetAddress a, int port);
54
DatagramPacket methods
byte[] getData();
void setData(byte[] buf);
void setAddress(InetAddress a);
void setPort(int port);
InetAddress getAddress();
int getPort();
55
Example: Java server (UDP)
import java.io.*;
import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
Create
datagram socket
at port 9876
Create space for
received datagram
Receive
datagram
56
Example: Java server (UDP), cont
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
}
}
}
Get IP addr
port #, of
sender
Write out
datagram
to socket
End of while loop,
loop back and wait for
another datagram
Create datagram
to send to client
57
Example: Java client (UDP)
import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("hostname");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
Create
input stream
Create
client socket,
DatagramSocket,
but no port
Translate
hostname to IP
address using DNS
58
Example: Java client (UDP), cont.
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
Create datagram
with data-to-send,
length, IP addr, port
Send datagram
to server
Read datagram
from server
59
Client/server socket interaction: UDP
close
clientSocket
Server (running on hostid)
read reply from
clientSocket
create socket,
clientSocket =
DatagramSocket()
Client
Create, address (hostid, port=x,
send datagram request
using clientSocket
create socket,
port=x, for
incoming request:
serverSocket =
DatagramSocket()
read request from
serverSocket
write reply to
serverSocket
specifying client
host address,
port umber
60
UDP Server vs Client
• Server has a well-known port number
• Client initiates contact with the server
• Less difference between server and client code than in TCP
• Both client and server bind to a UDP socket, server specifies port while client
does not
• Not accept for server and connect for client
• Client send to the well-known server port; server extracts the client’s
address from the datagram it receives
61
Sample UDP code
UDPEchoServer.java
Simple UDP Echo server.
Test using nc as the client (netcat):
> nc –u hostname port
62
Socket Programming in the Real World
• Download some open source implementations of network
applications
• Web browsers (Firefox)
• DNS Servers and resolvers (BIND)
• Email clients/servers (sendmail, qmail, pine)
• telnet
• Can you find the socket code? The protocol processing? What
percentage of the code is it? What does the rest of the code do?
63
Questions?
64
Resources
• Introduction to Computer Networks Slides By Amirhossein Sadr
• Dr. Mojtaba Vahidi Asl Slides
• Dr. Sadegh Aliakbari Slides
• Other Universites Slides
65
Thanks!
66

More Related Content

Similar to AP slides - Spring 1403 - Workshop Team

Git Memento of basic commands
Git Memento of basic commandsGit Memento of basic commands
Git Memento of basic commandsZakaria Bouazza
 
Git Commands Every Developer Should Know?
Git Commands Every Developer Should Know?Git Commands Every Developer Should Know?
Git Commands Every Developer Should Know?9 series
 
Learning git
Learning gitLearning git
Learning gitSid Anand
 
Let's Git this Party Started: An Introduction to Git and GitHub
Let's Git this Party Started: An Introduction to Git and GitHubLet's Git this Party Started: An Introduction to Git and GitHub
Let's Git this Party Started: An Introduction to Git and GitHubKim Moir
 
Hacktoberfest intro to Git and GitHub
Hacktoberfest intro to Git and GitHubHacktoberfest intro to Git and GitHub
Hacktoberfest intro to Git and GitHubDSC GVP
 
Git session Dropsolid.com
Git session Dropsolid.comGit session Dropsolid.com
Git session Dropsolid.comdropsolid
 
Git walkthrough
Git walkthroughGit walkthrough
Git walkthroughBimal Jain
 
Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)
Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)
Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)Ahmed El-Arabawy
 
Git_tutorial.pdf
Git_tutorial.pdfGit_tutorial.pdf
Git_tutorial.pdfAliaaTarek5
 
Version control with GIT
Version control with GITVersion control with GIT
Version control with GITZeeshan Khan
 

Similar to AP slides - Spring 1403 - Workshop Team (20)

Git Memento of basic commands
Git Memento of basic commandsGit Memento of basic commands
Git Memento of basic commands
 
Git Commands Every Developer Should Know?
Git Commands Every Developer Should Know?Git Commands Every Developer Should Know?
Git Commands Every Developer Should Know?
 
390a gitintro 12au
390a gitintro 12au390a gitintro 12au
390a gitintro 12au
 
Learning git
Learning gitLearning git
Learning git
 
1-Intro to VC & GIT PDF.pptx
1-Intro to VC & GIT PDF.pptx1-Intro to VC & GIT PDF.pptx
1-Intro to VC & GIT PDF.pptx
 
Git training v10
Git training v10Git training v10
Git training v10
 
Git training (basic)
Git training (basic)Git training (basic)
Git training (basic)
 
Let's Git this Party Started: An Introduction to Git and GitHub
Let's Git this Party Started: An Introduction to Git and GitHubLet's Git this Party Started: An Introduction to Git and GitHub
Let's Git this Party Started: An Introduction to Git and GitHub
 
Hacktoberfest intro to Git and GitHub
Hacktoberfest intro to Git and GitHubHacktoberfest intro to Git and GitHub
Hacktoberfest intro to Git and GitHub
 
Git training
Git trainingGit training
Git training
 
Git and github
Git and githubGit and github
Git and github
 
Use Git like a pro - condensed
Use Git like a pro - condensedUse Git like a pro - condensed
Use Git like a pro - condensed
 
簡單介紹git
簡單介紹git簡單介紹git
簡單介紹git
 
Git session Dropsolid.com
Git session Dropsolid.comGit session Dropsolid.com
Git session Dropsolid.com
 
Git slides
Git slidesGit slides
Git slides
 
Git walkthrough
Git walkthroughGit walkthrough
Git walkthrough
 
Git and Github
Git and GithubGit and Github
Git and Github
 
Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)
Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)
Embedded Systems: Lecture 11: Introduction to Git & GitHub (Part 2)
 
Git_tutorial.pdf
Git_tutorial.pdfGit_tutorial.pdf
Git_tutorial.pdf
 
Version control with GIT
Version control with GITVersion control with GIT
Version control with GIT
 

Recently uploaded

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 

Recently uploaded (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 

AP slides - Spring 1403 - Workshop Team

  • 1. Presented By Amirhossein Sadr AP SPRING 2024 Course Lectured By Dr. Mojtaba Vahidi Asl
  • 2. 1. You are a programmer 2. You want to be a better programmer
  • 4. I like my code to be elegant and efficient Clean code does one thing well Bjarne Stroustrup
  • 5. Clean code is simple and direct Clean code reads like well-written prose Grady Booch
  • 6. Clean code can be read Clean code should be literate Dave Thomas
  • 7. Clean code always looks like it was written by someone who cares Michael Feathers
  • 8. Reduced Duplication, High Expressiveness and early building of simple abstractions Ron Jeffries
  • 9. You know you are working on clean code when each routine you reads turns out to be pretty much what you expected Ward Cunnigham
  • 17. Member Prefixes (Avoid encodings) Hungarian Notation (Avoid encodings)
  • 18. Member Prefixes (Avoid encodings) Hungarian Notation (Avoid encodings)
  • 22. Pick One Word Per Concept Don’t Pun
  • 23. Use Solution Domain Names Add Meaningful Context
  • 26. One Level of Abstraction per Function Reading Code from Top to Bottom
  • 34. Have No Side Effects
  • 35. Don’t Repeat Yourself (DRY) Structured Programming
  • 36. Comments Do Not Make Up for Bad Code Explain Yourself in Code
  • 53. The Purpose of Formatting The Newspaper Metaphor Vertical Openness Between Concepts
  • 62. Prefer Exceptions to returning Error Codes
  • 63. Prefer Exceptions to Returning Error Codes
  • 65. Error Handling Is One Thing
  • 71. The Three Laws of TDD
  • 73. One Assert per Test Single Concept per Test
  • 76. The Single Responsibility Principle (SRP) Cohesion
  • 77. Simple Design Rule 1: Runs All the Tests Simple Design Rules 2: No Duplication Simple Design Rules 3: Expressive Simple Design Rules 4: Minimal Classes and Methods
  • 78.
  • 79. Robert C. Martin, Clean Code (Prentice Hall, 2008) Based on Arturo Herrero Slides
  • 80.
  • 81. GIT Advanced programming Dr.Mojtaba Vahidi Asl Hoda attari Spring 403 (part 1)
  • 82. WHAT IS GIT ? • undo on steroids • Transfer code (allow you to collaborate with others ) • Merge codes
  • 83. WHAT IS GIT ? • Created by Linus Torvalds, April 2005. • A command line version control program • Distributed version control • Cross platform (including Windows) • Open source, free
  • 84. Git is a distributed version control system What is distributed version control? • “if you're not distributed, you're not worth using” –Linus Torvalds • No need to connect to central server • Can work without internet connection • No single failure point • Developers can work independently and merge their work later • Every copy of a git repository can serve either as the server or as a client • Git tracks changes, not versions • Branch of little change sets floating around
  • 89. Check installation and change author identity $ git –version $ git config –-global user.name “HodaAttari” $ git config –-global user.email “hoda.attari@gmail.com”
  • 90. What is repository ? • Turn the current folder into a git repo by creating a hidden .git folder inside it. $ git init • Get the overall status of the git repository (to be explained later) $ git status $ git status --short : The short version • Change default branch name: $ git config –-global init.defaultBranch main • Check all of your git config • $ git config –-list • $ git config <key name> e.g. $git config user.name • Local Vs remote repository
  • 91. Important components In order to save the repo’s state at a certain moment (equivalent to copying it into another directory so you can bring it back if you break it), we make commits. So each repo consists of many commits. There is a pointer called HEAD which refers to a certain commit. Git regards this commit as the “last save”. So it calculates your files’ changes relative to their “image” in this commit. The equivalent of copying into another directory would be that HEAD refers to the copied folder of the project.
  • 92. *The three state of git files Working directory: 1. Unchanged (committed) 2. Untracked (All the other types are technically “tracked”) 3. Modified 4. Deleted Also called the “Git Index” or simply “Index”
  • 93. Commands To Move Files Between States $ git add <filename> : stage modified/untracked file $ git add . : stage all modified/untracked files $ git add --all : stage modified/untracked file $ git commit –m “commit message” : commit the entire staging area $ git commit : commit the entire staging area ,but write “extended” commit message in editor. $ git commit –a –m “commit message” : stage and commit the entire staging area (does not track untracked files
  • 94. • Checking commit history $ git log • Use Enter Key to scroll down when the content does not fit in the terminal. • Use Q key to exit the scroll area. • Checking commit history (short version) $ git log --oneline
  • 95. • Change the editor git commit takes commit messages in Nano: $ git config –global core.editor “nano” VS Code: $ git config –global core.editor “code --wait” • Check What git’s current core editor is: $ git config –global core.editor $ git config core.editor
  • 96. Undoing things in git Restoring working directory changes • Use restore to do all types of restorations Unstage a staged file: $ git restore –-staged <filename> Restore a modified/deleted file (restores it from the stage, NOT from the last commit) $ git restore <filename> IDEs like VSCode and Intellij have git extensions that simplify the restoration process index head Working tree index
  • 97. Undoing things in git Restoring working directory changes $ git restore –-staged <filename> Working directory stage head
  • 98. Undoing things in git Restoring working directory changes $ git restore <filename> Working Dir stage head
  • 99. Undoing things in git Restoring working directory changes • Use restore to do all types of restorations Do both of the previous ones: $ git restore –-staged --worktree <filename> Head Working Dir index
  • 100. Undoing things in git Undoing Commits • Each commit is linked to the previous, parent commit. The differences made to the files between the two commits can easily be calculated by Git. • Use revert to undo the changes made in a specific commit $ git revert <ref> <ref> can be a commit hash (read from git log), or other things which we do not yet cover. Note that git revert undoes the changes in exactly the commit specified and does not work if you want to undo several commits at once An example will be covered in Project 2
  • 101. What is tag? Tag types: 1. Annotated: hold information about the author, date created, message, etc. 2. Lighweight: Only holds info about the commit it’s pointing to. • Creating and deleting Tags: $ git tag <tag name> Creates a lightweight tag on the most recent commit (HEAD) with the specified name $ git tag <tag name> <commit hash> Creates a lightweight tag on any commit (specified by hash) with the specified name $ git tag -a <tag name> -m “tag message” Creates an annotated tag on the most recent commit (HEAD)with the specified message and name. $ git tag -a <tag name> -m “tag message” <commit hash> Creates an annotated tag on the hash-specified commit with the specified message and name. $ git tag -d <tag name> Deletes a tag locally.
  • 102. • Reading tags $ git tag Lists the names of all tags $ git show <tag name> Show all the data the tag holds (including commit, message, author, date, etc.) • Pushing tags : git push origin does NOT push tags $ git push origin <tag name> Push the specified tag $ git push origin --tags Push all tags $ git push origin --delete <tag name> Delete tag from origin (git push does not sync tags) • Checking out tags $ git checkout <tag name> Check out the tag’s commit
  • 103. Git ignore • Creating .gitignore $ touch .gitignore Create the .gitignore file You can use the wildcard * in your .gitignore directives: *.txt => ignores all txt files (in ANY directory) You can ignore entire directories: hello/ => ignores the contents of hello/ directory ANYWHERE in the repo /hello/ => ignores the contents of hello/ directory ONLY in the root To prevent .gitignore’s recursive behavior, you can create .gitignores INSIDE of directories. The rules specified in those will not apply to parent directories. List of complete gitignore rules can be found here
  • 104. Thanks for your attention
  • 105. GIT Advanced programming Dr.Mojtaba Vahidi Asl Hoda attari Spring 403 (part 2)
  • 107. Git Stores “Snapshots” of the files in each commit But it’s also easy for Git to see the changes between any two commits
  • 108. Git stores commits as a DAG (a directed acyclic graph) in which each commit “points” to its parent commit(s). Its structure is very similar to linked lists. Git branches, and tags (and in specific cases HEAD) are references (pointers) to certain commits in the history Head, branches, and tags simply “point to commits” and also hold some metadata Last commit
  • 109. As we have already mentioned, branches are simply “pointers to commits”. When you make the first commit in your repository, a default branch, (names master or main) is automatically created and points to the commit you made. Master here is a branch: it points to the commit with the hash f30ab
  • 110. Branch Commands $ git branch List all branches. Puts a * beside the branch that HEAD currently points to. If HEAD is detached, will print the commit hash that HEAD points to. $ git branch <branch name> Creates a new branch with the given name to point to whatever commit HEAD is pointing to. $ git checkout -b <branch name> <commit hash> Checks out the given commit and also creates a new branch with the given name to point to it (the HEAD will point to the newly created branch, NOT the commit, so it will not be detached) $ git branch –d <branch name> Deletes the given branch name. $ git log --all Show commits and branches and tags for ALL branches, not just the current one’s
  • 111. What are branches for? • Better understanding reset: we have introduced used git reset here. Git reset is a simple git checkout with the difference that if HEAD is in normal state, the HEAD won’t be updated to point to the specified commit, but the branch that HEAD is pointing to will be updated to point to the specified commit 1 2 1 2 1 2 head master head master head master
  • 113. merging $ git merge <branch name> Merges <branch name> “into” whatever branch HEAD is pointing to. There are 2 types of merging: 1. Fast-Forward Merge 2. Three-Headed Merge We will first consider the simpler case: fast-forward merge
  • 114. c2 c1 If HEAD is on branch B1 pointing to commit C1 and there is a branch B2 that points to commit C2 such that C1 is an ancestor of C2 (meaning C1 was turned into C2 through a series of commits): Then calling the command $ git merge B2 Will result in a fast-forward merge. In this type of merge, the branch that the head points to will simply be updated to point to the same commit as the branch that has been merged into it (in this case B2) See the result on the next page B1 head B2 Earliest commit Most recent commit merging
  • 115. c2 c1 B1 head B2 Earliest commit Most recent commit Result
  • 116. Fast forwarding c2 c1 B1 head B2 c1 Earliest commit Most recent commit
  • 118. Suppose you have created a branch and have made a few commits to it. Meanwhile, the master branch has also advanced by a few commits (maybe another developer committed to master or you merged another branch into it.) Your repo will look like this: A B Master HEAD Branch
  • 119. Conflict If you make a mistake in the conflict resolution process and want to undo all changes you made in the process of merging, use: $ git merge --abort General conflict Note that merging is not the only place you will encounter conflicts. We will see later on that conflicts arise when we are pulling from remotes as well. Merge conflicts are not based on line numbers: Git is pretty smart about comparing files and changes. It is incorrect to think that the only way git compares to see if two branches have a merge conflict is by comparing their changes to identical line numbers in files. The Project on the next page will illuminate this concept.
  • 120. Gitignore • Blank lines are ignored • Lines starting with # are ignored (comments) • Wildcards are used! • *.file → All files withe .file extention • !name.file → ! specifies a negation or exception. All files withe .file extention, except name.file Note: ignore large files, passwords, unnecessary files, etc.
  • 121. GitHub • remote: where should I upload my git projects git remote add origin <link of repo> Find repo link on GitHub page • push: the act of uploading the git project git push origin master Master → any other branch • clone: download the whole git project git clone <repo link> • pull: check for updates in the remote git git pull origin master • Fetch and merge! • pull = fetch + merge
  • 122.
  • 123. Revert and reset • revert vs. reset • Revert: take a previous commit and add it as a new commit, keeping the log intact. • Reset: move back to a previous commit, discarding any changes made after that commit. • git revert [commit_id or hash] • git reset --hard [commit_hash] • we can find commit hash from : git log --oneline Note: (undo reset!) Even though the commits are no longer showing up in the log, it is not removed from git. → If you know the commit hash you can reset to it.
  • 124. Last tips • search & use help & read documentation • don’t panic • everything messed up: re-clone! • test new commands in a toy repository • don't commit large files • don't re-write public history • pull before push, even better, pull before starting coding
  • 125. Thanks for your attention
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 132.
  • 133.
  • 135. ü username@domain.com ü user.name@domain.com ü user-name@domain.com ü username@domain.co.in ü user_name@domain.com × username.@domain.com × .user.name@domain.com × user-name@domain.com. × username@.com
  • 136.
  • 137.
  • 138. OOP Review Slides and Presentation by Farzin Haj Gholamrezaei Instructor: Dr.Vahidi Asl Advanced Programming Workshop 1402 Spring semester
  • 139. OOP Review Why Object Oriented Programming? Faster and easier to execute Clear structure for programming Easier to maintain, modify and debug Reusability with less code and shorter development time
  • 142. OOP Review Class methods Return type Method’s name Method’s parameters
  • 150. UML
  • 154. Unit Test Instructor: Dr.Vahidi Asl Mohammad-Moein Arabi 1
  • 155. Table of contents ● The Importance of testing softwares ● Unit Test ● JUnit in Java ● Best practices in writing tests ● Advance JUnit ● Additional topics ○ GitHub workflows ○ Code coverage 2
  • 156. Naive Approach ● Print the program’s state to standard output! ● Check the output of each method one by one manually. ● Before releasing software, add Main class to test each function and then remove it! (Not reusing tests) 3
  • 157. The problem with this way ● Low speed developing. ● Not cover all lines of code. ● Not reusing tests. ● The programmer must run tests manually. ● The programmer himself must ensure the test passes or not. 4
  • 158. Benefits of Auto Testing Let a program tests the program! ● High speed developing ● More accurate ● Debug easier after finding bugs ● Reuse tests ● Reports how many tests pass and fails 5
  • 159. What is Unit Test? ● An automated test code ● Written and maintained by the developer ● Tests a function or an small section ● The result of every test is pass or fail 6
  • 162. Write your first unit tests 9
  • 163. Unit Test in Java JUnit framework Not officially packed with JVM. Should be installed as a dependency. JUnit4 last release was v4.13.2 on Feb 2021 JUnit5 is the last major update. 10
  • 164. Download Junit 1. The official GitHub page 2. Dependency management in Intellij 11
  • 165. Class Calculator class Calculator { public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } public int multiply(int a, int b) { return a * b; } } 12
  • 166. import org.junit.Test; import static org.junit.Assert.assertEquals; public class CalculatorTest { @Test public void testAdditionMethod() { Calculator calculator = new Calculator(); int result = calculator.add(1, 1); assertEquals(2, result); } } 13 1. Create CalculatorTest class
  • 167. import org.junit.Test; import static org.junit.Assert.assertEquals; public class CalculatorTest { @Test public void testAdditionMethod() { Calculator calculator = new Calculator(); int result = calculator.add(1, 1); assertEquals(2, result); } } 14 1. Create CalculatorTest class 2. Add a new method to test add method
  • 168. import org.junit.Test; import static org.junit.Assert.assertEquals; public class CalculatorTest { @Test public void testAdditionMethod() { Calculator calculator = new Calculator(); int result = calculator.add(1, 1); assertEquals(2, result); } } 15 1. Create CalculatorTest class 2. Add a new method to test add method 3. Invoke add method in the test method assert the result
  • 169. import org.junit.Test; import static org.junit.Assert.assertEquals; public class CalculatorTest { @Test public void testAdditionMethod() { Calculator calculator = new Calculator(); int result = calculator.add(1, 1); assertEquals(2, result); } } 16 1. Create CalculatorTest class 2. Add a new method to test add method 3. Invoke add method in the test method assert the result 4. Add Test annotation to the test method
  • 170. import org.junit.Test; import static org.junit.Assert.assertEquals; public class CalculatorTest { @Test public void testAdditionMethod() { Calculator calculator = new Calculator(); int result = calculator.add(1, 1); assertEquals(2, result); } } 17 1. Create CalculatorTest class 2. Add a new method to test add method 3. Invoke add method in the test method assert the result 4. Add Test annotation to the test method Junit will only run methods with Test annotation. How JUnit knows which method has Test annotation? Reflection
  • 171. class Calculator { public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } public int multiply(int a, int b) { return a * b; } } 18 import org.junit.Test; import static org.junit.Assert.assertEquals; public class CalculatorTest { @Test public void testAdditionMethod() { Calculator calculator = new Calculator(); int result = calculator.add(1, 1); assertEquals(2, result); } }
  • 173. Good Test The properties of a good test: 1. Use meaningful names for test methods. 2. Each test method should test only one thing (Single Responsibility) 3. Tests should be independent of another test. 4. Use meaningful messages for fail reason. 20
  • 175. Assert methods 22 assertThrows assertThrows(ArithmeticException.class, () -> calculator.divide(1, 0)); assertTimeout assertTimeout(ofMinutes(2), () -> { // Perform task that takes less than 2 minutes. }); assertTrue assertTrue(5 > 3); assertFalse assertNotNull assertNotNull(getPersonName());
  • 176. Startup & Teardown Method 23 Before and after each test, these methods will be executed. public class BeforeAndAfterAnnotationsUnitTest { private List<String> list; @BeforeEach public void init() { System.out.println("startup"); list = new ArrayList<>(Arrays.asList("test1", "test2")); } @AfterEach public void teardown() { System.out.println("teardown"); list.clear(); } }
  • 177. Startup & Teardown Method 24 Executes only once. Before any tests and after all tests. class BeforeAllAndAfterAllAnnotationsUnitTest { @BeforeAll static void setup() { System.out.println("startup - creating DB connection"); } @AfterAll static void tearDown() { System.out.println("closing DB connection"); } }
  • 178. Compare JUnit v4 vs v5 25 JUnit 4 @Before @After @BeforeClass @AfterClass JUnit 5 @BeforeEach @AfterEach @BeforeAll @AfterAll
  • 179. Other Annotations 26 @DisplayName Declares a custom display name for the test class or test method. @Disabled Used to disable a test class or test method @Timeout lifecycle method if its execution exceeds a given duration.
  • 181. Test in GitHub A GitHub workflow is a configurable, automated process that executes one or more actions after each event (e.g. after pushing, after merging, …) GitHub can run our repository tests on its virtual machines! Shows passing or failing result to users. 28
  • 182. Code Coverage measures how many of your lines of code are executed when you run automated tests. Many tools are exists. One of them is Codecov 29
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188. 1. Create Model. Student.java : 2. Create Controller. StudentController.java :
  • 189. 3. Create View. StudentView.java : 4. Use the StudentController methods to demonstrate MVC design pattern usage. MVCPatternDemo.java : Output :
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195. Abstraction, interfaces & classes Advanced programming Dr. Mojtaba Vahidi Asl Seyed Sadra Mousavi Spring 1403
  • 196. What is abstraction? • Hiding implementation and showing only functionality to the user. • Example: Sending SMS. • You don’t know how SMS goes to the destination. You just know it goes where you want. • Another example: Driving a car. • You just push a pedal and it accelerates. You don’t know the details of this process. • Another example: Turning on the lights. • You don’t know the details of getting electricity to your home. You just know that if you push the button, the light will turn on.
  • 197. Abstraction in java • Abstraction can be achieved by abstract classes and interfaces. Abstract class Interface
  • 198. Abstract classes • They must be declared with an “abstract” keyword. • They can’t be instantiated. (we can’t make objects from them.) • They can have abstract and non-abstract methods. • They can have constructors and static methods. • They can have final methods that will force the subclass not to change the body of the method.
  • 200. Why we use abstract class? • It can be used as a template class for subclasses. • It can hold some common methods and their functionality so we don’t have to implement them every time.
  • 201. Interfaces • They must be declared with an “interface” keyword. • They are not class. So we can’t make objects of them. • Their fields modified as final. So we can’t change them with a setter or anything else. • All methods are abstract by default (unless you determine something else), So it isn’t necessary to write “abstract” keyword. • From Java 8, default and static methods were added to them. • From Java 9, private methods were added to them. • We use them for multiple inheritance.
  • 206. Why we use interface? • Interface help us in multiple inheritance which is a very big favor. • It holds the signatures of the methods which we need to be implemented. • It gives us loose coupling. • This means with interfaces, we make classes independent from each other. • Polymorphism is supported through interface.
  • 207. Difference between abstract class and interface • Abstract class is a class that can’t be instantiated and it can have abstract and non-abstract methods. • On the other hand, interface is something that makes the target class to implement a set of methods. • In abstract class we can implement some methods but we can’t do such thing in interface. • A class can inherit just one abstract class. But it can implement multiple interfaces.
  • 208. Interesting example for abstract classes and interfaces • You can use a general abstract class for walking and extend it for every hero instead of writing a walking method 114 times. • Also you can use an interface for every type of hero and put a set of methods there so that every hero from that type implements those methods.
  • 209. Inner classes (nested classes) • As it occurs from its name, these classes are in other classes. • There are 3 types of these classes: • 1) classes which are defined in other class. • 2) classes which are statically defined in other class. • 3) classes which are defined in a method from other class. (They aren’t popular.) • They all have some weird syntax.
  • 213. Object class • every class in java extends object class by default. • This class has some useful methods for itself. • Methods like: equals, getHashCode, toString, etc. • Equals and toString are the most useful methods of this class. • Equals returns result of comparing hash codes of two object.(You can override it to something else.) • toString returns this: class name + @ + hash code of the argument object.(You can override it to something else.)
  • 214. Polymorphism • It is one of the most important features of object-oriented programming. • It means doing an action in multiple ways. • there are 2 types of polymorphism. • 1) compile-time polymorphism which happens when you overload a static method in Java. • 2) run-time polymorphism which happens when you override a method.
  • 215. Example of compile-time polymorphism
  • 216. Example of run-time polymorphism
  • 217. Binding • Determining type of a variable or connecting a method call to the right body method is called binding. • There are two types of binding. • 1) static binding: when the type is determined at compiled time. If there is any private, static, final methods in class, there is static binding. • 2) dynamic binding: when the type is determined at run time.
  • 218. Example of static binding
  • 219. Example of dynamic binding
  • 220. Cloning • It means creating an exact copy of an object. • We have 2 ways to do such a thing. • 1) using the assignment operator to create a copy of that object. (It isn’t safe.) • 2) using clone() method to copy. This method is in cloneable interface and we should implement it first. • There are 2 types of cloning. • 1) Shallow copy which is not completely safe. • 2) Deep copy which is completely safe. • For more information check out https://www.geeksforgeeks.org/clone-method-in- java-2/.
  • 221. Sources • https://stackoverflow.com/questions/22085985/why-do-we- need-abstract-classes-in-java. • https://www.javatpoint.com/runtime-polymorphism-in-java. • https://www.w3schools.com/java/java_inner_classes.asp. • https://www.geeksforgeeks.org/clone-method-in-java-2/. • https://www.javatpoint.com/static-binding-and-dynamic- binding. • https://www.digitalocean.com/community/tutorials/abstract -class-in-java.
  • 222. Thanks for your attention
  • 224.
  • 226. Why is Java 8 important?
  • 231. Lambda Expressions Parameter {code block} -> AnotherParameter ( , )
  • 232. Lambda Expressions Parameter {code block} -> AnotherParameter ( , ) x -> x * x * 3.14 (x, y) -> x + y (x, str) -> { for(int i=0; i<x; i++) System.out.println(str); }
  • 235. Functional interfaces Functional interfaces is an interface with exactly one abstract method Java 8 and later support non-abstract methods in an interface called default methods. Runnable and Comparator are some functional interfaces. A lambda can be used as a functional interface
  • 236. Functional interfaces Available on java.util.function.* new
  • 237. Consumer Functional interface Parameters Return type Consumer One parameter Void BiConsumer Two parameter Void LongConsumer One long parameter Void
  • 238. Consumer Use .accept(…) to do the function BiConsumer can be useful in maps and pairs Since its void better to be used when outputting something to screen.
  • 239. Function Functional interface Parameters Return type Function One parameter Generic BiFunction Two parameter Generic DoubleFunction One double parameter Generic UnaryOperator One parameter Same as parameter BinaryOperator Two parameters of same type Same as parameter
  • 240. Function Use .apply(…) to do the function Use .andThen(…) to concat them BiFunction can be useful in maps and pairs Because it returns an object we can use :: (method refrence) and various functions.
  • 241. Supplier Functional interface Parameters Return type Supplier - Object IntSupplier - int BooleanSupplier - boolean
  • 242. Supplier Use .get(…) to do the function Because it returns an object we can use ::new
  • 243. Predicate Functional interface Parameters Return type Predicate One Parameter boolean BiPredicate Two Parameter boolean LongPredicate One long Parameter boolean
  • 244. Predicate Use .test(…) to do the function Use .and(…) .or(…) and .negate() BiFunction can be useful in maps and pairs Useful in conditions
  • 246. Streams We can use .stream() on all collections Has one terminal operation Use .foreach() to process each element Can have a few intermediate operation .filter(), .sorted(), .skip(), .limit(), .map(), .parallel(), .reduce(), .count(), .collect(), …
  • 249. Generics Imagine a list implementation in Java Does the type of content matter in the implementation? Why can’t we implement a list for each type? Why can’t we just use Object class?
  • 250. Generics This is how they did it.
  • 251. Generics This is how they did it. Can be useful when we don’t know or care about the type. Can use more than one generic Generics can extend something to be more limited
  • 252. Generics How to use? This future is called type inference and was introduced in java 7 The <> is called the diamond operator
  • 253. Generics A method can be generic too. A generic method does not need to be inside a generic class Controlling generic stuff is only at compile time There is no difference in byte code All types compile into their raw type This java behavior is called erasure
  • 257. Exceptions ADVANCED PROGRAMMING COURSE LECTURED BY DR.VAHIDI SPRING 1403 PRESENTER : SARA AKBARZADEH UNIVERSITY OF SHAHID BEHESHTI
  • 258. What IS THE PROBLEM HERE??
  • 259. What IS THE PROBLEM HERE?? For Special, Unusual, And Uncommon Cases, It Does Not Work Properly!!!!
  • 260. • The parameter "day" may be an incorrect value, such as “Hi" which is not a date. • The parameter "day" may not be in the desired format, like "29 Nov 2010." • The parameter "day" may be an empty string (""). • The parameter "day" may be null. We call these special cases exceptions.
  • 261. Handling exceptions What should we do with an exception? • For example, if the parameter of a method is not as we expect: u Should we terminate the program? • Imagine a wrong input causing the whole program to crash! • Should the method continue its execution and return a specific value (e.g., -1)? • Maybe it shouldn't return any value (void). • Can we determine a specific value as output? • Should we display the error as output? ANSWER : NONE!!!!!!!
  • 262. What is an Exception AN EXCEPTION IS AN UNUSUAL EVENT THAT OCCURS DURING THE EXECUTION OF A PROGRAM. IT DISRUPTS THE NORMAL FLOW OF THE PROGRAM. EXAMPLES: • INVALID INPUT • DIVISION BY ZERO • ACCESSING AN INDEX OUTSIDE THE BOUNDS OF AN ARRAY • HARD DISK FAILURES • OPENING A FILE THAT DOES NOT EXIST
  • 263. Default Behavior of Java When an Exception Occurs: By default, if an error or exception occurs during runtime: • The exception is detected by the Java Virtual Machine (JVM). • Some information about this exception is printed in the output. • The program execution is terminated abruptly. • However, this default behavior is usually not suitable.
  • 265. When an exception occurs, what happens? 1- An "exception object" is created. 2- The exception object is handed over to the Java Virtual Machine (JVM). This action is called "throwing an exception." The exception object contains information such as: • Error message • Details about the type of error • Line number in the program where the exception occurred 3- The normal execution flow of the program is halted.
  • 266. And also: 4- The JVM looks for a responsible entity to handle the exception (the "catch" block). • This responsible entity is called an exception handler. • The method call stack is traversed in order to find this block. • If such a block (exception handler) is found: • The thrown exception object is caught by this block. • Program execution continues from this block (normal execution is interrupted). • The information available in the exception object is used for better management of this specific situation. • If such a block is not found: • The "default Java behavior" in dealing with exceptions is executed. • (An error message is printed in the standard output, and the program execution terminates.)
  • 267.
  • 269. Rewriting the getYear method with exception handling
  • 270. How to use it
  • 271. Java keywords in the exception handling • THROW THROWS AN EXCEPTION. • THROWS IF A METHOD MAY THROW AN EXCEPTION, IT MUST DECLARE IT. • TRY BEGINS A BLOCK FOR EXCEPTION HANDLING. • CATCH RECEIVES AND HANDLES AN EXCEPTION.
  • 273. Separation of Error handling Codes CONSIDER THE PSEUDO-CODE BELOW: IT CALLS THE ENTIRE CONTENT OF A FILE INTO MEMORY.
  • 275. Concept of Stack Trace WHEN CATCHING AN EXCEPTION, THE FOLLOWING INFORMATION IS AVAILABLE IN THE EXCEPTION OBJECT: • THE ORIGINAL LOCATION WHERE THE EXCEPTION WAS THROWN. • THE STACK OF METHODS THAT THE EXCEPTION HAS PASSED THROUGH. A STACK TRACE IS A REPORT OF THE ACTIVE STACK FRAMES AT A PARTICULAR POINT IN TIME DURING THE EXECUTION OF A PROGRAM. IT CONTAINS INFORMATION ABOUT THE SEQUENCE OF METHOD CALLS THAT LED TO AN EXCEPTION OR ERROR, TYPICALLY INCLUDING: 1.THE CLASS AND METHOD NAMES. 2.THE FILE NAME AND LINE NUMBER IN THE SOURCE CODE WHERE EACH METHOD WAS CALLED. 3.ADDITIONAL CONTEXTUAL INFORMATION SUCH AS VARIABLE VALUES OR STATE OF THE PROGRAM.
  • 277. Exception Classes • EVERY EXCEPTION HAS A TYPE. • FOR INSTANCE, THE TYPE OF "ERROR WHEN READING A FILE" AND "DIVISION BY ZERO ERROR" ARE DIFFERENT. • EACH EXCEPTION IS AN OBJECT (EXCEPTION OBJECT). • EACH OBJECT HAS A TYPE (TYPE OR CLASS). • THE TYPE OF EXCEPTIONS HELPS IN BETTER MANAGEMENT. • JAVA HAS DIFFERENT CLASSES FOR THIS PURPOSE. SUCH AS NULLPOINTEREXCEPTION OR CLASSCASTEXCEPTION. • WE CAN ALSO CREATE NEW EXCEPTION CLASSES.
  • 280. How to Create a New Exception Class • THE NEW CLASS MUST BE A SUBCLASS OF EXCEPTION. • There is a class named java.lang.Exception in Java. • Subclasses of Exception can be thrown or caught. • EXCEPTION CLASSES ARE USUALLY SIMPLE CLASSES. • They have few and concise methods and attributes. • However, like all classes, they can have various constructors, attributes, and methods. • Typically, they have a parameterless constructor and a constructor with a string parameter that specifies the error message.
  • 282. create a new exception class in Java
  • 283. finally • The part that comes in finally is executed at the end of the try- catch execution, no matter what. • Whether an error is thrown or not, the execution of the finally section is guaranteed at the end of the process.
  • 284. In any situation • Normal completion of the execution within the try block without throwing an error. • Forced exit from the try block (e.g., with return, break, or continue). • An error is thrown within the try block and caught in the catch block. • An error is thrown within the try block and not caught in any of the catch blocks. • ... The finally block is suitable for releasing acquired resources in the try block. For example, closing a file or terminating a connection to a database. However, every resource except memory is automatically released by garbage collection.
  • 286.
  • 287.
  • 288. Exception Classes and Hierarchies IN A TRY-CATCH STATEMENT: • IF WE CATCH A SPECIFIC TYPE OF EXCEPTION IN ONE CATCH BLOCK, WE CANNOT CATCH ITS SUBCLASS IN A SUBSEQUENT CATCH BLOCK. • IN THIS CASE, THE COMPILER REPORTS AN ERROR: UNREACHABLE CATCH BLOCK.
  • 289. Exception Inheritance Suppose a method f() is overridden in a subclass. u f() in the subclass cannot throw more exceptions than f() in the superclass. u The types of exceptions thrown in a method in a subclass must be a subset of or equal to the exceptions declared in the method in the superclass. (This refers to the exceptions specified with the throws clause.) u Otherwise, the compiler encounters errors.
  • 290. Why can't a method in a subclass throw more exceptions? • IF THIS RULE DIDN'T EXIST, DEFINING THE CLASS CHILD WITHOUT ERROR WOULD BE IMPOSSIBLE: • IN THIS DEFINITION, THE IS-A RELATIONSHIP BETWEEN CHILD AND PARENT WOULD BE VIOLATED IN SOME WAY. • FOR EXAMPLE, THE COMPILER CANNOT FORCE THE METHOD "EXAMPLE" TO CATCH OR THROW IOEXCEPTION.
  • 297. Table of Contents ● What is Reflection ● Examples ● Class Object ○ Method Object ○ Annotation Object ○ Field Object ● Examples of Reflection ● Dynamic Binding ● Dynamic Loading ● Generic 2
  • 298. What is Reflection? Sometimes the program need to know properties of itself at runtime. ● Number of class A methods ● The annotations of an specific method ● Invoke methods by knowing its name ● … 3
  • 300. Example: RPC Bad smell code! 5 MyRPCServer rpcServer = new MyRPCServer(); if (input == "login") rpcServer.login(); else if (input == "logout") rpcServer.logout(); else if (input == "function1") rpcServer.function1(); else if (input == "function2") rpcServer.function2(); else if (input == "function3") rpcServer.function3(); ...
  • 301. Example: Junit Remember? How JUnit knows which method is a test method? 6 public class CalculatorTest { @Test public void testAdditionMethod() { Calculator calculator = new Calculator(); int result = calculator.add(1, 1); assertEquals(2, result); } }
  • 302. How reflection can help us? :( 7
  • 303. Class Object Each class has only and only one object. Properties: ● Class name ● What are the class methods ● Annotations of methods ● Which method is private and which is public 8
  • 304. Get Class Object String s1 = "ABC"; String s2 = "Java"; Person p1 = new Person("Ali Alavai"); Person p2 = new Person("Taghi Taghavi"); 9 ABC Java Ali Alavai Taghi Taghavi String class object Person class object
  • 305. Get Class Object 10 How to get the class object? 1. <class name>.class Class c1 = Person.class; 2. Pass the full name of class to forename method: Class c2 = Class.forName("ir.javacup.Person"); 3. Invoke getClass method on the class’s objects Object o = new Person(); Class c3 = o.getClass(); c1 == c2? c2 == c3?
  • 306. Get Method Call getMethod() on the class object. Get a method object by specifying its name and parameters. Then call that method with invoke() method. 11
  • 307. Get Method class Authenticate { public void login(String username, String password){} ... } Authenticate authenticate = new Authenticate(); Class classObject = Authenticate.getClass(); Method login1 = classObject.getMethod("login", String.class, String.class); login1.invoke(authenticate, "ali1383", "abc@1234"); 12 Why getMethod() also gets parameters?
  • 308. Get Method class Authenticate { public void login(String username, String password){} public void login(String username, String email, String password){} ... } Authenticate authenticate = new Authenticate(); Class classObject = Authenticate.getClass(); Method login1 = classObject.getMethod("login", String.class, String.class); Method login2 = classObject.getMethod("login", String.class, String.class, String.class); 13
  • 309. What about primitive types? 14
  • 310. Method method = String.class.getMethod("substring", int.class); Method m = Person.class.getMethod("f"); if(m.getReturnType().equals(void.class)) ... 15 ● int.class ● long.class ● void.class Primitive data types reflection
  • 311. Now we have a clean code solution for the RPC implementation problem :) 16
  • 312. Pass methods as parameter In high level languages (e.g. Python) we can pass functions as parameter to another function. Also possible in C++ with pointers. There is not a direct way to do this in Java. But Reflection… :) Pass method object as parameter to another method! 17
  • 313. Get Constructor Get a constructor by calling getConstructor() method on the class object. Like getMethod(), gets parameters. Then calling newInstance() on the constructor object will create a new object. 18
  • 314. Get Constructor Person() { } Person(String name, int age) { this.name = name; this.age = age; } Person(String name) { this.name = name; } 19 Class personClass = Person.class; Constructor cons = personClass.getConstructor(String.class); Object o = cons.newInstance("Ali"); Person c = (Person) o; Why newInstance return an Object class object? We will talk about it in generic section.
  • 315. Get Annotations Invoke getAnnotations() method: ● On class object to get an array of all class annotations. ● On method object to get an array of all method annotations. getAnnotations() returns An array of Annotation objects 20
  • 316. Get Annotations @WebService class Authenticate{ @HTTP500 @WebMethod public void handle500(){} 21 Annotation[] annotations = Authenticate.class.getAnnotations(); for (Annotation annotation : annotations) System.out.println(annotation.annotationType()); annotations= Authenticate.class.getMethod("handle500").getAnnotations(); for (Annotation a : annotations) System.out.println(a.annotationType().getSimpleName());
  • 317. Get Field Invoke getFields() method. On class object to get an array of all class fields. getFields() returns An array of Fields objects. Change the value by calling set() method on a field object. 22
  • 318. Get Field class Person { String name; int age; } 23 Person person = new Person(); Field[] fields = Person.class.getFields(); for(Field field:fields) if(field.getName().equals("age")) { Object value = field.get(circle); field.set(person, 20); }
  • 319. Review: Dynamic Binding Polymorphism… animal.walk() animal can be either Cat or Fish. At runtime one of the walk methods will be selected. This is called Dynamic Binding. 24 Animal abstract walk() Cat walk() Fish walk()
  • 320. Dynamic Loading When the class objects created? ● All of the class objects are not created and stored in memory ● If the program access the class, it will load in memory. In other words, when the first instance is created, the class object created. We call this Dynamic Loading in Java 25
  • 322. Generic & Reflection public final class Constructor<T> extends Executable public final class Class<T> implements Serializable,... public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, ... 27 Class personClass = Person.class; Constructor cons = personClass.getConstructor(String.class); Object new_person = cons.newInstance("Ali"); Person new_person = (Object) o; Class<Person> personClass = Person.class; Constructor<Person> cons = personClass.getConstructor(String.class); Person new_person = cons.newInstance("Ali");
  • 323. Generic & Reflection 28 Calling .class on generic types is not possible. Why? Because Type parameters will be removed at runtime. class GenericType<T> { private T element; public void f() { Class c2 = element.getClass(); Class c1 = T.class; } }
  • 324. Multithread cheat sheet Dr. Mojtaba Vahidi Asl Seyed Sadra Mousavi Spring 1403
  • 325. Constructors 1) Thread(Runnable target) Exp. Thread t = new Thread(runnable); 2) Thread(Runnable target, String name) Exp. Thread t = new Thread(runnable, firstThread); 3) Thread(ThreadGroup group, Runnable target) Exp. Thread t = new Thread(g1, runnable); 4) Thread(ThreadGroup group, Runnable target, String name) Exp. Thread t = new Thread(g1, runnable, t1); 2
  • 326. Methods 1) start(): With this method, thread starts its work. Exp. exampleThread.start(); 2) run(): Thread will do the body of this method. 3) getState(): This method returns the state of this thread. Exp. exampleThread.getState(); 4)isAlive(): This method returns true if this thread is alive. Exp. exampleThread.isAlive(); 3
  • 327. Methods 5) getName(): It returns the name of the thread. Exp. exampleThread.getName(); 6) setName(String name): It changes the name of this thread to argument String. Exp. exapleThread.setName(“test”); 7) join(): Wait for this thread to die. Exp. exampleThread.join(); 8) interrupt(): This method interrupts this thread. Exp. exampleThread.interrupt(); 4
  • 328. Methods 9) isInterrupted(): Checks whether this thread is interrupted or not. Exp. exampleThread.isInterrupted(); 10) getPriority(): This method returns the priority of this thread. Exp. exampleThread.getPriority(); 11) setPriority(int p): This method changes the priority of this thread to p. p should be an integer between 1 and 10. Exp. exampleThread.setPriority(7); 12) setDaemon(Boolean on): Set this thread as either daemon or user thread. Exp. exampleThread.setDaemon(true); 5
  • 329. Methods 13) isDeamon(): Checks whether this thread is daemon or not. Exp. exampleThread.isDeamon(); 14) sleep(long miliSec): Makes this thread to sleep for miliSec. Exp. exampleThread.sleep(1000); 15) wait(): Causes this thread to wait until another thread call notify or notifyAll. Exp. exampleThread.wait(); 16) notify(): Wakes up a single thread that is waiting on this object’s monitor. Exp. exampleThread.notify(); PRESENTATION TITLE 6
  • 330. Methods 17) notifyAll(): Wakes up all threads that are waiting on this object’s monitor. Exp. exampleThread.notifyAll(); PRESENTATION TITLE 7
  • 333. Java Socket Programming Amirhossein Sadr Course: AP SPRING 2024 Instructor: Dr. Mojtaba Vahidi Asl 1
  • 334. Recap: Client-Server Communication Paradigm Typical network app has two pieces: client and server application transport network data link physical application transport network data link physical Client: initiates contact with server (“speaks first”) typically requests service from server request reply Server: provides requested service to client 2
  • 335. How do clients and servers communicate? API: application programming interface • defines interface between application and transport layer • socket: Internet API • two processes communicate by sending data into socket, reading data out of socket Question: how does a process “identify” the other process with which it wants to communicate? • IP address of host running other process • “port number” - allows receiving host to determine to which local process the message should be delivered … more on this later. 3
  • 336. Recap: IP & Ports • In computer networking, a port or port number is a number assigned to uniquely identify a connection endpoint and to direct data to a specific service. At the software level, within an operating system, a port is a logical construct that identifies a specific process or a type of network service. A port at the software level is identified for each transport protocol and address combination by the port number assigned to it. The most common transport protocols that use port numbers are the Transmission Control Protocol (TCP) and the User Datagram Protocol (UDP); those port numbers are 16-bit unsigned numbers. port numbers lower than 1024 identify the historically most commonly used services and are called the well-known port numbers. 4
  • 337. Recap: IP & Ports • The Internet Protocol (IP) is the network layer communications protocol in the Internet Protocol Suite for relaying datagrams across network boundaries. • IP has the task of delivering packets from the source host to the destination host solely based on the IP addresses in the packet headers. • An Internet Protocol address (IP address) is a numerical label such as 192.0.2.1 that is assigned to a device connected to a computer network that uses the Internet Protocol for communication. IP addresses serve two main functions: network interface identification, and location addressing. 5
  • 338. Additional: Wireshark How to install? https://www.geeksforgeeks.org/how-to-install-wireshark-on-windows/ 6
  • 340. Sockets Socket: a door between application process and end-to-end transport protocol (UCP or TCP) process kernel buffers, variables socket controlled by application developer controlled by operating system host or server process kernel buffers, variables socket controlled by application developer controlled by operating system host or server internet 8
  • 341. Decisions • Before you go to write socket code, decide • Do you want a TCP-style reliable, full duplex, connection oriented channel? Or do you want a UDP-style, unreliable, message oriented channel? • Will the code you are writing be the client or the server? • Client: you assume that there is a process already running on another machines that you need to connect to. • Server: you will just start up and wait to be contacted 9
  • 342. Socket Programming is Easy • Create socket much like you open a file • Once open, you can read from it and write to it • Operating System hides most of the details 10
  • 343. Socket Programming Two socket types for two transport services: • UDP: unreliable datagram • TCP: reliable, byte stream-oriented Application Example: • client reads a line of characters (data) from its keyboard and sends data to server • server receives the data and converts characters to uppercase • server sends modified data to client • client receives modified data and displays line on its screen 11
  • 344. Socket Programming: Basics • The server application must be running before the client can send anything. • The server must have a socket through which it sends and receives messages. The client also need a socket. • Locally, a socket is identified by a port number. • In order to send messages to the server, the client needs to know the IP address and the port number of the server. Port number is analogous to an apartment number. All doors (sockets) lead into the building, but the client only has access to one of them, located at the provided number. 12
  • 345. OVERVIEW: TCP vs UDP TCP service: • connection-oriented: setup required between client, server • reliable transport between sending and receiving process • flow control: sender won’t overwhelm receiver • congestion control: throttle sender when network overloaded • does not provide: timing or minimum bandwidth guarantees UDP service: • unreliable data transfer between sending and receiving process • does not provide: connection setup, reliability, flow control, congestion control, timing, or bandwidth guarantee 13
  • 346. Socket Programming with TCP client must contact server • server process must first be running • server must have created socket (door) that welcomes clientʼs contact client contacts server by: • Creating TCP socket, specifying IP address, port number of server process • when client creates socket: client TCP establishes connection to server TCP 14
  • 347. Socket Programming with TCP • when contacted by client, server TCP creates new socket for server process to communicate with that particular client • allows server to talk with multiple clients • source port numbers used to distinguish clients (more in Chap 3) TCP provides reliable, in-order byte-stream transfer (“pipe”) between client and server application viewpoint: 15
  • 348. Pseudo code TCP server • Create socket (doorbellSocket) • Bind socket to a specific port where clients can contact you • Register with the kernel your willingness to listen that on socket for client to contact you • Loop Listen to doorbell Socket for an incoming connection, get a connectSocket Read and Write Data Into connectSocket to Communicate with client Close connectSocket • End Loop • Close doorbellSocket 16
  • 349. Pseudo code TCP client • Create socket, connectSocket • Do an active connect specifying the IP address and port number of server • Read and Write Data Into connectSocket to Communicate with server • Close connectSocket 17
  • 350. Socket Programming with UDP UDP: no “connection” between client & server • no handshaking before sending data • sender explicitly attaches IP destination address and port # to each packet • receiver extracts sender IP address and port# from received packet UDP: transmitted data may be lost or received out-of-order Application viewpoint: UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server 18
  • 351. Pseudo code UDP server • Create socket • Bind socket to a specific port where clients can contact you • Loop (Receive UDP Message from client x)+ (Send UDP Reply to client x)* • Close Socket 19
  • 352. Pseudo code UDP client • Create socket • Loop (Send Message To Well-known port of server)+ (Receive Message From Server) • Close Socket 20
  • 353. Two Different Server Behaviors • Iterative server • At any time, only handles one client request • Concurrent server • Multiple client requests can be handled simultaneously • create a new process/thread to handle each request for (;;) { accept a client request; handle it } for (;;) { accept a client request; create a new process / thread to handle request; parent process / thread continues } 21
  • 354. Concurrent/Multithreaded TCP Servers • What good is the doorbell socket? Can’t accept new connections until call accept again anyway? • Benefit comes in ability to hand off processing to another process or thread • Parent process creates the “door bell” or “welcome” socket on well-known port and waits for clients to request connection • When a client does connect, fork off a child process or pass to another thread to handle that connection so that parent can return to waiting for connections as soon as possible 22
  • 355. Pseudo code concurrent TCP server • Create socket doorbellSocket • Bind • Listen • Loop Accept the connection, connectSocket Fork If I am the child Read/Write connectSocket Close connectSocket exit • EndLoop • Close doorbellSocket 23
  • 356. Related Links • https://www.geeksforgeeks.org/design-a-concurrent-server-for- handling-multiple-clients-using-fork/ • https://www.geeksforgeeks.org/introducing-threads-socket- programming-java/ • https://www.geeksforgeeks.org/multithreaded-servers-in-java/ 24
  • 358. TCP vs UDP • TCP can use read/write (or recv/send) and source and destination are implied by the connection; UDP must specify destination for each datagram • Sendto, recevfrom include address of other party • TCP server and client code look quite different; UDP server and client code vary mostly in who sends first 26
  • 359. Java Sockets Programming • The package java.net provides support for sockets programming (and more). • Typically you import everything defined in this package with: import java.net.*; 27
  • 360. Java Socket Programming API • Class InetAddress • Represents an Internet Protocol (IP) Address • Class ServerSocket • Connection-oriented server side socket • Class Socket • Regular connection-oriented socket (client) • Class DatagramSocket • Connectionless socket 28
  • 361. InetAddress class • static methods you can use to create new InetAddress objects. • getByName(String host) • getAllByName(String host) • getLocalHost() InetAddress x = InetAddress.getByName( “cse.unr.edu”); • Throws UnknownHostException 29
  • 362. Sample Code: Lookup.java • Uses InetAddress class to lookup hostnames found on command line. > java Lookup cse.unr.edu www.yahoo.com cse.unr.edu:134.197.40.9 www.yahoo.com:209.131.36.158 30
  • 363. try { InetAddress a = InetAddress.getByName(hostname); System.out.println(hostname + ":" + a.getHostAddress()); } catch (UnknownHostException e) { System.out.println("No address found for " + hostname); } 31
  • 364. Socket class • Corresponds to active TCP sockets only! • client sockets • socket returned by accept(); • Passive sockets are supported by a different class: • ServerSocket • UDP sockets are supported by • DatagramSocket 32
  • 365. Java TCP Sockets • java.net.Socket • Implements client sockets (also called just “sockets”). • An endpoint for communication between two machines. • Constructor and Methods • Socket(String host, int port): Creates a stream socket and connects it to the specified port number on the named host. • InputStream getInputStream() • OutputStream getOutputStream() • close() 33
  • 366. Java TCP Sockets • java.net.ServerSocket • Implements server sockets. • Waits for requests to come in over the network. • Performs some operation based on the request. • Constructor and Methods • ServerSocket(int port) • Socket Accept(): Listens for a connection to be made to this socket and accepts it. This method blocks until a connection is made. 34
  • 367. Socket Constructors • Constructor creates a TCP connection to a named TCP server. • There are a number of constructors: Socket(InetAddress server, int port); Socket(InetAddress server, int port, InetAddress local, int localport); Socket(String hostname, int port); 35
  • 368. Socket Methods void close(); InetAddress getInetAddress(); InetAddress getLocalAddress(); InputStream getInputStream(); OutputStream getOutputStream(); • Lots more (setting/getting socket options, partial close, etc.) 36
  • 369. Socket I/O • Socket I/O is based on the Java I/O support • in the package java.io • InputStream and OutputStream are abstract classes • common operations defined for all kinds of InputStreams, OutputStreams… 37
  • 370. InputStream Basics // reads some number of bytes and // puts in buffer array b int read(byte[] b); // reads up to len bytes int read(byte[] b, int off, int len); Both methods can throw IOException. Both return –1 on EOF. 38
  • 371. OutputStream Basics // writes b.length bytes void write(byte[] b); // writes len bytes starting // at offset off void write(byte[] b, int off, int len); Both methods can throw IOException. 39
  • 372. ServerSocket Class (TCP Passive Socket) • Constructors: ServerSocket(int port); ServerSocket(int port, int backlog); ServerSocket(int port, int backlog, InetAddress bindAddr); 40
  • 373. ServerSocket Methods Socket accept(); void close(); InetAddress getInetAddress(); int getLocalPort(); throw IOException, SecurityException 41
  • 374. Example: Java server (TCP) import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket doorbellSocket = new ServerSocket(6789); while(true) { Socket connectSocket = doorbellSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectSocket.getInputStream())); Create welcoming socket at port 6789 Wait, on welcoming socket for contact by client Create input stream, attached to socket 42
  • 375. Example: Java server (TCP), cont DataOutputStream outToClient = new DataOutputStream(connectSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + 'n'; outToClient.writeBytes(capitalizedSentence); } } } Read in line from socket Create output stream, attached to socket Write out line to socket End of while loop, loop back and wait for another client connection 43
  • 376. Example: Java client (TCP) import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket connectSocket = new Socket("hostname", 6789); DataOutputStream outToServer = new DataOutputStream(connectSocket.getOutputStream()); Create input stream Create client socket, connect to server Create output stream attached to socket 44
  • 377. Example: Java client (TCP), cont. BufferedReader inFromServer = new BufferedReader(new InputStreamReader(connectSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + 'n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); connectSocket.close(); } } Create input stream attached to socket Send line to server Read line from server 45
  • 378. Client/server socket interaction: TCP (Java) wait for incoming connection request connectSocket = welcomeSocket.accept() create socket, port=x, fincoming request: or doorbellSocket = ServerSocket() create socket, connect to hostid, port=x connectSocket = Socket() close connectSocket read reply from connectSocket close connectSocket Server (running on hostid) Client send request using connectSocket read request from connectSocket write reply to connectSocket TCP connection setup 46
  • 379. TCP Server vs Client • Server waits to accept connection on well known port • Client initiates contact with the server • Accept call returns a new socket for this client connection, freeing welcoming socket for other incoming connections • Read and write only (addresses implied by the connection) 47
  • 380. Sample Echo Server TCPEchoServer.java Simple TCP Echo server. Based on code from: TCP/IP Sockets in Java 48
  • 381. UDP Sockets • DatagramSocket class • DatagramPacket class needed to specify the payload • incoming or outgoing 49
  • 382. Java UDP Sockets • In Package java.net • java.net.DatagramSocket • A socket for sending and receiving datagram packets. • Constructor and Methods • DatagramSocket(int port): Constructs a datagram socket and binds it to the specified port on the local host machine. • void receive( DatagramPacket p) • void send( DatagramPacket p) • void close() 50
  • 383. DatagramSocket Constructors DatagramSocket(); DatagramSocket(int port); DatagramSocket(int port, InetAddress a); All can throw SocketException or SecurityException 51
  • 384. Datagram Methods void connect(InetAddress, int port); void close(); void receive(DatagramPacket p); void send(DatagramPacket p); Lots more! 52
  • 385. Datagram Packet • Contain the payload • (a byte array) • Can also be used to specify the destination address • when not using connected mode UDP 53
  • 386. DatagramPacket Constructors For receiving: DatagramPacket( byte[] buf, int len); For sending: DatagramPacket( byte[] buf, int len InetAddress a, int port); 54
  • 387. DatagramPacket methods byte[] getData(); void setData(byte[] buf); void setAddress(InetAddress a); void setPort(int port); InetAddress getAddress(); int getPort(); 55
  • 388. Example: Java server (UDP) import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); Create datagram socket at port 9876 Create space for received datagram Receive datagram 56
  • 389. Example: Java server (UDP), cont String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } } Get IP addr port #, of sender Write out datagram to socket End of while loop, loop back and wait for another datagram Create datagram to send to client 57
  • 390. Example: Java client (UDP) import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); Create input stream Create client socket, DatagramSocket, but no port Translate hostname to IP address using DNS 58
  • 391. Example: Java client (UDP), cont. DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } } Create datagram with data-to-send, length, IP addr, port Send datagram to server Read datagram from server 59
  • 392. Client/server socket interaction: UDP close clientSocket Server (running on hostid) read reply from clientSocket create socket, clientSocket = DatagramSocket() Client Create, address (hostid, port=x, send datagram request using clientSocket create socket, port=x, for incoming request: serverSocket = DatagramSocket() read request from serverSocket write reply to serverSocket specifying client host address, port umber 60
  • 393. UDP Server vs Client • Server has a well-known port number • Client initiates contact with the server • Less difference between server and client code than in TCP • Both client and server bind to a UDP socket, server specifies port while client does not • Not accept for server and connect for client • Client send to the well-known server port; server extracts the client’s address from the datagram it receives 61
  • 394. Sample UDP code UDPEchoServer.java Simple UDP Echo server. Test using nc as the client (netcat): > nc –u hostname port 62
  • 395. Socket Programming in the Real World • Download some open source implementations of network applications • Web browsers (Firefox) • DNS Servers and resolvers (BIND) • Email clients/servers (sendmail, qmail, pine) • telnet • Can you find the socket code? The protocol processing? What percentage of the code is it? What does the rest of the code do? 63
  • 397. Resources • Introduction to Computer Networks Slides By Amirhossein Sadr • Dr. Mojtaba Vahidi Asl Slides • Dr. Sadegh Aliakbari Slides • Other Universites Slides 65