11 Mayıs 2021 Salı

NTPUDPClient Sınıfı

Giriş
Şu satırı dahil ederiz
<dependency>
  <groupId>commons-net</groupId>
  <artifactId>commons-net</artifactId>
  <version>3.8.0</version>
</dependency>
Windows 10 ile NTP sunucusunu bulmak için şöyle  yaparız
w32tm /query /peers
Örnek 
Şöyle yaparız
NTPUDPClient ntpudpClient = new NTPUDPClient();
ntpudpClient.setDefaultTimeout(5000);

try {
  InetAddress inetAddress = InetAddress.getByName("192.168.43.32");
  TimeInfo timeInfo = ntpudpClient.getTime(inetAddress);

  TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
  Date date = timeStamp.getDate();
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
  simpleDateFormat.format(date);
} catch (UnknownHostException e) {
 ...
}
ntpudpClient.close();
TimeInfo ile şöyle yaparız
timeInfo.computeDetails();
if (timeInfo.getOffset() != null) {
  this.timeInfo = timeInfo;
  this.offset = timeInfo.getOffset();
}

// This system NTP time
TimeStamp systemNtpTime = TimeStamp.getCurrentTime();
System.out.println("System time:\t" + systemNtpTime + " " + systemNtpTime.toDateString());

// Calculate the remote server NTP time
long currentTime = System.currentTimeMillis();
TimeStamp atomicNtpTime = TimeStamp.getNtpTime(currentTime + offset).getTime()

System.out.println("Atomic time:\t" + atomicNtpTime + " " + atomicNtpTime.toDateString());
TimeInfo ile şöyle yaparız
TimeInfo info = client.getTime(hostAddr);
info.computeDetails(); // compute offset/delay if not already done
Long offsetValue = info.getOffset();
Long delayValue = info.getDelay();
String delay = (delayValue == null) ? "N/A" : delayValue.toString();
String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();

System.out.println(" Roundtrip delay(ms)=" + delay
                + ", clock offset(ms)=" + offset); // offset in ms

20 Nisan 2021 Salı

CLI HelpFormatter Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.apache.commons.cli.HelpFormatter;

printHelp metodu
Bu metodun overload edilmiş bir sürü hali var. Overload edilen parametrelerin sayısı gittikçe artıyor. Her yeni parametre bir sonraki satıra yazılıyor gibi düşünülebilir.

Parametreler şöyle

- String cmdLineSyntax
- String header
- Options
- String footer
- boolean autoUsage

autoUsage true ise şöyle bir çıktı alırız
usage : myapp -myarf <arg>
 -myarg <arg>   - myexplanation for arg
autoUsage false ise şöyle bir çıktı alırız. Yani sadece ilk satır değişiyor.
usage : myapp
 -myarg <arg>   - myexplanation for arg
header ve footer verirsek ve autoUsage true şöyle bir çıktı alırız
usage : myapp -myarf <arg>
header
 -myarg <arg>   - myexplanation for arg
footer
Ayrıca setWidth() ile satır genişliği atanabilir.

Örnek 
Benim kullandıklarımdan birisi şöyle. İlk parametrede "command line syntax" belirtiliyor. hssi ve 9028 parametrelerinin mecburi olduğu da belirtiliyor. İkinci parametre olarak options ve üçüncü parametre olarak true geçerek geriye kalan isteğe bağlı seçenekleri de yazdırıyorum
Options options = ...;
helpFormatter.printHelp("java -jar foo.jar hssi 9028", options, true)
Örnek  - cmdLineSyntax + header + options + footer + autoUsage
Benim kullandıklarımdan birisi şöyle
Options options = ...;
String footer = "component1,component2"
helpFormatter.printHelp("myapp", "Starts my app", options, componentNames ,true);
Çıktı olarak şunu alırız
usage : myapp -blah <arg>
Starts my app
  -blah <arg> - my explanation
component1,component2

17 Nisan 2021 Cumartesi

Digest Crypt Sınıfı

crypto metodu- key
Açıklaması şöyle
Simply use crypto(String key) instead as it already provides random salt.
Örnek
Şöyle yaparız
String hashedPassword = Crypt.crypt(user.getPassword());
crypto metodu - key + salt
Açıklaması şöyle. Mesela SHA-512 kullanılacaksa salt string'i $6$ ile başlar.
The exact algorithm depends on the format of the salt string
Örnek
Şöyle yaparız
String saltBytes = ... ;
String salt = "$6$" + saltBytes;
String hashedPassword = Crypt.crypt(user.getPassword(), salt);

DescriptiveStatistics Sınıfı

Giriş
Şu satırı dahil ederiz
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
Bu sınıfın benzeri SynchronizedDescriptiveStatistics sınıfı da var.

28 Şubat 2021 Pazar

Camel TimerComponent Sınıfı

Örnek
Şöyle yaparız
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

@Component
public class RestAPIClientRoute extends RouteBuilder {
  @Override
  public void configure() throws Exception {
    restConfiguration().host("dummy.restapiexample.com").port(80);
    
    from("timer:rest-client?period=10s")
      .to("rest:get:/api/v1/employees")
      .log("${body}");
  }
}

25 Şubat 2021 Perşembe

Camel Processors Kavramı

Giriş
Açıklaması şöyle
Processors handles things in between endpoints like routing, transformation, validation, enrichment, etc. 
Örnek
Şu satırı dahil ederiz
<dependency>
  <groupId>org.apache.camel.springboot</groupId>
  <artifactId>camel-activemq-starter</artifactId>
  <version>3.8.0</version>
</dependency>
<dependency>
  <groupId>org.apache.camel.springboot</groupId>
  <artifactId>camel-jackson-starter</artifactId>
  <version>3.8.0</version>
</dependency>
Elimizde ActiveMQ'dan okuyup processor'a gönderen şöyle bir kod olsun. Burada Processor olan GetEmployee .bean() metodu ile belirtiliyor. GetEmployee sınıfının tek metodu olduğu için hangi metodunun çağrılacağını belirtmeye gerek yok.
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.dataformat.JsonLibrary; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class ActiveMQReceiverRoute extends RouteBuilder { @Autowired GetEmployee getEmployee; @Override public void configure() throws Exception { from("activemq:myqueue") .unmarshal().json(JsonLibrary.Jackson, Employee.class) .bean(getEmployee) .to("log:myloggingqueue"); } } @Component class GetEmployee{ Logger logger= LoggerFactory.getLogger(GetEmployee.class); public void getData(Employee employee){ logger.info("Emp data: "+employee.getId()); } }

17 Şubat 2021 Çarşamba

UnicodeUnescaper Sınıfı

Giriş
Şu satırı dahil ederiz
import org.apache.commons.text.translate.UnicodeUnescaper;
translate metodu
Şöyle yaparız
public class HTMLEncoder extends Common {

  public static String encode(String source) {
    String escaped = StringEscapeUtils.escapeJava(source);
    String utfChars = new UnicodeUnescaper().translate(escaped);
    return utfChars; 
  }
}