5 Aralık 2013 Perşembe

JAVA DA RSS OKUMA

RSS çeşitli internet siteleri tarafından yayınlanan haber vb. içeriğin tek bir ortamdan topluca izlenebilmesine olanak sağlayan yeni bir içerik besleme yöntemidir. RSS – Real Simple Syndication, RDF Site Summary veya RichSite Summary (Zengin Site Özeti) kelimelerinin baş harflerinden oluşan kısaltmadır. XML biçiminde olan RSS dosyaları ilk olarak NetScape firması tarafından geliştirilmeye başlanmıştır. RSS dosyalarının kullanımı her geçen gün artarak yaygınlaşmaktadır.
RSS yöntemini destekleyen sitelerin hazırladıkları XML biçimli dosyalara bir çok programla erişmek mümkündür. XML okuyucusu olan bu programlar, web gezgini veya e-posta istemcisi olabileceği gibi sadece RSS içeriği izlemek için hazırlanan masaüstü programları da olabilir.
İşte biz de bu yazımızda bir RSS linkinden gerekli bilgilerin nasıl çekildiğini öğreneceğiz.
RSS dosyalarında ki xml tag leri genelde aynıdır.Bunlar "title","content","date" ilh.
Tagler genelde aynı olduğundan,Java da RSS okuma işlemi için iki tane kütüphane yazılmıştır.Bu iki kütüphaneyi de projemize eklememiz gerekir.Bu kütüphaneler JDOM ve rome kütüphaneleridir.JDOM u buradan , rome kütüphanesini ise buradan indirebilirsiniz.
Bu kütüphaneleri indirip projemize ekledikten sonra artık kodlamaya başlayabiliriz demektir.RSS linki olarak kendi blogumun rss feed ini kullandım.


BlogItems.java

public class BlogItems implements Serializable {

    private String title;
    private String content;
    private String date;

    public BlogItems(String title, String content, String date) {
        this.title = title;
        this.content = content;
        this.date = date;
    }


public String getTitle() {
        return title;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}



BlogVeriler.java

public class BlogVeriler {

    private List<BlogItems> blogItems = new ArrayList<BlogItems>();
    private String url = "http://mesutemre.blogspot.com/feeds/posts/default?alt=rss";

    public List<BlogItems> getBlogItems() {
        return blogItems;
    }
    public void setBlogItems(List<BlogItems> blogItems) {
        this.blogItems = blogItems;
    }
    public void verileriGetir() {
        try {
            URLConnection feedUrl = new URL(url).openConnection();
            SyndFeedInput input = new SyndFeedInput();
            SyndFeed feed = input.build(new com.sun.syndication.io.XmlReader(feedUrl) {
            });
            List<SyndEntry> feedList = feed.getEntries();
            int feedSize = feedList.size();
            for (int i = 0; i < feedSize; i++) {
                SyndEntry entry = (SyndEntry) feedList.get(i);
                String title = entry.getTitle();
                String content = entry.getDescription().getValue();
                String date = entry.getPublishedDate().toString();
                blogItems.add(new BlogItems(title, content, date));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

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.