20 Kasım 2013 Çarşamba

JSF CUSTOM TAGS

JSF özel içerikler içeren hususi tagler oluşturmamıza izin vermektedir.Custom tag oluşturmanın adımları aşağıda ki gibidir.
Adım 1a. Bir xhtml dosyası oluşturup ui:composition tagini kullanan bir içerik hazırlanır
Adım 1b. Custom tag'in tanımlı olduğu bir xml dosyası oluşturulur.(taglib.xml)
Adım 1c. Bu tag library web.xml dosyasına kaydedilir
Bu adımları bir örnek üzerinde tatbik edelim.Mesela sıkça kullandığımız bir kayıt ekranının hazır form tagini yazalım.Form da ad ve soyad girilip  kayıt butonuna basıldığı zaman ManagedBean de bir kontrol sonucu bize "Hoşgeldiniz sayın Alimcan Karluk" gibi bir mesaj verecektir.

kayitFormu.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <head>
        <title>TODO supply a title</title>
    </head>
    <body>
        <ui:composition>
            <h:form>
                <h:panelGrid border="0" columns="2">
                    <h:outputLabel value="Ad:"/>
                    <h:inputText value="#{kayitad}" required="true"
                                 requiredMessage="Lütfen adınızı giriniz!" />
                    <h:outputLabel value="Soyad:"/>
                    <h:inputText value="#{kayitFormKontrol.soyad}" required="true"
                                 requiredMessage="Lütfen soyadınızı giriniz!"/>
                    <h:commandButton value="Kaydet" action="#{kayitFormKontrol.giris()}"/>
                    <h:commandButton value="Temizle" type="reset"/>
                    <h:outputLabel value="#{kayitFormKontrol.sonuc}"
                                   style="color: blue;font-style: italic" />
                    <h:messages style="color: red; font: bolder" />
                </h:panelGrid>
            </h:form>
        </ui:composition>
    </body>
</html>

Bu xhtml sayfasını yazarak 1.adımı tamamlamış oluruz.Şimdi ikinci adım olan taglib.xml dosyasını yazalım.

formTaglib.xml

<facelet-taglib>
    <namespace>http://mesutemre.blogspot.com</namespace>
    <tag>
            <tag-name>kayitForm</tag-name>
            <source>tags/kayitFormu.xhtml</source>
    </tag>
</facelet-taglib>
Yazdığımız bu taglib.xml dosyasının web.xml dosyasına kaydı aşağıda ki gibi yapılır.Bu dosyada ki namespace ve tag-name ileride karşımıza çıkacaktır.

web.xml

<context-param>
        <param-name>facelets.LIBRARIES</param-name>
        <param-value>/WEB-INF/formTaglib.xml</param-value>
 </context-param>

Yazdığımız custom tag'in bir web sayfasında kullanımı aşağıda ki gibidir.

index.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:kayitform="http://mesutemre.blogspot.com"
      >
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <kayitform:kayitForm kayitad="#{kayitFormKontrol.ad}"/>
        <br/>
        <h:outputText value="Her hakkı saklıdır."/>
    </h:body>
</html>

kayitFormu.xhtml sayfasında kullandığımız ManagedBean aşağıda ki gibidir.

KayitFormKontrol.java

package com.mesutemre;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean
@RequestScoped
public class KayitFormKontrol {

    private String ad,soyad;
    private String sonuc="";

    public String getSonuc() {
        return sonuc;
    }

    public void setSonuc(String sonuc) {
        this.sonuc = sonuc;
    }
   
    public String getAd() {
        return ad;
    }

    public void setAd(String ad) {
        this.ad = ad;
    }

    public String getSoyad() {
        return soyad;
    }

    public void setSoyad(String soyad) {
        this.soyad = soyad;
    }
   
    public void giris(){
        if(!ad.isEmpty() && !soyad.isEmpty()){
            sonuc+="Hoşgeldiniz sayın "+ad+" "+soyad;
        }
    }
}

Yazdığımız bu dosyalar aşağıda ki gibi lokalize edilir.


Uygulamanın çıktısı aşağıda ki gibi olur.





20 Ekim 2013 Pazar

JSF de XML içeriğini h:dataTable ile gösterme

Önceki yazımızda URL den alınan bir XML in nasıl parse edildiği üzerine konuşmuş ve bir de uygulama yapmıştık.
Şimdi yaptığımız bu uygulamadan dönen sonuçları JSF nin en mühim componentlerinden olan <h:dataTable> ile kullanalım.
Senaryomuz şu şekilde;
XML den çektiğimiz resim linkini  bir h:graphicImage tagi ile kullanıp resmi bu sayede göstereceğiz. Ayrıca XML den aldığımız title ve link elemanlarını da h:dataTable da yazdıracağız. Lafı fazla uzatmadan işin kodlama kısmına geçelim.
Kodlama kısmında bize lazım olan verileri tutabileceğimiz bir class,bir managed bean ve bir tane de xhtml sayfası.

public class SatanlarItems implements Serializable{
   
    private String image;
    private String description;
    private String title;

    public SatanlarItems(String image, String description, String title) {
        this.image = image;
        this.description = description;
        this.title = title;
    }

   

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}


@ManagedBean(name = "ecs")
@RequestScoped
public class EnCokSatanlarManagedBean {

    private List<SatanlarItems> arr = new ArrayList<SatanlarItems>();
    private static String url = "http://www.gold.com.tr/cok-satanlar-rss/54109/0";

    public List<SatanlarItems> getArr() {
        return arr;
    }

    public void setArr(List<SatanlarItems> arr) {
        this.arr = arr;
    }

    public void listele() throws MalformedURLException, IOException, ParserConfigurationException, SAXException {
        URL geoLocationDetailXMLURL = new URL(url);
        URLConnection geoLocationDetailXMLURLConnection = geoLocationDetailXMLURL.openConnection();
        BufferedReader geoLeocationDetails = new BufferedReader(new InputStreamReader(geoLocationDetailXMLURLConnection.getInputStream(), "UTF-8"));
        InputSource inputSource = new InputSource(geoLeocationDetails);
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();

        String expression = "rss/channel/item";
        String expressionTitle = "rss/channel/item/title";
        String expressionDesc = "rss/channel/item/link";
        String expressionImage = "rss/channel/item/image/url";

        XPath xPath = XPathFactory.newInstance().newXPath();
        org.w3c.dom.Document doc = builder.parse(inputSource);

        try {
            NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
            NodeList nodeListTitle = (NodeList) xPath.compile(expressionTitle).evaluate(doc, XPathConstants.NODESET);
            NodeList nodeListDesc = (NodeList) xPath.compile(expressionDesc).evaluate(doc, XPathConstants.NODESET);
            NodeList nodeListImage = (NodeList) xPath.compile(expressionImage).evaluate(doc, XPathConstants.NODESET);
           
            for (int i = 0; i < nodeList.getLength(); i++) {
                int k = nodeListImage.item(i).getFirstChild().getNodeValue().toString().length();
                arr.add(new SatanlarItems(nodeListImage.item(i).getFirstChild().getNodeValue().toString()
                        .substring(0, k-1),
                        nodeListDesc.item(i).getFirstChild().getNodeValue(),
                        nodeListTitle.item(i).getFirstChild().getNodeValue().toString()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



index.xhtml
<h:form>
            <h:commandButton value="Al" action="#{ecs.listele()}"/>
            <br />
            <h:dataTable value="#{ecs.arr}" var="a" border="1">
                <h:column>
                    <f:facet name="header">ÜRÜN FOTOĞRAFI</f:facet>
                    <h:graphicImage url="#{a.image}"/>
                </h:column>

                <h:column>
                    <f:facet name="header">BAŞLIK</f:facet>
                        #{a.title}
                </h:column>

                <h:column>
                    <f:facet name="header">AÇIKLAMA</f:facet>
                    <a href="#{a.description}">Detaylı bilgi için tıklayın</a>
                </h:column>
            </h:dataTable>
        </h:form>

Uygulamanın çıktısı aşağıda ki gibi olur.


18 Ekim 2013 Cuma

JAVA DA XML PARSE ETME (XPATH)

Java da XML parse etmenin birkaç metodu olmakla beraber bunların bazıları;
            -DOM  Parser
            -SAX Parser
            -JAXP
XPath bir W3C standardı olup XML dokümanının içinde ki bilgileri elde etmek için kullanılır. Küçük bir programlama dili gibi metodları, testleri ve ifadeleri vardır.
Bir XML dosyasını URL den veya dosyadan okuyabiliriz. Okuma mantığı her zaman aynıdır. Aşağıda yazdığım kodlar URL den çekilen bir XML dosyasının parse edilişidir. XPath ile alâkalı detaylı bilgiye buradan ulaşabilirsiniz. Biz lafı fazla uzatmadan kodlama kısmına geçelim.
Senaryomuz şu şekilde;
Elimiz de XML formatında bir URL var ve biz bu URL den bize lazım olan resim linklerini alacağız.

public class XPathParser {
    private static String url = "http://www.gold.com.tr/cok-satanlar-rss/54109/0";
    private static ArrayList<String> arr = new ArrayList<>();
    public static void main(String[] args) throws ParserConfigurationException, MalformedURLException, IOException, SAXException, XPathExpressionException {
        URL geoLocationDetailXMLURL = new URL(url);
        URLConnection geoLocationDetailXMLURLConnection = geoLocationDetailXMLURL.openConnection();
        BufferedReader geoLeocationDetails = new BufferedReader(new InputStreamReader(geoLocationDetailXMLURLConnection.getInputStream(), "UTF-8"));
        InputSource inputSource = new InputSource(geoLeocationDetails);
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder =  builderFactory.newDocumentBuilder();
        org.w3c.dom.Document xmlDocument = builder.parse(inputSource);
        XPath xPath =  XPathFactory.newInstance().newXPath();
        String expression = "rss/channel/item/image/url";   
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);      
        for (int i = 0; i < nodeList.getLength(); i++) {
            arr.add(nodeList.item(i).getFirstChild().getNodeValue().toString());
        }
       
        for (int i = 0; i < arr.size(); i++) {
            System.out.println(arr.get(i));
        }
    }
}
Çıktı aşağıda ki gibi olacaktır.

http://cdn.gold.com.tr/UrunResim/BuyukResim/22500118260518.jpg
http://cdn.gold.com.tr/UrunResim/BuyukResim/23289917929781.jpg
http://cdn.gold.com.tr/UrunResim/BuyukResim/23681317937327.jpg
http://cdn.gold.com.tr/UrunResim/BuyukResim/23681117934373.jpg
http://cdn.gold.com.tr/UrunResim/BuyukResim/24087418137445.jpg
http://cdn.gold.com.tr/UrunResim/BuyukResim/24252218265797.jpg
http://cdn.gold.com.tr/UrunResim/BuyukResim/21674611123910.jpg
http://cdn.gold.com.tr/UrunResim/BuyukResim/23680917931225.jpg