Thread in Java.

1. What is Thread?
 1.a. Thread is a Light-weight ,its allow multiple activities within a single process.
 1.b. All treads of a process share the common memory space, The process of execution multiple threads simultaneously is known as multi-threading.

2. Non-Thread Program vs Thread Program

2.a. Example Non-Thread Program.

public class WithoutThread {

 // main method
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String str = “banana”;
  String str2 = “papaya”;
  
  ProcessClass proStr = new ProcessClass();
  proStr.IterateRandomValue(str);
  proStr.IterateRandomValue(str2);
}
}
class ProcessClass{
 public void IterateRandomValue(String itr){
  for (int i = 0; i < 5; i++) {
    System.out.println(i + ” ” + itr );
  }
   }
 }

OUTPUT in Console:
0 banana
1 banana
2 banana
3 banana
4 banana
0 papaya
1 papaya
2 papaya
3 papaya
4 papaya

Descriptions on without Thread class : without added thread class, it will execute the process one by one ( check the output program above, program banana will run first until its finish, and then, papaya program will be run ) – sequentially. the Process will taking longer time to finish the processing compare than extends Thread class or implements Runnable class.

2.b. Thread Program.

  • the Functions of Java Threads is to allow multiple activities within a single process.
  • To implement The Threads function we need to extends Thread Class or Implements Interface Runnable Class.

Example Program extend Thread class.

public class ThreadExample {
 //Main Thread
    public static void main(String[] args)
    {
     // TODO Auto-generated method stub
     String str = “banana”;
     String str2 = “papaya”;
     
     // First Thread
     ExtendThread firstThread = new ExtendThread(str);
     firstThread.start();
     
        //Second Tread
     ExtendThread secondThread = new ExtendThread(str2);
     secondThread.start();
    }

}

class ExtendThread extends Thread
{
 private String strNew;

 ExtendThread(String str) {
  strNew = new String(str);
 }

 @Override
 public void run() {
  for (int i = 0; i < 5; i++) {
   System.out.println(i + ” ” + strNew);
  }

 }
}

Output:
Starting Banana
Creating ..Papaya
Starting Papaya
Running..Banana
Thread : Banana,4
Running..Papaya
Thread : Papaya,4
Thread : Banana,3
Thread : Papaya,3
Thread : Banana,2
Thread : Papaya,2
Thread : Banana,1
Thread : Papaya,1

  • If we see the results for (papaya,1) and (Banana, 1) its actually run simultaneously
  • How to Use ServletOutputStream – for Servlet Download zip file into response Client?

    Good Day!

    How to Use ServletOutputStream – for Servlet Download zip file into response Client?

    Description / Answer:

    • from the tomcat.apache.org lib descriptions – Provides an output stream for sending binary data to the client.
    • is an abstract class that the servlet container implements. Subclasses of this class must implement the java.io.OutputStream.write(int) method.
    • method that are regularly used are : .write() – writing what the client request and paste to servlet response client.
    • Its use to attached the Output Stream to download on browser.

    example program – Servlet Class :

    ServletOutputStream servletOutputStream = null;
    FileInputStream fileInputStream = null;
    filename = “documentInput.Zip“;

    try {
    File file = new File(“C://documents/temp/tempfile.zip“);
    fileInputStream = new FileInputStream(file);
    servletOutputStream = response.getOutputStream();

    // download using browser client – change to byte
    response.setContentType(“application/zip“);
    response.setContentLength((int)f.length());
    response.addHeader(“Content-Disposition“,”attachment;filename=\“” + filename + “\””);
    byte[] arBytes = new byte[32768];

    int count;
    while ((count = fileInputStream.read(arBytes)) > 0)
    {
    servletOutputStream.write(arBytes, 0, count);
    }

    }catch (IException e) {
    // TODO: handle exception
    } finally{
    servletOutputStream.flush();
    fileInputStream.close();
    }

    Creating example jax-ws Service Provider + ejb 3.1 + mysql + webSphere v7.0 + RAD v 8.0.2- part 2

    Creating example jax-ws Service Provider + ejb 3.1 + mysql + webSphere v7.0 – part 2

    1.) Create EAR file, at your Rational Application Development – RAD, right click  select New > Enterprise Application Project > Project name : “studEAR” > Finish

    1ws2.png

    2.) Create new Project EJB. New > Other > Java EE > Utility Project > Next > Project Name “studentEJB” >  Finish

    14.png

    3.)

     

     

     

    Create Simple Web Service JAX-WS – Client Part – RAD IBM – Websphere 7.0 + java 6

    Create Simple Web Service JAX-WS – Client Part – RAD IBM – Websphere 7.0 + java 6

    1.) After you done doing my example on JAX-WS Server Part 1, you can create new Dynamic web project “jaxwsClientFirst” – for client part.

    1.1.) Create package, com.fndong.client, then right click New > others > Web Service > Web Service Client

    9ws1.png

    1.2.) Create package, com.fndong.client, then right click New > others > Web Service > Web Service Client.

    10ws1.png

    Click on Browse Button of Service Definition and select the WSDL file of jaxwsServerFirst , Press Ok. Then set the target Location “com.fndong.client” > Next > Finish.

    1.3.) Then it will generated java class automatically :

    11ws1.png

    1.4.) Open class SalaryImplService.java , inside the codes, change the URL to  :

    url = com.fndong.client.SalaryImplService.class.getResource(“/WEB-INF/wsdl/SalaryImplService.wsdl”);

    to

    url = com.fndong.client.SalaryImplService.class.getResource(“http://localhost:9080/jaxwsServerFirst/SalaryImplService/SalaryImplService.wsdl&#8221;);

    1.5.) This client jax-ws used WebSphere thin client jar for WebService Client. Right Click on jaxwsClientFirst  >BuildPath > Configure Build Path,Under Libraries Tab ->

    12ws1.png

    Click on WebSphere Application Server v7.0. Click On Remove, and Press OK.

    1.6.) Then add thin client jar , Right Click again on jaxwsClientFirst  >BuildPath > Configure Build Path,Under Libraries Tab ->  Add External JARs > add three jars below.

    • com.ibm.jaxws.thinclient_7.0.0.jar
    • com.ibm.ws.admin.client_7.0.0.jar
    • com.ibm.ws.webservices.thinclient_7.0.0.jar

    – click OK Button.

    1.7.) Create a client program that invokes the server jaxwsServerFirst, by Creating new Client java class in the package com.fndong.client – “CalculateClient.java“.

     package com.fndong.client;
    
    /**
     * @author fndong
     *
     */
    public class CalculateClient {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
             SalaryImplService service = new  SalaryImplService();
             SalaryService salaryService = service.getSalaryImplPort();
             double var1 = 2000;
             double var2 = 5000;
             double mysalary = salaryService.calculateSalaryAllowance(var1, var2);
             System.out.println("my salary : " + mysalary);       
        }
    
    }

     

    Create Simple Web Service JAX-WS – Server Part – RAD IBM – Websphere 7.0 + java 6

    1). Create Simple Web Service JAX-WS – RAD IBM – Websphere 7.0 + java 6

    1.1) Create your ear File first – Select New > Enterprise Application Project – “jaxwsServerEar” – Server Web Service  Part  1

    1.2.) Create New Java Project – Select New > Dynamic Web Project– “jaxwsServerFirst

    1ws1.png

    1.3) create your Interface class with package. Create Package – com.fndong.service  / create your Class web Service “SalaryService” ( The interface will list calculate the salary and allowance)

    package com.fndong.service;
    
    import javax.jws.WebMethod;
    import javax.jws.WebService;
    
    /**
     * @author fndong
     *
     */
    @WebService
    public interface SalaryService {
         @WebMethod
         public int calculateSalaryAllowance(double salary, double allowance);
    }
    • The @WebService annotation marks the WebServiceFirst class as implementing a web service, which results in a deployable web service being produced.
    • The @WebMethod

    1.4.) Create implementation class to calculate Salary and Allowance – “SalaryImpl

    package com.fndong.Impl;
    
    import com.fndong.service.SalaryService;
    
    /**
     * @author fndong
     *
     */
    @WebService(endpointInterface="com.fndong.service.SalaryService")
    public class SalaryImpl implements SalaryService {
         
        public double calculateSalaryAllowance(double salary, double allowance) {
             return salary + allowance;
    }
    
    
    }
    
    

    1.5.) Create Web Service for the Implementation Class “SalaryImp” by right SalaryImp > Web Services> create WebServices

    2ws1.png

    • Next > check the box – Generate WSDL file into the project.

    3ws1.png

     

     

     

     

     

     

     

     

     

     

     

    Next > Next > Finish

    1.6.) The Class “SalaryImplDelegate.java” will generated automatically and also WSDL files. ( Check inside WebContent Folder)

    4ws1.png

    1.7.) The server started and test the result and also validate the WSDL.

    5ws1.png

    1.7.1.) check the WSDL document in the browser.

    http://localhost:9080/jaxws/SalaryImplService?wsdl

    6ws1.png

    1.8.) Test with WebServices Explorer, just right click wsdl->WebServices->Test with WebServices Explorer

    7ws1.png

    1.9.) It will load the page in your RAD . You test the result of calculation between Salary and Allowance, for arg0 = 3000 and arg1 = 50 , Click Go Button, so the result at the Status – Body:

    8ws1.png

    Selamat Mencuba (malay languange)

    notes for programming – mixed – Q & A – Part 1

    Notes for programming – mixed – Q & A – Part 1

    1.) What is difference between extends and implementations in java (20/09/2016) ?

    answers:

    1.1.a) extends is for extending a class.
    1.1.b) implements is for implementing an interface

    http://www.cs.pomona.edu/~kim/CSC051F12/Lectures/Lecture28/Lecture28_7.html

    Difference Between Implements and Extends

    2.) which is the best practice for checking condition if the Object is null (21/09/2016)?

    – Lets say you want to checking if your object input are null, there are three ways:
    1) Add null first to check the input
    if(null.equals(input))
    CORRECT – The best practice

    2) Add input first then check with null
    if(input.equals(null))

    INCORECT – not the best practice , WHY ? – it will potentially causing a NullPointerException.

    3) check the condition by == this syntax equals
    if(input == null)  

    CORRECT – The best practice

    3.) what is best practice for Java String method (local) variables be initialized to null or “”?

    • its depends on what your programs want to do, there are certain time we need to initialized or directly set to null because we want to check the condition input != null and do something, but if we wanted to prevent the nullpointer its better to set “” – EMPTY string. 

    4.) Missing braces in If statement is not recommendation.

    4.1. First codes without curly braces:

    if(statement)
        do this;
    else
        do this;

    4.2. Second codes with curly braces:

    if(statement){
        do this;
    }else{
        do this;
    }
    • if the First and the second is the best if-else recommendation.
      • answers: when not Omitting braces it will harms readability and can easily cause issues when the code is modified.
      • for the first if statement , the compiler will read for the first do this.
      • Code merges. It’s been known to happen on projects I’ve worked on that single-statement ifs have been broken by automatic merges. The scary thing is the indentation looks right even though the code is wrong, so this type of bug is hard to spot.So I go with braces – on their own lines. It’s easier to spot the levels that way. Yes, it does waste vertical screen real estate and that’s a genuine downside. On balance though, I think it’s worth it.
      • if really don’t want to use curly braces, write just one line only, its really safeful:
        • if (condition) dothis();

    http://stackoverflow.com/questions/2125066/is-it-bad-practice-to-use-an-if-statement-without-brackets

    https://dzone.com/articles/omitting-braces-not-just-a-mat

    http://howtodoinjava.com/for-fun-only/why-try-catch-finally-blocks-require-braces/

    https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html

    5.) Date date = new Date(); date.parse(“String_date_format“) , does no longer supported, Deprecated. .parse() :

    • With Java 8, the preferred date/time classes are no longer in the java.util package and the preferred date/time handling classes are now in the java.time package.
    • The DateTimeFormatter class provides of Pattern methods to provide an instance of DateTimeFormatter based on the provided date/time pattern String. One of the format methods can then be called on that instance of DateTimeFormatter to get the date and/or time information formatted as a String matching the provided pattern.

    5.1.) DEPRECATED
    java.util.Date date = new java.util.Date();
    java.text.SimpleDateFormat dateformat = new java.text.SimpleDateFormat(“YYYY-dd-MM”);
    date.parse(date.parse()); // The method parse(String) from the type Date is deprecated

    5.2) NEW Date Format for Java 8
    – using: java.time.LocaleDate();

     LocalDate date = LocalDate.now();
      String text = date.format(formatter);
      LocalDate parsedDate = LocalDate.parse(text, formatter);

    5.3.) How to passing value Date with Format Pattern – “YYYY-dd-MM” to save to database? (29/09/2016 – 11.00 am – HTV Building)

    LocalDate localDate = LocalDate.now(); // YYYY-mm-dd - java.time 8
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // java.time 8
    SimpleDateFormat smpdatef = new SimpleDateFormat("yyyy-MM-dd"); // java.text
    String strldate = localDate.format(formatter);
    Date date  = smpdatef.parse(strldate);
    // using sql date to change to Date 
        java.sql.Date datesql = null;
    
    datesql = new java.sql.Date(smpdatef.parse(strldate).getTime());
    
    System.out.println("date sql : " + datesql);
    
    // set to entity with Date value
    Users user = new Users();
    user.setUserDate(datesql);

    Output: date sql : 2016-09-29

    6.) Operator: what is super() method in java? (4/10/2016)

    1.1. Super keyword are to use for accessing Superclass’s Member and reference variable is used to refer parent class Object.
    1.2. the Subclass method overrides one of its superclass’s methods, it can invoke the overridden method through the use for keyword super.

    a. At variable level.
    b. At method level.
    c. At constructor level.