Search Blog

Search duranek.blogspot.com

Tuesday, January 31, 2012

Cobertura

Cobertura? Cobertura is a free Java tool that calculates the percentage of code accessed by tests. It can be used to identify which parts of your Java program are lacking test coverage. It is based on jcoverage.

Strategy Pattern ( Behavioral )

Strategy Pattern

1)    Policy Pattern olarak da soylenir
2)    Pattern
    A)    Once bir interface ve metodu tanimlanir.
    o metod strategy oluyor.
    B)    strategy'yi implemente eden class
    lar yazilir.
    C)    icinde strategy referansi olan
        context class'i yazilir.
    D)    Daha sonra farkli strategy lerde
        context class'ini yaratabiliriz.

3)    Class lar sadece behaviour'lari belli
    duruma gore degisirse kullanilir.

Neden HSQLDB

hsqldb

1)    index yok
2)    tablo kolonlari ve size lerde limit yok gibi bir sey
3)    genelde standalone application lar icin yazildi. Her client a 
    mysql server kurmamak icin. multi user distributed client system icin
    uygun degil.
4)    unit test icin kullanilabilir.

Sunday, January 29, 2012

GWT - SmartGWT Version Upgrade

Gerekli jarlari degistirdikten sonra, clean edip, war\deploymentplan ve WEB-INF\deploy directorylerini mutlaka silmek gerekiyor. Cunku eski generation lar kaliyor, hata veriyor. Daha sonra full compile edip calistirmak gerekiyor. Jar lari sadece build path de degil, WEB-INF\lib de de kullaniyor olabilirsin dikkat. Onlari da degistirmek gerekir.

GWT - Spring Integration

GWT and Spring
1)    Spring MVC class larini kullanacagiz.29
2)    web.xml e Spring MVC servletini ekle

    <!-- Initialise the Spring MVC DispatcherServlet -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map the DispatcherServlet to only intercept RPC requests -->
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.rpc</url-pattern>
    </servlet-mapping>
    
3)    DispatcherServlet in web.xml'deki name'i xxx ise xxx-servlet.xml adinda kendi bean xml'ini arar. Burada spring-servlet.xml olacak.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <!-- The application context definition for the DispatcherServlet -->

    <!-- Maps the request through to a concrete controller instance -->
    <bean id="urlMapping"
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <value>
                /**/login.rpc=loginController
            </value>
        </property>
    </bean>

    <!-- GwtRpcController wraps our service in order to decode the incoming -->
    <!-- request then delegates processing of the call to the POJO service -->
    <!-- and then encodes the return value forwarding the response. -->
    <bean id="loginController" class="com.deploymentplan.server.user.GwtRpcController">
        <property name="remoteService">
            <bean class="com.deploymentplan.server.user.LoginWindowImpl" />
        </property>
    </bean>

</beans>

4)    Annotation ile servise belirt

@RemoteServiceRelativePath("login.rpc")
public interface LoginWindowService extends RemoteService{

bu login.rpc, web.xml de servlet-mapping'de spring servlet'i ile map edecek o da yine web.xml de servlet tag'inde tanimladigimiz
DispatcherServlet'i cagiracak. DispatcherServlet spring-servlet.xml'i kullanacak, login.rpc'nin map ettigi controller'i bulacak.
yine spring-servlet.xml'de o controller'a remoteservice olarak LoginServiceImpl oarak map edecegiz.

5)    Simdi server tarafini yazalim.

public class LoginWindowImpl implements LoginWindowService {

Fakat normalde bu sekildeydi ??

public class LoginWindowImpl extends RemoteServiceServlet implements LoginWindowService {

6)    Yazilana gore bunun Deploymentplan.gwt.xml'e eklenmesi gerekiyor. Fakat ben eklememistim calisiyordu. Simdilik eklemeden deneyelim.

<!-- RPC service servlet declarations                             -->
<servlet path="/login.rpc"
    class="com.deploymentplan.server.user.LoginWindowImpl"/>
    
7)     GwtRpcController'in yazilmasi. Bu sekilde spring-mvc DispatcherServler in handle ini RemoteServiceServlet'e atiyoruz. RemoteServiceServlet'in processCall'unu
da biz yapiyoruz. Bunu yapmamizin nedeni ise, remoteService'i spring-servlet.xml de biz atamistik. Onunla cagirsin diye.

package org.example.gwtwisdom.server;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class GwtRpcController extends RemoteServiceServlet implements
        Controller, ServletContextAware {

    private ServletContext servletContext;

    private RemoteService remoteService;

    private Class remoteServiceClass;

    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        super.doPost(request, response);
        return null;
    }

    @Override
    public String processCall(String payload) throws SerializationException {
        try {

            RPCRequest rpcRequest = RPC.decodeRequest(payload,
                    this.remoteServiceClass);

            // delegate work to the spring injected service
            return RPC.invokeAndEncodeResponse(this.remoteService, rpcRequest
                    .getMethod(), rpcRequest.getParameters());
        } catch (IncompatibleRemoteServiceException ex) {
            getServletContext()
                    .log(
                            "An IncompatibleRemoteServiceException was thrown while processing this call.",
                            ex);
            return RPC.encodeResponseForFailure(null, ex);
        }
    }

    @Override
    public ServletContext getServletContext() {
        return servletContext;
    }

    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public void setRemoteService(RemoteService remoteService) {
        this.remoteService = remoteService;
        this.remoteServiceClass = this.remoteService.getClass();
    }

}

8)    Client tarafinda async'i cagirirken

GWT.create(LoginWindowService.class);

9)    Islerimizi spring in DispatcherServlet'i ile halledegimiz icin, artik gwt nin integrated tomcat'ini 
kullanamayiz. web.xml'lerimiz farkli artik. Hosted mode'un -noserver switch'i bizi kurtariyor.
Burada bir alicengiz yapiyoruz. Bir kereligine tomcat'imize deploy etmemiz lazim ki, tomcat application'imizi bilsin.
O bildikten sonra, eclipse uzerinden workspace den calisabilir olacagiz. Tomcat'e bir kere deploy edip
calisip calismadigina bakiyoruz.

10)    Eclipse den Run configurations diyoruz.
program arguments a bakiyoruz.
Daha once su yaziyordu

-remoteUI "${gwt_remote_ui_server_port}:${unique_id}" -startupUrl DeploymentPlan.html -logLevel INFO -port 8888 -war D:\dev2\git\dpgwt\DeploymentPlan\war -codeServerPort 9997 com.deploymentplan.DeploymentPlan

simdi,

-startupUrl http://localhost:8080/DeploymentPlan -noserver -remoteUI "${gwt_remote_ui_server_port}:${unique_id}" -logLevel INFO -codeServerPort 9997 -war D:\dev2\git\dpgwt\DeploymentPlan\war com.deploymentplan.DeploymentPlan

bunu su sekilde de diyorlar, startupUrl i degistir ve sonuna -noserver koy

11)    Bu sekilde client i debug edebilirsin.
server'i debug etmek icin remote debug eklemen lazim.

Eclipse Tomcat Remote Debug

Eclipse Tomcat Remote Debug

1)    Catalina.bat icine 
set DEBUG_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

2)    daha sonra run debug configuration icinden ( debug olan yalniz, normal olanda bulamazsin )
remote java application sec. port 8000 olsun.

3) bu sekilde gwt de debug edebilirsin


Spring MVC servlet xxx is not available hatasi

Spring MVC kullanirken, Dispatcher kullaniyorsan,
asagidaki hatayi aliyorsan, web.xml'in icinden 
load on startup'i kaldirip, hangi class'in eksik
oldugunu bul. Onu ekleyip tekrar dene
com.google.gwt.user.client.rpc.StatusCodeException: 404 Apache Tomcat/6.0.20 - Error report

HTTP Status 404 - Servlet spring is not available


type Status report

message Servlet spring is not available

description The requested resource (Servlet spring is not available) is not available.


Apache Tomcat/6.0.20

Ant ve Tomcat

Ant Ile Tomcat manage etmek icin

1)    Once catalina-ant.bat 'i ant runtime e eklemek gerekiyor.

2)    D:\dev2\apache-tomcat-6.0.20\conf\tomcat-users.xml  edit et.    
    
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="admin" password="admin" roles="admin,manager"/>
  
3)        

    <taskdef name="deploy" classname="org.apache.catalina.ant.DeployTask" />
    <taskdef name="undeploy" classname="org.apache.catalina.ant.UndeployTask" />

    <target name="deploy">
        <deploy url="http://localhost:8080/manager"
            username="admin"
            password="admin"
            path="/${name}"
            update="true"
            localWar="${dist.dir}/${name}.war" />
    </target>

    <target name="undeploy">    
        <undeploy url="http://localhost:8080/manager"
            username="admin"
            password="admin"
            path="/${name}" />
    </target>
    
    <target name="tomcat-start">
        <java jar="${tomcat.home}/bin/bootstrap.jar" fork="true">
            <jvmarg value="-Dcatalina.home=${tomcat.home}"/>
        </java>
    </target>

    <target name="tomcat-stop">
        <java jar="${tomcat.home}/bin/bootstrap.jar" fork="true">
            <jvmarg value="-Dcatalina.home=${tomcat.home}"/>
            <arg line="stop"/>
        </java>
    </target>

web.xml de order onemli

İki servlet tag'i arasina servlet-mapping yazarsan hata verir. Belirtilen sirada yapmak zorundasin.

Tuesday, January 24, 2012

Apache CXF - Eclipse Platform

1)    Apache CXF Download 2.3.0
    Binary distribution
2)     Latest Eclipse J2EE Version Helios
3)    Tomcat 7.0.2

4)    Tomcat'i eclipse e tanimlama
    Java Eclipse
    Window\preferences
    Server category
    Runtime Environments
    Press Add Apache tomcat 7.0
    Browse, choose root directory.
    JRE kismina jdk secmemiz lazim. Bunun nedeni jsp compilation icin
    ok    

5)    File new dynamic web project
    Dynamic Web Module Version 2.5 secmek lazim
    daha stable.
    Sonra finish'e bas.

6)    New Servlet de
    doGet metodunu implement et

7)    doGet icine
    response.setContentType("text/html")
    PrintWriter out = response.getWriter();
    out.println("<html> ...");
    
    right click run, then run on server

8)    PreferencesWeb Services
    CXF 2.x Preferences
    Add
    CXF Home: apache-cxf-2.3.0

9)    Preferences 
    server and runtime
    select apache cxf. 2.x

10)    New Dynamic Web Project
    Dynamic web module version 2.5
    Configuration : cxf web services project v2.5
    finish

11)    Standart java class yap.    

12)    public String xxx(String xxx) {
        return xxx;
    }

13)    new web service
    objeyi sec
    client ve sever full sec
    monitor the web servce
    next
    use a service endpoint interface
    create and SEI
    skip annotations.
    generate wsdl
    generate wrapper and fault beans
    default soap binding: soap 1.1
    generate separate xsd for the types
    press start server
    test facility web service explorer
    press next
    we don't need bindings.
    next
    next
    next
    next
    finish

14)    web service explorer is for testing web service.
    DeepThoughtSEI_...Client.java 
    generated code.
    right click, run as java application
    calisir. bu koddan bakarak, nasil yapildigini
    ogrenirsin.
    
15)    Web service:
    contract-first : wsdl+sml schema : java code (exchange)
    code-first : java-code : wsdl+sml-schema (initial)

16)    cxf is very well integrated iwth spring.easy
    axis2 : cok fazla support ediyor

Ant Environment Variables in Eclipse

If you change the environment variable when eclipse is open, you have to restart for seing it.

Sunday, January 22, 2012

Spring Transaction Management 2

Spring Transaction Management

1)    ACID principle : Atomicity, Consistentency, isolation, durability 
2) You can handle transaction
    a)    in SQL
    b)    in JDBC
    c)    in ORM ( Hibernate, iBatis etc.. )
    d)    in EJB or Spring
    
3)    @Transactional annotation'i yalnizca servis metoduna konur. DAO metodlarina konmaz.
Cunku servis bircok DAO cagirabilir.

4) Propagation

@Transactional(propagation = Propagation.REQUIRED)

REQUIRED - uses the existing transaction. If it doesn't exist, creates a new one
REQUIRES_NEW - must start a new transaction. If there's an existing one, it should be suspended
SUPPORTS - if there is a transaction, runs in it. If there isn't, it just runs outside transaction context
NOT_SUPPORTED - must not run in a transaction. If there's an existing one, it should be suspended
MANDATORY - must run in a transaction. If there isn't one, it throws an exception
NEVER - must not run in a transaction. If there's an existing one, an exception will be thrown
NESTED - if there is a transaction, it runs withing the nested transaction of it. Otherwise it runs in its own

Default olani REQUIRED olan.
    
5)    Isolation

Concurrent Transaction Problems:

    a)    Lost Update
        Two transactions both update a row, second one rolls back, 
        both changes are lost
    b)    Dirty Read 
        Reading the changes without being committed. Rollback olursa patlar.
    c)    Unrepeatable read
        Ayni row'u iki kere select ederken, arada diger transaction commit
        ederse, ikincisinde farkli gorme.
    d)    Phantom Read - Unrepeatable a benziyor. Sadece ikinci transaction, insert yaparsa
        ve ilk transaction ozellikle bir satiri degil, kosulu select ediyorsa, ilk selecte
        gore daha fazla kayit gelebilir.

Isolation Levels:

DEFAULT - database isolation level, default
        Possible Problems:
        1)    unrepeatable read
        2)    phantom read
        3)  dirty read
        4)    Lost Update
READ_UNCOMMITTED - dirty read. No Lock.
        Possible Problems:
        1)    unrepeatable read
        2)    phantom read
        3)  dirty read
READ_COMMITTED - Write Lock
        Possible Problems:
        1)    Unrepeatable Read
        2)    Phantom Read
REPEATABLE_READ - Write Lock, Read Lock
        Possible Problems:
        1)    Phantom Read
SERIALIZABLE - No Problem, but performance is low - Write Lock, Read Lock, Range Lock



6)    Sadece Unchecked Exception lar rollback olur !
    Unchecked exception : RuntimeException

    a)Metod sorunsuz biterse commit
    b) catch edilen exception rethrow edilmezse, transaction commit.
    c) checked exception catch edilse de edilmese de ( rethrow olsa )
        transaction commit.
    d) unchecked exception catch edilmezse! o zaman rollback.
    
    Yukaridaki default olani. Eger ozellikle belirtmek istiyorsan:
    
    @Transactional(rollbackFor = IOException.class, noRollbackFor = RuntimeException.class)
    public void doSomething(...
    

Spring and JUnit 4

Spring and JUnit 4

1)    File/New/JUnit Test Case 
    Create a New JUnit 4 Test
    
    @Test tag'i JUnit 4'un test methodunu gosteriyor

2)    Add @RunWith(SpringJUnit4ClassRunner.class)

When JUnit starts the test case, Spring will now create a TestContextManager 
and three default TestExecutionListeners: 
    1)    DirtiesContextTestExecutionListener, 
    2)    DependencyInjectionTestExecutionListener, 
    3)    TransactionalTestExecutionListener.
    
3)    Spring'in bunlari yapabilmesi icin, bir context.xml'i point etmek lazim.
Bunu da, @ContextConfiguration("xxx.xml")
seklinde class a ekleyerek yapiyoruz. Hemen @RunWith'in ustune ya da altina.

4)    Eger bir test, context'i bozuyorsa, o test metodunun ustune @DirtiesContext
deriz, ki bittikten sonra context refresh olsun.

5) Icinde database olan testleri yapabilmek icin,
 @Transactional  da ekleriz ki, TransactionalTestExecutionListener calissin,
 ve testten sonra degisiklik varsa onlari rollback etsin.
 
6) @RunWith yapmamak icin, AbstractJUnit4SpringContextTests den extend de yapabiliriz.
ayrica bize degerli access ler verir: applicationContext ve logger, simpleJdbcTemplate.
yararli metodlar: countRowsInTable, deleteFromTables, executeSqlScript

Static Import

Static Import

If you don't want to use like that: Math.PI but 
like that PI , you have to static import :
import static java.lang.Math.* 
or
import static java.lang.Math.PI

Spring Transaction Management 1


1)        Transaction Manager yaratma

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <!-- <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/> -->
        <property name="url" value="jdbc:hsqldb:mem:BankApp"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>
        
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    Bunu DataSourceTransactionManager kullaniyoruz cunku, JDBC kullaniyoruz. Eger Hibernate kullansaydik,
    transactionManager'imizin adi HibernateTransactionManager olmaliydi.
    
    
    Bu asagidakiler yerine, 
    
    To do setAutoCommit(false);
    To use Same Connection from datasource
    Commit If all successful
    Rollback is not successful
    
    @Transactional annotation ekleriz ve hepsi olur. Bunu metoda ekleriz. Eger class'a eklersek, butun public metodlar
transactional olur
    
2)    <tx:annotation-driven/>  'in eklenmesi gerekiyor. Bu BeanPostProcessor'a @Transacitonal'lari
handleetme davranisini register ediyor.

Annotations 1

@Override :  Method gerçekten override etmiyorsa,
isim vs. yanlis yaziysan uyarir.

@Deprecated : javadoc daki @deprecated ile ayni

Declarative Transaction Management

Programmatic vs. Declarative


Spring offers two ways of handling transactions: programmatic and declarative. If you are familiar with EJB transaction handling, this corresponds to bean-managed and container-managed transaction management.

Programmatic means you have transaction management code surrounding your business code. That gives you extreme flexibility, but is difficult to maintain and, well, boilerplate.

Declarative means you separate transaction management from the business code. You only use annotations or XML based configuration.

We say that:
programmatic management is more flexible during development time but less flexible during application life
declarative management is less flexible during development time but more flexible during application life

Thursday, January 19, 2012

Equals & HashCode

Equals And HashCode

1) equals()  methodu override edilmezse, sadece iki referans esitse
ayni obje olarak kabul edilir. Eger override etmezsek, Hash collection
larinda search yaparken sorun yasariz. Cunku value'yu bulmak icin
key olarak objenin ozelliklerini degil referansını key olarak 
koymus oluyoruz.
2) String and Wrapper classes work good with Hash collections.
3) Hashing retrieval :
    1) Find the right bucket (using hashCode();)
    2) Search the bucket for the right element (using equals();)
4) Hashcode metodunda, equals metodunda kullandigin degiskenleri 
kullanarak bir hashCode ureteceksin.
5) Eger equals olarak obje esitse, hashcode lari da esittir
   hashcode lar esitse, equals lar esit olmayabilir.
   hashcode olarak sabit bir deger gonderirsek, bu compile eder ama yavas olur.
6) Transient variable lari hashcode da kullanma. cunku kazara
serialize edip deserialize edersen, hashmap in icinde bulamazsin.

Wednesday, January 18, 2012

JDK Differences


java 1.5 ve java 1.4

1)    Auto boxing/unboxing
2)    Generics
3)    Annotations
4)     java.util.concurrent
5)    enum
6)    variable number of arguments
7)    new for loop
8)    import static
9)    printf    

java 1.6 vs java 1.5

1)    Improvements and performance
2)     Embedded Java DB (based on apache derby )
3)     swing

java 1.7 vs java 1.6

1)    faster then java 6
2)     better garbage collector
3)    modularization
4)    autoclosable
5)    Strings are allowed in switch
6)    

PreparedStatement vs Statement

PreparedStatement vs Statement

PreparedStatement'in java ile alakasi yok aslinda. Database server'in yaptigi
bir is. Precompilation yapiyor, execution plan'i hazirlayip cacheliyor, boylece
ileriki execute larda hizli oluyor.

PreparedStatement, ilk ucunu hazirliyor. Yani db ye iki defa gidilir.

The following occurs when a database receives a SQL statement:

1) The database parses the statement and looks for syntax errors.
2)The database validates the user to make sure the user has privileges to execute the statement.
3)The database validates the semantics of the statement.
4)The database figures out the most efficient way to execute the statement 
and prepares a query plan. Once the query plan is 
created, the database can execute the statement.

1)    Performance
2)    SQL injection'i onler. 
3)     Runtime sirasinda Parametre yazabiliriz.
4)    PreparedStatement larin tercih edilmedigi yerler daha cok memory yedigi
    icin embed cihazlar olabilir. Cok az ram'i olan.

Cross Join

What Mean SQL Cross Join ?

This is cartesian multiplication. Multiplying first
table with the second.

SELECT * FROM [TABLE 1] CROSS JOIN [TABLE 2]

OR

SELECT * FROM [TABLE 1], [TABLE 2]


Immutable Class


immutable class:

1) class must be final
2) All methods must be final
3) All members must be private and final
4) There will be no setter methods
5) Constructor is public
6) If member variable is an Object, then getObject method must return 
a new Object with same values. Don't return the reference
7) If member variable is an Object then constructor must create new Object with
the values of the object.
8) If you want to change an amount in the class for example, you always create
new Object with new value.
9) Eger member variable larda List varsa, listi get yaparken,
Collections.unmodifiableList(mOBList);
yapacaksin. Listenin icindekiler de immutable olmak zorunda.

Tuesday, January 17, 2012

Flyweight Pattern ( Structural )

Flyweight Pattern ( Structural Design Pattern )

1) Iskambil Oyunu yapacagiz. 52 Tane kagit var. Bu 52 kagitta 4 tip olur. 
   Kupa Karo Maca Sinek
   Her birinden 13 tane var. 
   Eger iskambil kagidi bir obje ise, o objenin hem tip hem de numara variable'i olacak.
   Basite indirgeyelim. Her variable 1 byte olsun.
   52 kagit icin, toplam 52x2 = 104 byte yer gerecek.
   Fakat Her tipi obje yapip, variable'lara o objenin referansini versek,
   52 kagit var, numaralar icin 52, tip icin 4 olacak, boylece 56 byte yer ayiracagiz.
   Her tipi de ihtiyac oldugumuz zaman yaratsak, performans da cok hizli olacaktir. 
   Bunu map ile yapiyoruz.
2) Bu durumda, FlyweightFactory class'i, bize istenen tipi dondurecek. Icinde bir map olacak.
O map te tip varsa dondurecek, yoksa yaratacak, yarattigini map'e atacak ve dondurecek.
Burada da flyweight tip oluyor.


Monday, January 16, 2012

RMI in 2011

RMI in 2011

1) Java to Java ya limited.
2) Bir tarafta yapilan degisikligi diger tarafa da deploy etmek
lazim. serilizationVersionUID den dolayi. Load balancer'larda
daha da sorun cikartabiir.
3) RMI son donemlerde pek dikkat cekmiyor.
4) Performansı iyi.
5) Web service daha low coupling.
    

Serialization Rules

Serialization Rules 

1) Objenin full serializable olmasi icin Obje ve Super obje Serializable 
implemente edecek 
2) Superclass serializable degilse de serialize olur. 
Fakat superClass'in no-arg constructor'u olacak. 
YOksa readObject() de java.io.InvalidClassException alir. 
Bir objenin default olarak no-arg constructor'u vardir, 
fakat o objeye herhangi bir argumanli constructor yazarsaniz, 
no-arg constructor'u ayrica implemente etmeniz gerektigini hatirlatalim. 
3) Serializable olmayan superclass in 
constructor'u deserialization sirasinda calisir. 
4) Butun primitive type ler serializable 
5) transient serialize olmaz. 
6) Static field lar serialize olmaz. 
7) Serializable object'in non serializable objesi varsa compile eder 
ama runtime de hata alir.

Facade Pattern ( Structural )

Facade Pattern ( One Of Structural Patterns ) 1) Simple interface to a larger body of code. Class Library. 2) Wrap a poorly designed collection of APIs with a single well-designed API. 3) Utility Class is a facade. 4) Calling a one function for a set of functions 5) JOptionPane.showMessageDialog() ornek bir facade. AWT ile bir suru sey yazacagina kolay bi sekilde hallediyorsun. Sık kullanılan, ve terzi usulu olmayan bir isi, yani almost her zaman aynı şekilde yapılan bir işi tek fonksiyona indirmek. 6) Facade aslinda bir obje, onu yaratip onun uzerinden is yapiyorsun. Yani bir singleton gibi, yok constructor private olacak, yok getInstance static olacak gibi kurallari yok. Bir mucize aramamak lazim. Zaten herkesin dogal olarak yaptigi utility fonksiyonlarini bir class ta toplarsan, ona facade deniyor. 7) Also Facade is not the only entry point to the sub-system but is a convenient point of communication to the subsystem and client can always have the direct access to the subsystem. 8) Facade ayni zamanda singleton olabilir, birden fazla yaratilmasina gerek yoksa, ama boyle bir sart yok.

Sunday, January 15, 2012

High Cohesion And Low Coupling

High Cohesion : bir objenin alakasız isleri mümkün oldugu kadar az yapmasi Low Coupling : Objelerin birbirine mümkün olduğu kadar az depend olmasi, birbirini daha az referans almasi.

Cross Cutting Concern

Aspect yapilmasini gerektiren durumlardir. Mesela programın core tarafi, core concern dir. Logging, transaction , security gibi kodlamalar bütün sistemi ilgilendirdigi ve her yerde yazilmasi gerektigi icin bunlara cross cutting concern deniyor.

Overriding Static Methods

Taken from http://geekexplains.blogspot.com/2008/06/can-you-override-static-methods-in-java.html
Can you override Static Methods in Java?

Question: Can you override Static Methods in Java?

Answer: Well... the answer is NO if you think from the perspective of how an overriden method should behave in Java. But, you don't get any compiler error if you try to override a static method. That means, if you try to override, Java doesn't stop you doing that; but you certainly don't get the same effect as you get for non-static methods. Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods). Okay... any guesses for the reason why do they behave strangely? Because they are class methods and hence access to them is always resolved during compile time only using the compile time type information. Accessing them using object references is just an extra liberty given by the designers of Java and we should certainly not think of stopping that practice only when they restrict it :-)

Example: let's try to see what happens if we try overriding a static method:-

class SuperClass{
......
public static void staticMethod(){
System.out.println("SuperClass: inside staticMethod");
}
......
}

public class SubClass extends SuperClass{
......
//overriding the static method
public static void staticMethod(){
System.out.println("SubClass: inside staticMethod");
}

......
public static void main(String []args){
......
SuperClass superClassWithSuperCons = new SuperClass();
SuperClass superClassWithSubCons = new SubClass();
SubClass subClassWithSubCons = new SubClass();

superClassWithSuperCons.staticMethod();
superClassWithSubCons.staticMethod();
subClassWithSubCons.staticMethod();
...
}

}

Output:-

SuperClass: inside staticMethod
SuperClass: inside staticMethod
SubClass: inside staticMethod

Notice the second line of the output. Had the staticMethod been overriden this line should have been identical to the third line as we're invoking the 'staticMethod()' on an object of Runtime Type as 'SubClass' and not as 'SuperClass'. This confirms that the static methods are always resolved using their compile time type information only.

For Singleton Pattern

Java Singleton Pattern ( One Of Creational Patterns ) icin: 1) Bir class'in icinde Private Static Object 2) Private Constructor 3) Static get Instance Method of the object 4) Change getInstance Method to synchronized for threadsafe 5) Override clone method of Object, and do throw new CloneNotSupportedException() 6) Optional, making the class final to not override

Tuesday, January 10, 2012

Google Searchbox

Search calismadigi icin, google search koydum. design - add new gadget html/javascript
<form method="get" action="http://www.google.com/search">

<div style="border:1px solid black;padding:4px;width:20em;">
<table border="0" cellpadding="0">
<tr><td>
<input type="text" name="q" size="30" 
 maxlength="270" value="" />
<input type="submit" value="Google Search" /></td></tr>
<tr><td align="center" style="font-size:75%">
<input type="checkbox" name="sitesearch" 
 value="pclives.blogspot.com" checked /> Search Pclives.blogspot.com<br />
</td></tr></table>
</div>

</form>

AOP 2

AOP in Spring

Advice: Method Names
Pointcut: Advice path lere shortcut
JoinPoint: Aspect de called method un ismini verir. Aspect metoduna parametre 
olarak yazilir.

<aop:aspectj-autoproxy /> bunu spring.xml e yazmak lazim.

Spring de member variable update icin advice yazilmaz.
sadece method icin yaziliyor. member variable icin sadece aspectj kullanmak lazim

@Before("execution(public void String getName())")
Bu anotation sadece bu metodlarda calisir.

joinPoint.getTarget() dersen cagiran object i gosterir
joinPoint.toString() dersen cagiran metodu yazar.
joinPoint.getTarget() ile , objeyi cekip islem yapabilirsin

@Before("args(String)")
argument i String olan metodlardan once calistir.

@Before("args(name)")
public void xxAdvice(String name) {

}
Burada name olarak value yu kullanabiliriz. Bunun da String olmasi lazim.

@Before annotation'i, biz explicit olarak metodu cagirdigimiz zaman
calisir. Spring initialize olurken bu metodu cagirdigi zaman calismaz.
( Spring initialize olurken, default value leri set ediyordu ya )

@After
Bu annotation i metoddan sonra calismasi icin yapabilirsin.

@AfterReturning
Bu annotation ile advice sadece return olunca yani exception olmazsa
cagirilir.

@AfterThrowing
Sadece throw olduktan sonra cagirilir.

Aspect class larinin annotation'i @Aspect

@AfterReturning(pointcut="args(name)",returning="returnString")
public void xxadvice(String name,String returnString){

}
return String i almak icin bu annotation i kullanabiliriz.

Advice metodlarina parametre olarak Object verirsek, cast ederek
istedigimiz objeye cevirebiliriz.

@AfterThrowing(pointcut="args(name)",throwing="ex")
public void xxxAdvice(String name, RuntimeException ex)
Bu sekilde ise exception i alabiliriz.

Ayni parametre olarak Object verdiğimiz gibi, throwing olarak Exception
class ini veririsek cast ederek istedigimizi alabiliriz. 

@Around annotation i ile hem before hem after'da calistirabilirsin
advice'i.

@Around("test()")
public void xxAdvice(ProceedingJoinPoint proceedingJoinPoint) {
//before da cagirilacak yer
proceedingJoinPoint.proceed();  //metodun gercekten cagirilmasi
//after da cagirilacak yer.
}
Fakat around yaptigimiz zaman ProceedingJoinPoint kullanmak lazim. Ve bu sart !
Ikisini tek yerde yapabiliriz.

Neden hep @Around hep kullanmiyoruz, hep en kolay olani kullanmak lazim.
Always the least powerful

Eger eger advice olan metod obje donuyorsa, @Around metod da obje donmeli

Tipik conventionlar
pakeler asagidaki gibi:
com.xx  : main
com.xx.aspect : aspectler icin . Class isimleri XXXAspect
com.xx.model : bean ler icin
com.xx.service : servisler icin ( servislerden bean leri cagirma ) . XXXService
Conventionlarimiz olursa gerek class ismi, gerek servis ismi, aspect lerde
pointcut expression yazarken cok kolay olur. Cunku pointcut expression lar
da regular expression gibi. 

expression lari && ile baglayabilirsin
@Before("a" && "b")

Yeni bir annotation yaratirsin. xxxAnnotation
@Around("@annotation(com.xx.xxxAnnotation)")
dersin. Sonra advice istedigin metodun ustune gelip @xxxAnnotation dersin.
Sadece o annotation in bulundugu metodlari cagirir.

Annotation yerine, spring xml in icine de aspect leri tanimlayabiliriz.
<aop:config>
    <aop:aspect id="xx" ref="beanIsmi">
        <aop:pointcut id="allGetters" expression="execution("* get())"/>
        <aop:around method="xxx" pointcut-ref="allGetters"/>
    </aop:aspect> // bu aslinda class'a @Aspect tanimlamak ile ayni
</aop:config>

Aspect Class inin da bean xml icinde tanimlanmis olmasi lazim bunu tabi unutmamak lazim.
annotated ve xml solution icin de. 

Annotation genelde functionality acisindan, XML configuration acisindan tercih edilir.
Mesela transaction tanimlama functionality dir, debug mod ya da degil flag i mesela
xml configuration dir.