Archive for the ‘Java’ Category.

java.util.Comparable Interface

java.util.Comparable interface i aşağıdaki gibidir.

 

1
2
3
public interface Comparable<T> {
    public int compareTo(T o);
}

 

Karşılaştırılan objelere göre input objesi büyükse negatif integer, objeler eşit ise sıfır, input objesi küçükse pozitif integer dönülür.

Eğer elemanları Comparable interface ini implement etmeyen bir listeyi, Collections.sort(list) ile sıralamaya çalışırsanız ClassCastException i atılır.

Örnek:

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
/**
 *
 * @author ugurd
 */

public class Node implements Comparable<Node> {
    public String name;
    public int    value;

    public Node(int value, String name) {
        this.value = value;
        this.name  = name;
    }

    public int compareTo(Node o) {
        if (this.value < o.value) {
            return -1;
        } else if (this.value == o.value) {
            return 0;
        } else {
            return 1;
        }
    }

    public static void main(String[] args) {
        Node n1 = new Node(1, "a");
        Node n2 = new Node(2, "b");
        Node n3 = new Node(1, "c");

        System.out.println(n1.compareTo(n3));
        System.out.println(n1.compareTo(n2));
        System.out.println(n2.compareTo(n3));
    }
}

 

Output:

run:
0
-1
1
BUILD SUCCESSFUL (total time: 0 seconds)

kaynak

java.util.Comparator Interface

Comparator interface i adından da anlaşılacağı gibi primitive olmayan class objelerinin karşılaştıılmasını sağlar. Javadoc bu adresten ulaşabilirsiniz. Objenin karşılaştırılabilmesi için interface içindeki compare() fonksiyonun tanımlanması gerekmektedir.

 

Örnek olarak class tanımımız aşağıdaki gibi olsun.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
 *
 * @author ugur
 */

public class Node {

    public int value;
    public String name;

    public Node(int value, String name) {
        this.value = value;
        this.name = name;
    }
}

 

Comparator class ını aşağıdaki gibi tanımlıyoruz.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.Comparator;

/**
 *
 * @author ugur
 */

public class CompareNode implements Comparator<Node> {

    public int compare(Node o1, Node o2) {
        if (o1.value < o2.value )
            return -1;
        else if (o1.value > o2.value)
            return 1;
        else
            return 0;
    }
}

 

 

Kullanımı ise aşağıdaki gibidir.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.PriorityQueue;

/**
 *
 * @author ugur
 */

public class Test {

    public static void main(String [] args) {

        PriorityQueue<Node> queue = new PriorityQueue<Node>(100, new CompareNode());
        queue.add(new Node(5, "a"));
        queue.add(new Node(2, "b"));
        queue.add(new Node(3, "c"));

        while(!queue.isEmpty()) {
            System.out.println(queue.poll().name);
        }
    }
}

 

 

Output:

 

run:
b
c
a

Factory Method Pattern

Factory method pattern factory objelerini implement eden desing pattern lardır. Elimizde class olmadan o class a ait objelerin oluşturulmasını sağlar.

 

UML :

 

factory

 

 

Örnek :

 

Java

 

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
abstract class Pizza {
    public abstract int getPrice(); // count the cents
}
 
class HamAndMushroomPizza extends Pizza {
    public int getPrice() {
        return 850;
    }
}
 
class DeluxePizza extends Pizza {
    public int getPrice() {
        return 1050;
    }
}
 
class HawaiianPizza extends Pizza {
    public int getPrice() {
        return 1150;
    }
}
 
class PizzaFactory {
    public enum PizzaType {
        HamMushroom,
        Deluxe,
        Hawaiian
    }
 
    public static Pizza createPizza(PizzaType pizzaType) {
        switch (pizzaType) {
            case HamMushroom:
                return new HamAndMushroomPizza();
            case Deluxe:
                return new DeluxePizza();
            case Hawaiian:
                return new HawaiianPizza();
        }
        throw new IllegalArgumentException("The pizza type " + pizzaType + " is not recognized.");
    }
}
 
class PizzaLover {
    /*
     * Create all available pizzas and print their prices
     */

    public static void main (String args[]) {
        for (PizzaFactory.PizzaType pizzaType : PizzaFactory.PizzaType.values()) {
            System.out.println("Price of " + pizzaType + " is " + PizzaFactory.createPizza(pizzaType).getPrice());
        }
    }
}

Output:
Price of HamMushroom is 850
Price of Deluxe is 1050
Price of Hawaiian is 1150

 

 

Php

 

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
 
abstract class Pizza
{
    protected $_price;
    public function getPrice()
    {
        return $this->_price;
    }
}
 
class HamAndMushroomPizza extends Pizza
{
    protected $_price = 8.5;
}
 
class DeluxePizza extends Pizza
{
    protected $_price = 10.5;
}
 
class HawaiianPizza extends Pizza
{
    protected $_price = 11.5;
}
 
class PizzaFactory
{
    public static function createPizza($type)
    {
        $baseClass = 'Pizza';
        $targetClass = ucfirst($type).$baseClass;
 
        if (class_exists($targetClass) && is_subclass_of($targetClass, $baseClass))
            return new $targetClass;
        else
            throw new Exception("The pizza type '$type' is not recognized.");
    }
}
 
$pizzas = array('HamAndMushroom','Deluxe','Hawaiian');
foreach($pizzas as $p) {
    printf(
        "Price of %s is %01.2f".PHP_EOL ,
        $p ,
        PizzaFactory::createPizza($p)->getPrice()
    );
}
 
 
// Output:
// Price of HamAndMushroom is 8.50
// Price of Deluxe is 10.50
// Price of Hawaiian is 11.50
 
?>

 

 

Kaynak: wikipedia

Strategy Pattern

Kullanılan algoritma runtime de sürekli değişiyorsa strategy pattern kullanılması uygun olur. Algoritmalar bir interface ile encapsulate edilerek runtime da değiştirilebilir hale getirilir. Algoritmaları kullanan objenin bu değişiklerden haberi olmaz. Ayrıca başka bir algoritma interface i implement ederek kolayca sisteme eklebilir.

 

 

UML : 

 

 

Capture

 

 

 

Java Örneği:

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//StrategyExample test application
 
class StrategyExample {
 
    public static void main(String[] args) {
 
        Context context;
 
        // Three contexts following different strategies
        context = new Context(new ConcreteStrategyAdd());
        int resultA = context.executeStrategy(3,4);
 
        context = new Context(new ConcreteStrategySubtract());
        int resultB = context.executeStrategy(3,4);
 
        context = new Context(new ConcreteStrategyMultiply());
        int resultC = context.executeStrategy(3,4);
 
    }
 
}
 
// The classes that implement a concrete strategy should implement this
 
// The context class uses this to call the concrete strategy
interface Strategy {
 
    int execute(int a, int b);
 
}
 
// Implements the algorithm using the strategy interface
class ConcreteStrategyAdd implements Strategy {
 
    public int execute(int a, int b) {
        System.out.println("Called ConcreteStrategyAdd's execute()");
        return a + b;  // Do an addition with a and b
    }
 
}
 
class ConcreteStrategySubtract implements Strategy {
 
    public int execute(int a, int b) {
        System.out.println("Called ConcreteStrategySubtract's execute()");
        return a - b;  // Do a subtraction with a and b
    }
 
}
 
class ConcreteStrategyMultiply implements Strategy {
 
    public int execute(int a, int b) {
        System.out.println("Called ConcreteStrategyMultiply's execute()");
        return a * b;   // Do a multiplication with a and b
    }
 
}
 
// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {
 
    private Strategy strategy;
 
    // Constructor
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }
 
    public int executeStrategy(int a, int b) {
        return strategy.execute(a, b);
    }
 
}

 

 

 

 

Php Örneği:

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
class StrategyExample {
    public function __construct() {
        $context = new Context(new ConcreteStrategyA());
        $context->execute();
 
        $context = new Context(new ConcreteStrategyB());
        $context->execute();
 
        $context = new Context(new ConcreteStrategyC());
        $context->execute();
    }
}
 
interface IStrategy {
    public function execute();
}
 
class ConcreteStrategyA implements IStrategy {
    public function execute() {
        echo "Called ConcreteStrategyA execute method\n";
    }
}
 
class ConcreteStrategyB implements IStrategy {
    public function execute() {
        echo "Called ConcreteStrategyB execute method\n";
    }
}
 
class ConcreteStrategyC implements IStrategy {
    public function execute() {
        echo "Called ConcreteStrategyC execute method\n";
    }
}
 
class Context {
    private $strategy;
 
    public function __construct(IStrategy $strategy) {
        $this->strategy = $strategy;
    }
 
    public function execute() {
        $this->strategy->execute();
    }
}
 
new StrategyExample();
?>

 

 

Kaynak: wikipedia

Observer Pattern

Observer ları durum değiştiği zaman otomatik olarak uyarır.

 

Class Diagram:

 

800px-Observer.svg

 

 

Java Örnek:

 

Klavyeden girilen her satırı ayrı ayrı event olarak alır. java.util.Observer ve java.util.Observable classları kullanılmıştır.

 

 

 

 

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
/* File Name : EventSource.java */
 
package obs;
 
import java.util.Observable;          //Observable is here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class EventSource extends Observable implements Runnable {
    public void run() {
        try {
            final InputStreamReader isr = new InputStreamReader( System.in );
            final BufferedReader br = new BufferedReader( isr );
            while( true ) {
                String response = br.readLine();
                setChanged();
                notifyObservers( response );
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* File Name: ResponseHandler.java */
 
package obs;
 
import java.util.Observable;
import java.util.Observer;  /* this is Event Handler */
 
public class ResponseHandler implements Observer {
    private String resp;
    public void update (Observable obj, Object arg) {
        if (arg instanceof String) {
            resp = (String) arg;
            System.out.println("\nReceived Response: "+ resp );
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* Filename : MyApp.java */
/* This is the main program */
 
package obs;
 
public class MyApp {
    public static void main(String args[]) {
        System.out.println("Enter Text >");
 
        // create an event source - reads from stdin
        final EventSource evSrc = new EventSource();
 
        // create an observer
        final ResponseHandler respHandler = new ResponseHandler();
 
        // subscribe the observer to the event source
        evSrc.addObserver( respHandler );
 
        // starts the event thread
        Thread thread = new Thread(evSrc);
        thread.start();
    }
}

Kaynak: wikipedia

Facade Pattern

Object oriented programlamada kullanılan design pattern lardan biridir. Class library gibi büyük kodlar için basit arayüzler sunulmasını sağlar. Kütüphanenin kolay kullanılmasını ve anlaşılmasını sağlar. Kütüphaneyi kullanan kodların bağımlılılarını azaltır. Kod yazanlar için esneklik sağlar.

 

 

Yapısı:

 

FacadeDesignPattern

 

Örnek:

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
37
38
39
40
41
42
43
44
45
46
47
48
49
/* Complex parts */
 
class CPU {
  public void freeze() { ... }
  public void jump(long position) { ... }
  public void execute() { ... }
}
 
class Memory {
  public void load(long position, byte[] data) {
    ...
  }
}
 
class HardDrive {
  public byte[] read(long lba, int size) {
    ...
  }
}
 
/* Facade */
 
class Computer {
  private CPU cpu=null;
  private Memory memory=null;
  private HardDrive hardDrive=null;
 
  public Computer() {
    this.cpu=new CPU();
    this.memory=new Memory();
    this.hardDrive=new HardDrive();
  }
 
  public void startComputer() {
    cpu.freeze();
    memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
    cpu.jump(BOOT_ADDRESS);
    cpu.execute();
  }
}
 
/* Client */
 
class You {
  public static void main(String[] args) {
    Computer facade = new Computer();
    facade.startComputer();
  }
}

State Pattern

Bir objenin durumunu belirtmek için kullanılır. Objenin durumu runtime de sürekli değişiyorsa kullanılması uygun olur.

 

 

Örnek Java Implementasyonu:

 

 

State interface i ve iki implemantasyonu.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
interface State {
  public void writeName(StateContext stateContext, String name);
}
 
class StateA implements State {
  public void writeName(StateContext stateContext, String name) {
    System.out.println(name.toLowerCase());
    stateContext.setState(new StateB());
  }
}
 
class StateB implements State {
  private int count=0;
  public void writeName(StateContext stateContext, String name){
    System.out.println(name.toUpperCase());
    // change state after StateB's writeName() gets invoked twice
    if(++count>1) {
      stateContext.setState(new StateA());
    }
  }
}

 

StateContext class i state objelerini tutar.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class StateContext {
  private State myState;
  public StateContext() {
    setState(new StateA());
  }
 
        // normally only called by classes implementing the State interface
  public void setState(State newState) {
    this.myState = newState;
  }
 
  public void writeName(String name) {
    this.myState.writeName(this, name);
  }
}
 

Kullanımı

 

1
2
3
4
5
6
7
8
9
10
11
public class TestClientState {
  public static void main(String[] args) {
    StateContext sc = new StateContext();
    sc.writeName("Monday");
    sc.writeName("Tuesday");
    sc.writeName("Wednesday");
    sc.writeName("Thursday");
    sc.writeName("Saturday");
    sc.writeName("Sunday");
  }
}

 

Output

 
monday
TUESDAY
WEDNESDAY
thursday
SATURDAY
SUNDAY

Java Listenin Elemanlarını Sıralamak

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
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 *
 * @author ugur
 */

public class SortListExample {

    public static void main(String args[]) {

        Integer[] intArray = new Integer[] {1,4,2,10,9,8,20,15,3,3,4};

        List<Integer> list = Arrays.asList(intArray);
       
        Collections.sort(list);

        for(Integer i : list) {
            System.out.print(i + " ");
        }
        System.out.println(" ");

        // reverse order
        Collections.sort(list,Collections.reverseOrder());

        for(Integer i : list) {
            System.out.print(i + " ");
        }
        System.out.println(" ");
    }
}

Output:
run:
1 2 3 3 4 4 8 9 10 15 20
20 15 10 9 8 4 4 3 3 2 1
BUILD SUCCESSFUL (total time: 0 seconds)

Pager Tag Kütüphanesi

Pager Tag kütüphanesi büyük verilerin jsp sayfası içinde sıralanması için kullanılan bir kütüphanedir. Google, Altavista, Yahoo gibi sitelerin indeks stillerini içerir. Dinamik sayfalar için çok kullanışlıdır.

 

Anasayfa

Demo

Download

 

Kurulumu

    1. WEB-INF/web.xml dosyasına aşağıdaki satırları ekleyin.
    <taglib>
      <taglib-uri>
    
    http://jsptags.com/tags/navigation/pager
    
      </taglib-uri>
      <taglib-location>
        /WEB-INF/jsp/pager-taglib.tld
      </taglib-location>
    </taglib>
               
              2. pager-taglib.tld dosyasını /WEB-INF/jsp altına kopyalayın.
                 
                3. pager-taglib.jar dosyasını /WEB-INF/lib altına kopyalayın.
                 

                Örnek Kullanımı

                 

                AltaVista Stili

                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
                <%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %>

                <pg:pager url="http://www.altavista.com/cgi-bin/query" maxIndexPages="20"
                             export="currentPageNumber=pageNumber">
                  <pg:param name="pg"/>
                  <pg:param name="q"/>

                <% for() { %>
                    <pg:item>
                      <%= data %>
                    </pg:item>

                <% } %>


                  <pg:index>
                    <font face=Helvetica size=-1>Result Pages:
                    <pg:prev>&nbsp;<a href="<%= pageUrl %>">[&lt;&lt; Prev]</a></pg:prev>
                    <pg:pages><%
                      if (pageNumber.intValue() < 10) {
                        %>&nbsp;<%
                      }
                      if (pageNumber == currentPageNumber) {
                        %><b><%= pageNumber %></b><%
                      } else {
                        %><a href="<%= pageUrl %>"><%= pageNumber %></a><%
                      }
                    %>
                    </pg:pages>
                    <pg:next>&nbsp;<a href="<%= pageUrl %>">[Next &gt;&gt;]</a></pg:next>
                    <br></font>
                  </pg:index>
                </pg:pager>

              Basit bir RESTful Webservice Client Servlet i

              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
              37
              38
              import java.io.IOException;
              import java.io.PrintWriter;
              import javax.servlet.ServletException;
              import javax.servlet.http.HttpServlet;
              import javax.servlet.http.HttpServletRequest;
              import javax.servlet.http.HttpServletResponse;
              import org.apache.commons.httpclient.HttpClient;
              import org.apache.commons.httpclient.HttpStatus;
              import org.apache.commons.httpclient.methods.GetMethod;

              /**
               *
               * @author ugur
               */

              public class SimpleClient extends HttpServlet {

                  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                      PrintWriter out = response.getWriter();
                      GetMethod getMethod = null;
                      try {
                          getMethod = new GetMethod("http://ws.audioscrobbler.com/2.0/?method=artist.search&artist=metallica&api_key=APIKEY");
                          HttpClient httpClient = new HttpClient();
                          int statusCode = httpClient.executeMethod(getMethod);
                          if (statusCode == HttpStatus.SC_OK) {
                              out.print(new String(getMethod.getResponseBody()));
                          } else {
                              out.print("HTTP error with code: " + statusCode);
                          }
                      } catch (Exception e) {
                          // Send any errors to the view
                          out.print(e.getMessage());
                      } finally {
                          if (getMethod != null) {
                              getMethod.releaseConnection();
                          }
                      }
                  }
              }

              Kullanılan kütüphaneler:

              Common Apache Logging
              Common Apache Codec
              Common Apache httpclient