29 Aralık 2022 Perşembe

sun.misc.Unsafe Sınıfı

Açıklaması şöyle
2.2. Unsafe API
The Unsafe API is extremely efficient due to its addressing model. However, as the name suggests, this API is unsafe and has several drawbacks:

- It often allows the Java programs to crash the JVM due to illegal memory usage
- It's a non-standard Java API
constuctor
Örnek
Şöyle yaparız
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
allocateInstance metodu
Nesne için sadece bellek ayırır ve constructor'ı çağırmaz.
Örnek
Şöyle yaparız
class InitializationOrdering {
  private long a;

  public InitializationOrdering() {
    this.a = 1;
  }

  public long getA() {
    return this.a;
  }
}

InitializationOrdering o3 
  = (InitializationOrdering) unsafe.allocateInstance(InitializationOrdering.class);
 
assertEquals(o3.getA(), 0);
defineAnonymousClass metodu
Java 15 ile Bunun yerine artık Hidden Classes kullanılıyor

getLong metodu
Örnek
Şöyle yaparız
public class Foo {

  private static final long OFFSET_value;
  private static final Unsafe UNSAFE = UnsafeLocator.UNSAFE;

  static {
    try {
      OFFSET_value = getOffset("value");
    } catch (ReflectiveOperationException e) {
      ...
    }
  }

  private static long getOffset(String fieldName) throws NoSuchFieldException {
    Field field = Foo.class.getDeclaredField(fieldName);
    return UnsafeLocator.UNSAFE.objectFieldOffset(field);
  }

  public volatile long value;

  public long unsafe() {
    return UNSAFE.getLong(this, OFFSET_value);
  }
}




AWS CDK - Cloud Development Kit

Giriş
Açıklaması şöyle
The AWS CDK is an open-source software development framework to model and provision cloud application resources through AWS CloudFormation, programmatically with languages like Typescript, Javascript, Go, Python, C#, and Java.
Aslında bu AWS CDK ile altta Java kodu ile CloudFormation Template formatında yaml dosyası oluşturuluyor.

Kavramlar
Açıklaması şöyle
L1 Construct
Represent all resources available in AWS CloudFormation. These constructs start with the prefix Cfn. For example, CfnDBInstance represents the AWS::RDS::DBInstance

L2 Construct
Also, represent all resources available in AWS CloudFormation, but at a high level. Offer convenients defaults and reduce the need to know all details about the AWS resource. For example, Topic.Builder.create represent the creation of topic in AWS.

L3 Construct
These constructs are to help you to complete tasks that involve multiple resources in AWS. For example, The LambdaRestApi construct represents an Amazon API Gateway API that’s backed by an AWS Lambda function.

Stacks
Is the unit of deployment. All AWS resources are defined within a stack.

We can define a lot of stack numbers in we AWS CDK app.

Apps
An app is a container for one o more stacks, its serve as stack’s scope.
Bir örnek burada

Maven
Şu satırı dahil ederiz
<properties>
  <cdk.version>2.51.1</cdk.version>
  <constructs.version>[10.0.0,11.0.0)</constructs.version>
  <aws.java.sdk.version>2.16.1</aws.java.sdk.version>
</properties>

<dependencies>
  <dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>aws-sdk-java</artifactId>
    <version>${aws.java.sdk.version}</version>
  </dependency>

  <!-- AWS Cloud Development Kit -->
  <dependency>
    <groupId>software.amazon.awscdk</groupId>
    <artifactId>aws-cdk-lib</artifactId>
    <version>${cdk.version}</version>
 </dependency>

 <dependency>
   <groupId>software.constructs</groupId>
   <artifactId>constructs</artifactId>
   <version>${constructs.version}</version>
 </dependency>

</dependencies>

















27 Aralık 2022 Salı

Tomcat server.xml Connector

Giriş
Açıklaması şöyle. Temel olarak iki Connector tipi var. "Http Connector" ve "AJP Connector"
This represents an endpoint by which requests are received and responses are returned.
Açıklaması şöyle
The connector is responsible for handling client connections, and it provides support for various service protocols, including BIO, NIO, AIO, etc. The value of its existence lies in shielding the complexity of multi-protocol Containers and unifying the processing standards of Containers.
Açıklaması şöyle.
Tomcat can work in 2 modes:

BIO (one thread per connection), or NIO (many more connections than threads).

Tomcat7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the "protocol" parameter in the server.xml file - BIO will be "HTTP1.1" or "org.apache.coyote.http11.Http11Protocol" and NIO will be "org.apache.coyote.http11.Http11NioProtocol"
Connector - APR (Apache Portable Runtime)
Şöyle yaparız.
<Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
               maxThreads="150"
               SSLEnabled="true"
               scheme="https"
               compression="off"
               connectionTimeout="1190"
               address="0.0.0.0"
               >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
        <SSLHostConfig>
            <Certificate certificateKeyFile="/etc/ssl/certs/private.key"
                         certificateFile="/etc/ssl/certs/public.pem"
                          />
        </SSLHostConfig>
</Connector>
http2 kullanmak için şöyle yaparız.
<Connector port="443" protocol="org.apache.coyote.http11.Http11AprProtocol"
  maxThreads="150" SSLEnabled="true" 
  compressableMimeType="text/html,text/xml,text/plain,text/css,text/javascript,
  application/javascript,application/json" compression="on" compressionMinSize="1024"
>
  <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
  <SSLHostConfig>
    <Certificate certificateKeyFile="conf/localhost-key.pem"
      certificateFile="conf/localhost-cert.pem"
      certificateChainFile="conf/cacert.pem"
      type="RSA" />
  </SSLHostConfig>
</Connector>
Connector - AJP
Cluster şeklinde kullanmak için şöyle yaparız.
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
Örnek
Şöyle yaparız.
<Connector port="8012" protocol="AJP/1.3" redirectPort="8446"
  connectionTimeout="10000" keepAliveTimeout="10000" />
httpd'ye şöyle yaparız.
vi /etc/httpd/conf.d/mydomain.com.conf

<VirtualHost www.mydomain.com:80>
    ServerName www.mydomain.com
    ServerAlias mydomain.com
    ErrorLog /var/log/httpd/mydomain_com_error.log
    CustomLog /var/log/httpd/mydomain_com_requests.log combined
    ProxyPass / ajp://my.public.ip.addr:8012/
    ProxyPassReverse / ajp://my.public.ip.addr:8012/
</VirtualHost>
Connector - connectionTimeout
Açıklaması şöyle.
This will be used to set the number of milliseconds for the Connector to wait, after accepting a connection, for the request URI lines to be presented. Use a value of -1 to indicate no timeout. The default value for this attribute is 60000 (60 seconds), but when we install Tomcat, Tomcat sets this to 20000 (20 seconds).
Şöyle yaparız.
<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" 
       URIEncoding="UTF-8"/>
Connector - keystore
server.xml HTTPS yazısına taşıdım.

Connector - maxConnections
Açıklaması şöyle. NIO için varsayılan değer 10,000
The maximum number of connections that the server will accept and process at any given time. When this number has been reached, the server will accept, but not process, one further connection. This additional connection be blocked until the number of connections being processed falls below maxConnections at which point the server will start accepting and processing new connections again. Note that once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. The default value varies by connector type. For BIO the default is the value of maxThreads unless an Executor is used in which case the default will be the value of maxThreads from the executor. For NIO the default is 10000. For APR/native, the default is 8192.
Note that for APR/native on Windows, the configured value will be reduced to the highest multiple of 1024 that is less than or equal to maxConnections. This is done for performance reasons. If set to a value of -1, the maxConnections feature is disabled and connections are not counted.
Connector - maxHttpHeaderSize
Şöyle yaparız
<Connector port="8443" 
  maxHttpHeaderSize="8192" 
  maxThreads="150" 
  minSpareThreads="25" 
  maxSpareThreads="75" 
  enableLookups="false" 
  disableUploadTimeout="true" 
  acceptCount="100" 
  scheme="https" 
  secure="true" 
  SSLEnabled="true" 
  clientAuth="true" 
  sslProtocol="SSL/TLS" 
  keystoreFile="C:/EBCM_Client_TEST.pfx"
  keystorePass="allianzebcm"
  keystoreType="PKCS12"/>
Connector - maxThreads
Açıklaması şöyle.
Each incoming request requires a thread for the duration of that request. If more simultaneous requests are received than can be handled by the currently available request processing threads, additional threads will be created up to the configured maximum (the value of the maxThreads attribute). If still more simultaneous requests are received, they are stacked up inside the server socket created by the Connector, up to the configured maximum (the value of the acceptCount attribute). Any further simultaneous requests will receive "connection refused" errors, until resources are available to process them.
Açıklaması şöyle.
If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.
NIO modda kaç thread kullanmak istediğimizi belirtmek için şöyle yaparız.
<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
       maxThreads="250" SSLEnabled="true" scheme="https" secure="true"
       clientAuth="false" sslProtocol="TLS" connectiontimeout="20000"/>
Connector - port
Açıklaması şöyle.
The TCP port number on which this Connector will create a server socket and await incoming connections (OS will allow only one server application to listen to a particular port number on a particular IP address). The default value in case of non-SSL is 8080 and, in case of SSL, it's 8443.
Örnek
Şöyle yaparız. port 80 yerine 8080 yapılabilir.
<Connector port="8080" maxHttpHeaderSize="8192"
  maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
  enableLookups="false" redirectPort="8443" acceptCount="100"
  connectionTimeout="20000" disableUploadTimeout="true"
  URIEncoding="UTF-8"
/>
Connector - protocol
Açıklaması şöyle.
This will be used to set the protocol to handle incoming traffic. The default value is HTTP/1.1, which uses an auto-switching mechanism to select either a Java NIO-based connector or an APR/native-based connector.
Şu değerleri alır
-org.apache.coyote.http11.Http11Protocol (BIO)
-org.apache.coyote.http11.Http11NioProtocol (NIO)
-org.apache.coyote.http11.Http11AprProtocol
-AJP/1.3
-HTTP/1.1

Connector - redirectPort
Açıklaması şöyle.
If the Connector is supporting non-SSL requests, and a request is received which requires an SSL transport, Catalina will automatically redirect the request to the port number specified here.
Niçin redirect kullanırız sorusunun cevabı şöyle. Http'den Https'e yönlendirmek için kullanılabilir.
For usability reasons you need to offer a redirect to HTTPS from all HTTP URL:s. Otherwise first time visitors who simply enter example.com/some/page into the URL bar of the browser will be greeted by a connection error.
Bazı siteler HSTS header kullanıyor. Bu header ile browser'da HTTPS Everywhere varsa kendiliğinden http'den https'e istek gönderiyor. Yani redirect'e gerek kalmıyor.

HTTPS Everywhere'in açıklaması şöyle
HTTPS Everywhere is client-side, and HSTS is server-side.
Şöyle yaparız.
<Connector port="80" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />
Connector - scheme
Açıklaması şöyle.
Set this attribute to the name of the protocol you wish to have returned by calls. The default value is "HTTP."
Şöyle yaparız.
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
  maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
  clientAuth="false" sslProtocol="TLS" />
Connector - SSLCertificateFile
Şöyle yaparız.
<Connector 
   port="8443" maxThreads="200"
   scheme="https" secure="true" SSLEnabled="true"
   SSLCertificateFile="/usr/local/ssl/server.crt" 
   SSLCertificateKeyFile="/usr/local/ssl/server.pem"
   clientAuth="optional" SSLProtocol="TLSv1.2"/>
Connector - URIEncoding
Açıklaması şöyle.
This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL; if nothing is specified, UTF-8 will be used.
Http Get isteğinde HttpServletRequest sınıfı Http standardında belirtildiği gibi gönderilen parametreleri Latin 1 olarak string'e çevirir. Eğer UTF-8 olarak çevirsin istersek bunu URIEncoding ile belirtiriz.
Örnek
Şöyle yaparız.
<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" 
       URIEncoding="UTF-8"/>