7 Ocak 2017 Cumartesi

Spring BeanPostProcessor Sınıfı

Giriş
Spring bu arayüzü gerçekleştiren 28 tane sınıf sunuyor. Dolayısıyla kendi sınıfımızı yazmaya muhtemelen hiçbir zaman gerek olmayacak.

postProcessAfterInitialization metodu
Şöyle yaparız.
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
  throws BeansException {
  ...
  return bean;
}
postProcessBeforeInitialization metodu
Şöyle yaparız.
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
  throws BeansException {
  ...
  return bean;
}

2 Ocak 2017 Pazartesi

DoubleBuffer Sınıfı

Giriş
Buffer sınıfından kalıtır.

constructor
Şöyle yaparız.
byte[] buf = new byte[512];
DoubleBuffer db = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).
                  asDoubleBuffer();
allocate metodu
Şöyle yaparız.
DoubleBuffer db = DoubleBuffer.allocate (5000);
capacity metodu
Şöyle yaparız.
DoubleBuffer db1 = DoubleBuffer.allocate(5000);
DoubleBuffer db2 = DoubleBuffer.allocate(db1.capacity());
clear metodu
Şöyle yaparız.
db.clear();
get metodu
Şöyle yaparız.
DatagramSocket socket = new DatagramSocket(25000);
byte[] buf = new byte[512];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
DoubleBuffer db = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).
                  asDoubleBuffer();

while (true) {
  socket.receive(packet);
  db.limit(packet.getLength() / Double.BYTES);
  double x = db.get(0);
  System.out.println(x);
}
limit metodu
Şöyle yaparız.
db.limit(10);
put metodu
Şöyle yaparız.
DoubleBuffer db1 = ...;
DoubleBuffer db2 = ...;
db2.put (db1);

1 Ocak 2017 Pazar

Closeable Arayüzü

Giriş
Java 5'ten beri mevcut. Bu arayüz ile kaynaklar try bloğu içinde kullanılabiliyor.

close metodu
Kendimiz tanımlamak istersek şöyle yaparız.
ExecutorService service = Executors.newSingleThreadExecutor();
try (Closeable close = service::shutdown) {

}

Javadoc Tagleri

Giriş
Javadoc tag'leri @ karakteri ile başar. Açıklaması şöyle
@author: You can define who created this class, package, or method

@since: specify when a feature or method was added

@version: the current version

@param: given a method or a constructor, the argument information

@return: given a method a description about what is returning

@throws: what can go wrong on this call? It is a tag to explain it so the user can avoid it. 

@see: to get more information on another method.

{@code ...}
Şöyle yaparız. Javadoc içinde java kodu yazabilmeyi sağlar
/**
 * ...
 * <pre>{@code
 *   ...
 * }</pre>
 */
{@link ...}
Hyperlink şeklinde diğer sınıfa bağlantı verir. @link'ten sonra gelen ilk kelime sınıf ismini, ikinci kelime ise Javadoc'ta görünecek kelimeyi belirtir. Sınıfın içindeki bir alana atıfta bulunmak için # karakter kullanılır. Mesela com.foo.Bar#field1

Atıfta bulunmak istediğimiz sınıf veya metod public olmalıdır.  Eğer public değilse @see kullanılabilir.

Örnek - Metoda Atıf
Şöyle yaparız
@deprecated please use {@link Team#of(String)} instead veya @return a {@link Team} instance
Örnek - Sınıfa Atıf
Şöyle yaparız. 
/**
 * Returns an {@link Identity Identity(s)} ...
 */
{@see ...}
Örnek
Şöyle yaparız. Burada atıfta bulunulan metod private olsa bile hatalı değil.
/**
 * This class represents a dog.
 *
 * @see Dog#bark()
 */
public class Dog {

  private void bark() {
    System.out.println("Woof!");
  }
}


ZoneOffset Sınıfı

Giriş
Açıklaması şöyle
Stores offset in hours and minutes from Greenwich. Stores seconds in range -18:00 ile +18:00
ZoneId sınıfından kalıtır.

constructor
Örnek - ZonedDateTime
Şöyle yaparız.
ZonedDateTime zdt = ...;
ZoneOffset offset = zdt.getOffset ();
UTC alanı
Şöyle yaparız.
ZoneId z = ZoneOffset.UTC;
getLong metodu
Örnek
getLong() sonucundaki offset değerini saat ve dakikaya çevirmek için şöyle yaparız
ZonedDateTime zdt = ...
ZoneOffset zoneOffset = zdt.getOffset();
long offsetLong = zoneOffset.getLong(ChronoField.OFFSET_SECONDS);

Duration duration = Duration.ofSeconds(offsetLong);

long hours = duration.toHours();
long minutes = duration.toMinutes() % 60;

TemporalAdjusters Sınıfı

Giriş
Tarihleri ileri geri oynatmak için kullanılırlar.

firstDayOfMonth metodu
Şöyle yaparız. Önce başlangıç tarihini ay başına alırız. Daha sonra iki tarih arasındaki pazar günlerini sayarız.
LocalDate start = ..., end = ...;

for (LocalDate date = start.with(TemporalAdjusters.firstDayOfMonth()); !date.isAfter(end);
date = date .plusMonths(1)) { if (date.getDayOfWeek() == DayOfWeek.SUNDAY) { count++; } }
lastDayOfMonth metodu
Örnek ver

lastInMonth metodu
Ayın son perşembesi şöyle bulunur. Önce şu satırları dahil ederiz.
import static java.time.DayOfWeek.THURSDAY;
import static java.time.temporal.TemporalAdjusters.lastInMonth;
Sonra şöyle yaparız.
int month = 12;
int year = 2015;
LocalDate lastThursday = LocalDate.of(year, month, 1).with(lastInMonth(THURSDAY));
System.out.println("lastThursday = " + lastThursday); //prints 2015-12-31
next metodu
Örnek ver

Clock Sınıfı

Giriş
Şu satırı dahil ederiz
import java.time.Clock;
Soyut bir sınıftır. Açıklaması şöyle
to allow alternate clocks to be plugged in as and when required
Kullanım
1. fixed(), systemDefaultZone(), systemUTC() metodlarından birisi çağrılarak bir Clock elde edilir ve bu nesnenin instant() metodu çağrılır
2. fixed(), systemDefaultZone(), systemUTC() metodlarından birisi çağrılarak bir Clock elde edilir ve bu nesne Insant.now() metoduna geçilir.

Örnek
Şöyle yaparız
import java.time.Clock;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;

public class ExpiringValue<T> {
  private final T value;

  private final Instant expiresAt;

  private final Clock clock;

  public ExpiringValue(T value, Instant expiresAt) {
    this(value, expiresAt, Clock.systemDefaultZone());
  }

  public ExpiringValue(T value, Instant expiresAt, Clock clock) {
    this.value = Objects.requireNonNull(value);
    this.expiresAt = Objects.requireNonNull(expiresAt);
    this.clock = Objects.requireNonNull(clock);
  }

  public Optional<T> get() {
    return isExpired() ? Optional.empty() : Optional.ofNullable(value);
  }

  private boolean isExpired() {
    return !Instant.now(clock).isBefore(expiresAt);
  }
}
fixed metodu
Şöyle yaparız.
Clock clk = Clock.fixed( 
  Instant.parse( "2016-01-23T12:34:56Z" , ZoneOffset.UTC )
);
instant metodu
Şöyle yaparız.
Instant now = Clock.systemUTC().instant();
systemDefaultZone metodu
Şöyle yaparız.
Clock clk = Clock.systemDefaultZone ();
system metodu
Şöyle yaparız.
Instant now = Instant.now ( Clock.systemUTC () );
Instant now = Instant.now ( Clock.system ( ZoneId.of ( "America/Montreal" ) ) );
Instant now = Instant.now ( Clock.systemDefaultZone () );
systemUTC metodu

Şöyle yaparız.
Clock clk =  Clock.systemUTC();