This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mycompany.client; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class CustomerDataService { | |
public List<Customer> customerList=new ArrayList<>(); | |
Customer e=new Customer(); | |
public CustomerDataService(){ | |
e.setAddress("Hatay/Antakya"); | |
e.setId("0"); | |
e.setName("Gokhan"); | |
e.setPhoneNumber("15134235322452"); | |
customerList.add(e); | |
} | |
private static CustomerDataService ourInstance=new | |
CustomerDataService(); | |
public static CustomerDataService getInstance(){ | |
return ourInstance; | |
} | |
public String addCustomer(Customer customer){ | |
String newId=Integer.toString(customerList.size()+1); | |
customer.setId(newId); | |
customerList.add(customer); | |
return newId; | |
} | |
public List<Customer> getCustomerList(){ | |
return customerList; | |
} | |
public Customer getCustomerById(String id) { | |
for (Customer customer : customerList) { | |
if (customer.getId().equals(id)) { | |
return customer; | |
} | |
} | |
return null; | |
} | |
} |
Sınıfımızı incelemeden önce Customer.java adlı sınıfımızın olduğunu ve bu sınıfımızda name,address ve phonenumber adındaki değişkenlerimizin setter ve getter metodlarının bulunduğunu unutmayalım. Bu classımızda verilerimiz list yardımı ile işlenmiş. addCustomer metodumuzda id ile birlikte parametre olarak alınan customer nesnesi customerList'e depolanıyor.newId ise bir nevi veritabanındaki AutoIncrement gibi çalışıyor. getCustomerList fonksiyonumuz bize o listede bulunan tüm değerleri list olarak döndürüyor.Aynı şekilde getCustomerById fonksiyonumuz da parametre olarak alınan id değerini liste içinde arıyor.Bu değerde bir veri var ise geri döndürüyor yok ise null değer döndürüyor.Bu fonksiyonun customer tipinde değer döndürdüğüne dikkat edelim. Consturctor'ın içindede
list'emize veri ekledik.Bunu tarayıcımız üzerinde GET isteği ile verinin nasıl geldiğini görmek için yaptık
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mycompany.api; | |
import javax.ws.rs.*; | |
import javax.ws.rs.core.*; | |
import java.util.*; | |
import com.mycompany.client.*; | |
@Path("customers") | |
public class CustomerWebService { | |
CustomerDataService dt=CustomerDataService.getInstance(); | |
@GET | |
@Produces(MediaType.APPLICATION_JSON) | |
public List<Customer> getCustomers(){ | |
return dt.getCustomerList(); | |
} | |
@POST | |
@Consumes(MediaType.APPLICATION_JSON) | |
@Produces(MediaType.TEXT_PLAIN) | |
public String createCustomer(Customer newCostumer){ | |
return dt.addCustomer(newCostumer); | |
} | |
@GET | |
@Path("{id}") | |
@Produces(MediaType.APPLICATION_JSON) | |
public Customer getCustomer(@PathParam("id") String id) { | |
return dt.getCustomerById(id); | |
} | |
} |
Şimdide web servis sınıfımıza bakalım.Bir önceki yazımızda @Consumes ve @Produces ek açıklamalarından bahsetmiştik.Burada @GET requestin'e karşılık response döndürebilecek iki adet fonksiyon var. GET/api/customers ve GET/api/customers/0 istekler bu formatta olmalı. Bu fonksiyonların verileri JSON formatında üreteceğini görüyoruz. Diğer bir fonksiyonumuzda gelen bir post isteğini dataservisimizi kullanarak gerçekleştiriyor ve gördüğünüz üzere addCustomer metodumuz bize yeni eklenen müşterinin id'sini döndürüyor.Bu id düz yazı formatında dönüyor.Kullanıcının ise bu POST isteğinde kullanacağı verinin JSON formatında olması gerekiyor (@Consumes).Buraya kadar olan kısmı çalıştırıp GET metoduyla yapılan istekleri kontrol edelim.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mycompany.client; | |
import javax.ws.rs.client.*; | |
import javax.ws.rs.core.*; | |
public class ClientApp { | |
public static void main(String []args){ | |
Client client=ClientBuilder.newClient(); | |
WebTarget target=client.target("http://localhost:8080/PostAnnotation/api/customers"); | |
postUsingRawJSON(target); | |
postByObjectToJasonTransformation(target); | |
getAllCustomers(target); | |
} | |
private static void getAllCustomers(WebTarget t){ | |
String s=t.request().get(String.class); | |
System.out.println("All customers : "+s); | |
} | |
private static void postUsingRawJSON(WebTarget target){ | |
String customer = ClientUtil.createCustomerInJSON("Alyssa William" | |
, "1021 Hweitt Street" | |
, "343-343-3433"); | |
String response = target.request() | |
.post(Entity.entity(customer, MediaType.APPLICATION_JSON) | |
, String.class); | |
System.out.println("customer created with id: "+response); | |
getCustomerById(target, response); | |
} | |
private static void getCustomerById(WebTarget target, String response) { | |
String s = target.path(response) | |
.request() | |
.get(String.class); | |
System.out.println("new customer :"+s); | |
} | |
private static void postByObjectToJasonTransformation(WebTarget target) { | |
Customer newCustomer = ClientUtil. | |
createCustomer("Jake Mae", "342, " + | |
"Snake Dr, GreenLake", "444-333-4564"); | |
String response = target.request(MediaType.APPLICATION_JSON).accept(MediaType.TEXT_PLAIN_TYPE) | |
.post(Entity.json(newCustomer) | |
,String.class); | |
System.out.println("customer created with id: "+response); | |
getCustomerById(target, response); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mycompany.client; | |
public class ClientUtil { | |
public static String createCustomerInJSON(String name,String address,String phoneNumber){ | |
return String.format("{\"name\":\"%s\",\"address\":\"%s\",\"phoneNumber\":\"%s\"}", | |
name, address, phoneNumber); | |
} | |
public static Customer createCustomer(String name,String address,String phoneNumber){ | |
Customer c=new Customer(); | |
c.setName(name); | |
c.setAddress(address); | |
c.setPhoneNumber(phoneNumber); | |
return c; | |
} | |
} |
Bu sınıfımızdaki fonksiyonlar ise oluşturduğumuz webservisine uygun formatlarda requestler yaparak dönen değerleri yazdırıyor.Buradaki mantığı anlatacak olursak siz bir request yaparken bunun isteğini belirtirsiniz.Daha sonra bu isteği yapacağınız hedef adresinizin bilinmesi ve bu adrese gidebilmeniz için bir sunucunuzun olması gerekiyor.Sunucu demişken önceki örneklerimizde glassfish'i kullanırken bu ve sonraki örneklerimizde Ertuğrul hocamın tavsiyesiyle payara'yı kullanacağız. Glassfish'ten kurtulmanın mutluluğu içerisindeyiz.Bunu kutlamamız gerekiyor :). Neyse devam edelim.Tabiki yapacağınız post isteklerinde verinin hangi formatta olduğuda önemli bunun içinde clientutil sınıfımızı yazmıştık.Önce projemizi run edip daha sonra clientapp sınıfımızı run ettiğimizi unutmayalım. Şimdi çıktılarımıza bakalım.
Umarım anlatabilmişimdir :).Herkese huzurlu günler diliyorum...
Hiç yorum yok:
Yorum Gönder