Friday, May 3, 2013

574


User->HomePage: onClickRegister()
HomePage->+RegisterPage: turnToPage()
User->RegisterPage: enterText()
RegisterPage->RegisterPage:disPlayInfoTag()
User->RegisterPage: onClickSubmit()
RegisterPage->ConfirmationDialog: displayDialog()
User->ConfirmationDialog: OnclickContinue()
RegisterPage->AccountTable: addUser()
RegisterPage-->-HomePage: turnToPage()

RegisterPage->RegisterPage: MissingFirstNameMsg()
RegisterPage->RegisterPage: MissingLastNameMsg()
RegisterPage->RegisterPage: invalidEmailMsg()
RegisterPage->RegisterPage: EmailTooShortMsg()
RegisterPage->+AccountTable: checkedExistAccount()
AccountTable-->-RegisterPage: checkedExistAccount()
AccountTable->RegisterPage: EmailExistMsg()
User->RegisterPage: onClickRetriveID()
note right of RegisterPage
   pass control to
retrive ID use case
end note
User->RegisterPage: onClickResetPassWord()
note right of RegisterPage
  pass control to
reset password use case
end note
RegisterPage->RegisterPage: IDtooShortMsg()
RegisterPage->RegisterPage: invalidIDMsg()
RegisterPage->RegisterPage: IDexistMsg()
RegisterPage->SuggestionDialog: displaySuggestion()
RegisterPage->RegisterPage: passwordTooShortMsg()
RegisterPage->RegisterPage: PasswordMismatchMsg()
RegisterPage->RegisterPage: PasswordMissingMsg()
User->ConfirmationDialog: onClickChangeEmail()
ConfirmationDialog->RegisterPage: returnToPage()
RegisterPage->UserAgreementPage: popUpWindow()
RegisterPage->PrivatePolicyPage: popUpWindow()




Monday, April 22, 2013

Petrit Net

http://www.informatik.uni-hamburg.de/TGI/PetriNets/introductions/aalst/

http://www.informatik.uni-hamburg.de/TGI/PetriNets/

A Petri net (also known as a place/transition net or P/T net) is one of several mathematical modeling languages for the description of distributed systems. A Petri net is a directed bipartite graph, in which the nodes represent transitions (i.e. events that may occur, signified by bars) and places (i.e. conditions, signified by circles). The directed arcs describe which places are pre- and/or postconditions for which transitions (signified by arrows) occurs. Some sources[1] state that Petri nets were invented in August 1939 by Carl Adam Petri — at the age of 13 — for the purpose of describing chemical processes.

weight of arcs

Monday, April 15, 2013

Business_Process_Modeling_BPMN

Resource Description Framework (RDF)

N3(N-triple)Validator

N3 EXAMPLES

Java Program that can read write N3

reference 

TERMS:

OWL: Web Ontology Languages 


RDF: RESOURCE DESCRIPTION FRAMEWORK 

example of RDF:


The fundamental concepts of RDF are: 
resources
properties
statements 

Tutorial to RDF
http://www.rdfabout.com/quickintro.xpd
Tutorial to N3
http://www.w3.org/2000/10/swap/Primer
http://eulersharp.sourceforge.net/2004/02swap/RDFEngine/inferencing.htm
http://infomesh.net/2002/notation3/


Graphical Representations


http://www.infowebml.ws/rdf-owl/graphical-representations.htm#member

N3 Example:
 RDF triples

A student record in a database has the following fields: 
- name 
- major 
- student identity number 
- GPA 
- Advisor 

Model this database using RDF triples, by defining the classes and properties. Use the N3 notation. Give the triples for one example student record. 


:student rdf:type rdfs:Class.    //rdf:type  //student是 Class
:name rdf:type rdf:Property.  //name 是 Property
:major rdf:type rdf:Property.
:sin rdf:type rdf:Property.
:gpa rdf:type rdf:Property.
:advisor rdf:type rdf:Property.


:name rdfs:domain :student.  //Property - name 属于 student (Class student 拥有Property - name)
:major rdfs:domain :student.
:sin rdfs:domain :student.
:gap rdfs:domain :student.
:advisor rdfs:domain rdf:student.

student1 rdf:type :student.     //student1 是 student (instance)
student1 :name "Joe Smith".
student1 :major "Computer Science".
student1 :sin 12345678.
student1 :gpa 3.5.
student1 :advisor faculty17.


The property which tells you what type something is is rdf:type which can be abbreviated to N3 to just a. So we can define a class of person
:Person a rdfs:Class.



Define the following using OWL statements: 
1. A student has exactly one advisor. 
2. A student is uniquely identified by their SIN. 
3. Define the set of honor students as the set of all students whose GPA is 4.0. This is a very strong notion of honor student, but it greatly simplifies the question for you.


1. :advisor rdf:type owl:functionalProperty.
2. :sin rdf:type owl:inverseFunctionalProperty.
3. :honorStudent owl:equivalentClass
      [ a owl:Restriction ;
owl:onProperty :gpa ;
owl:hasValue .40 ]

rdf:domain v.s. rdf:range
There is an example here: http://www.w3.org/2000/10/swap/Primer


The property which tells you what type something is is rdf:type which can be abbreviated to N3 to just a. So we can define a class of person
:Person a rdfs:Class.
In the same document, we could introduce an actual person
:Pat a :Person.
Classes just tell you about the thing which is in them. An object can be in many classes. There doesn't have to be any hierarchical relationship -- think of Person, AnimateObject, Animal, TallPerson, Friend, and so on. If there is a relationship between two classes you can state it - check out the properties (of classes) in the RDF Schema and OWL vocabularies.
:Woman a rdfs:Class; rdfs:subClassOf :Person .
A property is something which is used to declare a relationship between two things.
:sister a rdf:Property.
Sometimes when a relationship exists between two things, you immediately know something about them, which you can express as a class. When the subject of any property must be in a class, that class is a domain of the property. When the object must be in a class, that class is called the range of a property. A property can have many domains and ranges, but typically one specifies one.
:sister rdfs:domain :Person; 
        rdfs:range :Woman.
Note the class identifiers start with capitals and properties with lower case letters. This is not a rule, but it is a good convention to stick to. Note also that because the domain of rdfs:range and rdfs:domain themselves is rdf:Property, it follows that :sister is a rdf:Property without it being stated explicitly.

rdfs:domain vs rdfs:range
Example 
"When the subject of any property must be in a class, that class is a domain of the property. When the object must be in a class, that class is called the range of a property."
http://workingontologist.org/Examples/Chapter3/shakespeare.n3
a Person linvedIn a Place

bio:livedIn
      a       owl:ObjectProperty ;
      rdfs:domain lit:Person ;//subject
      rdfs:label "lived in"^^xsd:string ;
      rdfs:range lit:Place . //object



Wednesday, April 10, 2013

Spring Note

Spring 


1. Annotation injection is performed before XML injection, thus the latter configuration will override the former for properties wired through both approaches.


Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file. So consider to have following configuration file in case you want to use any annotation in your Spring application.
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>
   <!-- bean definitions go here -->

</beans>
Once <context:annotation-config/> is configured, you can start annotating your code to indicate that Spring should automatically wire values into properties, methods, and constructors. Let us see few important annotations to understand how they work:

Thursday, April 4, 2013

Maven-Spring

OPTION1

1. install m2Eclipse in Eclipse
2. Create maven project
3. create SOURCE FOLDER -> "sre/main/java/resources"
4. add config xml files to resources folder
5. add dependencies to pom.xml

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
</dependencies>
...

Maven will download those dependencies automatically.




OPTION2

In mkyong's example, he established the maven project in linux and then import it into eclipse.
http://www.mkyong.com/spring/quick-start-maven-spring-example/

1. Generate project structure with Maven

In command prompt, issue following Maven command :
mvn archetype:generate -DgroupId=com.mkyong.common -DartifactId=SpringExamples 
 -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Maven will generate all the Java’s standard folders structure for you (besides resources folder, which you need to create it manually)

2. Convert to Eclipse project

Type “mvn eclipse:eclipse” to convert the newly generated Maven style project to Eclipse’s style project.
mvn eclipse:eclipse
Later, import the converted project into Eclipse IDE.
Create a resources folder (not folder)
Create a resources “/src/main/resources” folder, the Spring’s bean xml configuration file will put here later. Maven will treat all files under this “resources” folder as resources files, and copy it to output classes automatically.

3. Add Spring dependency

Add Spring dependency in Maven’s pom.xml file.
File : pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.mkyong.common</groupId>
 <artifactId>SpringExamples</artifactId>
 <packaging>jar</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>SpringExamples</name>
 <url>http://maven.apache.org</url>
 <dependencies>
 
  <!-- Spring framework -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring</artifactId>
   <version>2.5.6</version>
  </dependency>
 
 </dependencies>
</project>
Issue “mvn eclipse:eclipse” again, Maven will download the Spring dependency libraries automatically and put it into your Maven’s local repository. At the same time, Maven will add the downloaded libraries into Eclipse “.classpath” for dependency purpose.


I have try this one but the eclipse complained that ApplicationContext and ClassPathXmlApplicationContext cannot be resolve although the spring framework are in the lib path.

Solution :
Convert the project to maven project in Eclipse. (Download m2eclipse firstly: help->install->m2eclipse)


The reason might be that eclipse didn't know what maven is.


OK, LET'S MOVE ON...


Why use XML to config the project?
loose coupling;






Wednesday, March 20, 2013

How SOAP message looks like


getPatientByDbId Method invocation



Method parameter(s)

TypeValue
long2

Method returned

edu.stevens.cs548.clinic.service.dto.patient.PatientDto : "edu.stevens.cs548.clinic.service.dto.patient.PatientDto@79a7c927"

SOAP Request


<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Header/>
    <S:Body>
        <ns3:getPatientByDbId xmlns:ns2="http://cs548.stevens.edu/clinic/service/dto/patient" xmlns:ns3="http://cs548.stevens.edu/clinic/service/web/soap/patient" xmlns:ns4="http://cs548.stevens.edu/clinic/service/dto/treatment">
            <arg0>2</arg0>
        </ns3:getPatientByDbId>
    </S:Body>
</S:Envelope>

SOAP Response


<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:getPatientByDbIdResponse xmlns:ns2="http://cs548.stevens.edu/clinic/service/web/soap/patient" xmlns:ns3="http://cs548.stevens.edu/clinic/service/dto/patient" xmlns:ns4="http://cs548.stevens.edu/clinic/service/dto/treatment">
            <ns3:PatientDto>
                <id>2</id>
                <patient-id>10001</patient-id>
                <name>Sam</name>
                <dob>1988-03-20Z</dob>
            </ns3:PatientDto>
        </ns2:getPatientByDbIdResponse>
    </S:Body>
</S:Envelope>

Java multi-threading interview questions and answers


Java multi-threading interview questions and answers - continuation



This is the continuation from Java multi-threading questions and answers 

Q. Why synchronization is important?
A. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often causes dirty data and leads to significant errors. The disadvantage of synchronization is that it can cause deadlocks when two threads are waiting on each other to do something. Also synchronized code has the overhead of acquiring lock, which can adversely affect the performance.



Q. What is a ThreadLocal class?
A. ThreadLocal is a handy class for simplifying development of thread-safe concurrent programs by making the object stored in this class not sharable between threads.ThreadLocal class encapsulates non-thread-safe classes to be safely used in a multi-threaded environment and also allows you to create per-thread-singleton.


Q. What is a daemon thread?
A. Daemon threads are sometimes called "service" or “background” threads. These are threads that normally run at a low priority and provide a basic service to a program when activity on a machine is reduced. An example of a daemon thread that is continuously running is the garbage collector thread. The JVM exits whenever all non-daemon threads have completed, which means that all daemon threads are automatically stopped. To make a thread  as a daemon thread in Java

?
1
myThread.setDaemon(true);

The JVM always has a main thread as default. The main thread is always non-daemon. The user threads are created from the main thread, and by default they are non-daemon. If you want to make a user created thread to be daemon (i.e. stops when the main thread stops), use the setDaemon(true) as shown above.
Q. How can threads communicate with each other? How would you implement a producer (one thread) and a consumer (another thread) passing data (via stack)?
A. The wait( ), notify (), and notifyAll( ) methods are used to provide an efficient way for threads to communicate with each other. This communication solves the ‘consumer-producer problem’. This problem occurs when the producer thread is completing work that the other thread (consumer thread) will use.

Example: If you imagine an application in which one thread (the producer) writes data to a file while a second thread (the consumer) reads data from the same file. In this example the concurrent threads share the same resource file. Because these threads share the common resource file they should be synchronized.  Also these two threads should communicate with each other because the consumer thread, which reads the file, should wait until the producer thread, which writes data to the file and notifies the consumer thread that it has completed its writing operation.

Let’s look at a sample code where count is a shared resource. The consumer thread will wait inside the consume( ) method on the producer thread, until the producer thread increments the count inside the produce( ) method and subsequently notifies the consumer thread. Once it has been notified, the consumer thread waiting inside the consume( ) method will give up its waiting state and completes its method by consuming the count (i.e. decrementing the count).





Here is a complete working code example on thread communication.

Note:  A method calls notify( )/notifyAll( ) as the last thing it does (besides return). Since the consume method was void, the notify( ) was the last statement. If it were to return some value, the notify( ) would have been placed just before the return statement.

Q. Why wait, notify, and notifyall methods are defined in the Object class, and not in the Thread class?
A. Every Java Object has a monitor associated with it. The threads using that object can lock or unlock the monitor associated with the object.Wait and notify/notifyAll methods are responsible for acquiring and relinquishing the lock associated with the particular object. Calling wait causes the current thread to wait to acquire the lock of the Object, and calling notify/notifyAll relinquishes the lock and notify the threads waiting for that lock.


Q. What does join( ) method do?
A. t.join( ) allows the current thread to wait indefinitely until thread “t” is finished.  t.join (5000) allows the current thread to wait  for thread “t” to finish but does not wait longer than 5 seconds.

?
1
2
3
4
5
6
7
8
9
try {
  t.join(5000); //current thread waits for thread “t” to complete but does not wait more than 5 sec
  if(t.isAlive()){
     //timeout occurred. Thread “t” has not finished
  }
  else {
     //thread “t” has finished
  
}

For example, say you need to spawn multiple threads to do the work, and continue to the next step only after all of them have completed, you will need to tell the main thread to wait. this is done with thread.join() method.




Here is the RunnableTask. The task here is nothing but sleeping for 10 seconds as if some task is being performed. It also prints the thread name and timestamp as to when this task had started

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.Date;
public class RunnableTask implements Runnable {
 @Override
 public void run() {
  Thread thread = Thread.currentThread();
  System.out.println(thread.getName() + " at " + new Date());
  try {
   Thread.sleep(10000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}


The taskmanager manages the tasks by spawing multiple user threads from the main thread. The main thread is always created by default. The user threads 1-3 are run sequentially, i.e. thread-2 starts only after thread-1 completes, and so on. The user threads 4-6 start and executes concurrently.



?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class TaskManager {
  
  
 public static void main(String[] args) throws InterruptedException {
  RunnableTask task = new RunnableTask();
   
  //threads 1-3 are run sequentially
  Thread thread1 = new Thread(task, "Thread-1");
  Thread thread2 = new Thread(task, "Thread-2");
  Thread thread3 = new Thread(task, "Thread-3");
   
  thread1.start(); //invokes run() on RunnableTask
  thread1.join();  // main thread blocks (for 10 seconds)
  thread2.start(); //invokes run() on RunnableTask
  thread2.join();  // main thread blocks (for 10 seconds)
  thread3.start(); //invokes run() on RunnableTask
  thread3.join();  // main thread blocks (for 10 seconds)
   
  Thread thread4 = new Thread(task, "Thread-4");
  Thread thread5 = new Thread(task, "Thread-5");
  Thread thread6 = new Thread(task, "Thread-6");
  
  thread4.start(); //invokes run() on RunnableTask
  thread5.start(); //invokes run() on RunnableTask
  thread6.start(); //invokes run() on RunnableTask
 }
}


Notice the times of the output. There is a 10 second difference bewteen threads 1-3. But Threads 4-6 started pretty much the same time.

?
1
2
3
4
5
6
Thread-1 at Fri Mar 02 16:59:22 EST 2012
Thread-2 at Fri Mar 02 16:59:32 EST 2012
Thread-3 at Fri Mar 02 16:59:42 EST 2012
Thread-4 at Fri Mar 02 16:59:47 EST 2012
Thread-6 at Fri Mar 02 16:59:47 EST 2012
Thread-5 at Fri Mar 02 16:59:47 EST 2012


Q. If 2 different threads hit 2 different synchronized methods in an object at the same time will they both continue?
A. No. Only one thread can acquire the lock in a synchronized method of an object. Each object has a synchronization lock. No 2 synchronized methods within an object can run at the same time. One synchronized method should wait for the other synchronized method to release the lock.   This is demonstrated here with method level lock. Same concept is applicable for block level locks as well.





Q. Explain threads blocking on I/O?
A. Occasionally threads have to block on conditions other than object locks. I/O is the best example of this. Threads block on I/O (i.e. enters the waiting state) so that other threads may execute while the I/O operation is performed. When threads are blocked (say due to time consuming reads or writes) on an I/O call inside an object’s synchronized method and also if the other methods of the object are also synchronized then the object is essentially frozen while the thread is blocked.

Be sure to not synchronize code that makes blocking calls, or make sure that a non-synchronized method exists on an object with synchronized blocking code. Although this technique requires some care to ensure that the resulting code is still thread safe, it allows objects to be responsive to other threads when a thread holding its locks is blocked.



Q. If you have a circular reference of objects, but you no longer reference it from an execution thread, will this object be a potential candidate for garbage collection?
A. Yes. Refer diagram below.


Q. Which of the following is true?

a) wait( ), notify( ) ,notifyall( ) are defined as final & can be called only from within a synchronized method
b) Among wait( ), notify( ), notifyall( ) the wait() method only throws IOException
c) wait( ),notify( ),notifyall( ) & sleep () are methods of object class

A. a and b. The c is wrong because the sleep method is a member of the Thread class.The other methods are members of the Object class.

Q. What are some of the threads related problems and what causes those problems?
A. DeadLock, LiveLock, and Starvation.

Deadlock occurs when two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on the same resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other resource to release the lock, unless one of the user processes is terminated. The thread deadlock can occur in conditions such as:

  •  two threads calling Thread.join() on each other.
  •  two threads use nested synchronized blocks to lock two objects and blocks lock the same objects in different order.

Starvation and livelock are much less common a problem than deadlock, and it occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available.

The thread livelock can occur in conditions such as:

  • all the threads in a program are stuck in infinite loops.
  • all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify( ) or Object.notifyAll() on the relevant objects.  Because all the threads are blocked, neither call can be made.

Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. The thread starvation can occur in conditions such as:

  • one thread cannot access the CPU because one or more other threads are monopolizing the CPU.
  • setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.  

Q. What happens if you call the run( ) method directly instead of via the start method?
A. Calling run( ) method directly just executes the code synchronously (in the same thread), just like a normal method call. By calling the start( ) method, it starts the execution of the new thread and calls the run( ) method. The start( ) method returns immediately and the new thread normally continues until the run( ) method returns. So, don't make the mistake of calling the run( ) method directly.

Note:  These Java interview questions and answers are extracted from my book "Java/J2EE Job Interview Companion".

If you liked the above Java multi-threading questions and answers, you will like the following link, which has a little more advanced coding questions on multi-threading.