mirror of
https://github.com/affaan-m/everything-claude-code.git
synced 2026-06-13 03:33:15 +08:00
translate properly docs/
This commit is contained in:
@@ -4,26 +4,24 @@ description: Quarkus 3.x LTS architecture patterns with Camel for messaging, RES
|
||||
origin: ECC
|
||||
---
|
||||
|
||||
> **Not / Note**: Bu dosya henuz Turkceye cevrilmemistir, su anda Ingilizce orijinaldir. Ceviri PR'lari memnuniyetle karsilanir.
|
||||
# Quarkus Geliştirme Desenleri
|
||||
|
||||
# Quarkus Development Patterns
|
||||
Apache Camel ile bulut-native, event-driven servisler için Quarkus 3.x mimari ve API desenleri.
|
||||
|
||||
Quarkus 3.x architecture and API patterns for cloud-native, event-driven services with Apache Camel.
|
||||
## Ne Zaman Aktif Edilir
|
||||
|
||||
## When to Activate
|
||||
- JAX-RS veya RESTEasy Reactive ile REST API'leri oluşturma
|
||||
- Resource → service → repository katmanlarını yapılandırma
|
||||
- Apache Camel ve RabbitMQ ile event-driven desenler uygulama
|
||||
- Hibernate Panache, caching veya reaktif akışları yapılandırma
|
||||
- Validation, exception mapping veya sayfalama ekleme
|
||||
- Dev/staging/production ortamları için profiller kurma (YAML yapılandırma)
|
||||
- LogContext ve Logback/Logstash encoder ile özel loglama
|
||||
- Async işlemler için CompletableFuture ile çalışma
|
||||
- Koşullu akış işleme uygulama
|
||||
- GraalVM native derleme ile çalışma
|
||||
|
||||
- Building REST APIs with JAX-RS or RESTEasy Reactive
|
||||
- Structuring resource → service → repository layers
|
||||
- Implementing event-driven patterns with Apache Camel and RabbitMQ
|
||||
- Configuring Hibernate Panache, caching, or reactive streams
|
||||
- Adding validation, exception mapping, or pagination
|
||||
- Setting up profiles for dev/staging/production environments (YAML config)
|
||||
- Custom logging with LogContext and Logback/Logstash encoder
|
||||
- Working with CompletableFuture for async operations
|
||||
- Implementing conditional flow processing
|
||||
- Working with GraalVM native compilation
|
||||
|
||||
## Service Layer with Multiple Dependencies (Lombok)
|
||||
## Birden Fazla Bağımlılıklı Service Katmanı (Lombok)
|
||||
|
||||
```java
|
||||
@Slf4j
|
||||
@@ -43,7 +41,7 @@ public class As2ProcessingService {
|
||||
|
||||
String structureIdPartner = logContext.get(As2Constants.STRUCTURE_ID);
|
||||
|
||||
// Conditional flow logic
|
||||
// Koşullu akış mantığı
|
||||
boolean isChorusFlow = Boolean.parseBoolean(logContext.get(As2Constants.CHORUS_FLOW));
|
||||
log.info("Is CHORUS_FLOW message: {}", isChorusFlow);
|
||||
|
||||
@@ -62,7 +60,7 @@ public class As2ProcessingService {
|
||||
|
||||
log.info("Invoice validation completed. Message is valid");
|
||||
|
||||
// CompletableFuture async operation
|
||||
// CompletableFuture async işlemi
|
||||
try(InputStream inputStream = Files.newInputStream(filePath)) {
|
||||
CompletableFuture<StoredDocumentInfo> documentInfoCompletableFuture =
|
||||
fileStorageService.uploadOriginalFile(inputStream,
|
||||
@@ -85,7 +83,7 @@ public class As2ProcessingService {
|
||||
documentInfo, originalFileName, structureIdPartner,
|
||||
flowProfile, invoiceValidationResult.getDocumentHash());
|
||||
|
||||
// Async Camel publishing
|
||||
// Async Camel yayınlama
|
||||
businessRulesPublisher.publishAsync(payload);
|
||||
this.eventService.createSuccessEvent(payload, "BUSINESS_RULES_MESSAGE_SENT");
|
||||
}
|
||||
@@ -94,16 +92,16 @@ public class As2ProcessingService {
|
||||
}
|
||||
```
|
||||
|
||||
**Key Patterns:**
|
||||
- `@RequiredArgsConstructor` for constructor injection via Lombok
|
||||
- `@Slf4j` for Logback logging
|
||||
- Scoped LogContext with try-with-resources
|
||||
- Conditional flow logic based on runtime parameters
|
||||
- CompletableFuture with `.join()` for async operations
|
||||
- Event tracking for success/error scenarios
|
||||
- Async Camel message publishing
|
||||
**Temel Desenler:**
|
||||
- Constructor injection için Lombok üzerinden `@RequiredArgsConstructor`
|
||||
- Logback loglama için `@Slf4j`
|
||||
- try-with-resources ile kapsamlı LogContext
|
||||
- Runtime parametrelerine dayalı koşullu akış mantığı
|
||||
- Async işlemler için `.join()` ile CompletableFuture
|
||||
- Başarı/hata senaryoları için event takibi
|
||||
- Async Camel mesaj yayınlama
|
||||
|
||||
## Custom Logging Context Pattern (Logback)
|
||||
## Özel Loglama Bağlamı Deseni (Logback)
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -112,14 +110,14 @@ public class ProcessingService {
|
||||
public void processDocument(Document doc) {
|
||||
LogContext logContext = CustomLog.getCurrentContext();
|
||||
try (SafeAutoCloseable ignored = CustomLog.startScope(logContext)) {
|
||||
// Add context to all log statements
|
||||
// Tüm log ifadelerine bağlam ekle
|
||||
logContext.put("documentId", doc.getId().toString());
|
||||
logContext.put("documentType", doc.getType());
|
||||
logContext.put("userId", SecurityContext.getUserId());
|
||||
|
||||
log.info("Starting document processing");
|
||||
|
||||
// All logs within this scope inherit the context
|
||||
// Bu kapsam içindeki tüm loglar bağlamı devralır
|
||||
processInternal(doc);
|
||||
|
||||
log.info("Document processing completed");
|
||||
@@ -131,7 +129,7 @@ public class ProcessingService {
|
||||
}
|
||||
```
|
||||
|
||||
**Logback Configuration (logback.xml):**
|
||||
**Logback Yapılandırması (logback.xml):**
|
||||
|
||||
```xml
|
||||
<configuration>
|
||||
@@ -149,7 +147,7 @@ public class ProcessingService {
|
||||
</configuration>
|
||||
```
|
||||
|
||||
## Event Service Pattern
|
||||
## Event Service Deseni
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -181,13 +179,13 @@ public class EventService {
|
||||
}
|
||||
|
||||
private String serializePayload(Object payload) {
|
||||
// JSON serialization
|
||||
// JSON serileştirme
|
||||
return objectMapper.writeValueAsString(payload);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Camel Message Publishing (RabbitMQ)
|
||||
## Camel Mesaj Yayınlama (RabbitMQ)
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -215,7 +213,7 @@ public class BusinessRulesPublisher {
|
||||
}
|
||||
```
|
||||
|
||||
**Camel Route Configuration:**
|
||||
**Camel Route Yapılandırması:**
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -242,7 +240,7 @@ public class BusinessRulesRoute extends RouteBuilder {
|
||||
}
|
||||
```
|
||||
|
||||
## Camel Direct Routes (In-Memory)
|
||||
## Camel Direct Route'ları (Bellek İçi)
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -250,13 +248,13 @@ public class DocumentProcessingRoute extends RouteBuilder {
|
||||
|
||||
@Override
|
||||
public void configure() {
|
||||
// Error handling
|
||||
// Hata yönetimi
|
||||
onException(ValidationException.class)
|
||||
.handled(true)
|
||||
.to("direct:validation-error-handler")
|
||||
.log("Validation error: ${exception.message}");
|
||||
|
||||
// Main processing route
|
||||
// Ana işleme route'u
|
||||
from("direct:process-document")
|
||||
.routeId("document-processing")
|
||||
.log("Processing document: ${header.documentId}")
|
||||
@@ -278,7 +276,7 @@ public class DocumentProcessingRoute extends RouteBuilder {
|
||||
}
|
||||
```
|
||||
|
||||
## Camel File Processing
|
||||
## Camel Dosya İşleme
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -308,7 +306,7 @@ public class FileMonitoringRoute extends RouteBuilder {
|
||||
}
|
||||
```
|
||||
|
||||
## Camel Bean Invocation
|
||||
## Camel Bean Çağrısı
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -328,7 +326,7 @@ public class InvoiceRoute extends RouteBuilder {
|
||||
}
|
||||
```
|
||||
|
||||
## REST API Structure
|
||||
## REST API Yapısı
|
||||
|
||||
```java
|
||||
@Path("/api/documents")
|
||||
@@ -367,7 +365,7 @@ public class DocumentResource {
|
||||
}
|
||||
```
|
||||
|
||||
## Repository Pattern (Panache Repository)
|
||||
## Repository Deseni (Panache Repository)
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -389,7 +387,7 @@ public class DocumentRepository implements PanacheRepository<Document> {
|
||||
}
|
||||
```
|
||||
|
||||
## Service Layer with Transactions
|
||||
## Transaction'lı Service Katmanı
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -425,7 +423,7 @@ public class DocumentService {
|
||||
}
|
||||
```
|
||||
|
||||
## DTOs and Validation
|
||||
## DTO'lar ve Validation
|
||||
|
||||
```java
|
||||
public record CreateDocumentRequest(
|
||||
@@ -442,7 +440,7 @@ public record DocumentResponse(Long id, String referenceNumber, DocumentStatus s
|
||||
}
|
||||
```
|
||||
|
||||
## Exception Mapping
|
||||
## Exception Eşleme
|
||||
|
||||
```java
|
||||
@Provider
|
||||
@@ -473,7 +471,7 @@ public class GenericExceptionMapper implements ExceptionMapper<Exception> {
|
||||
}
|
||||
```
|
||||
|
||||
## CompletableFuture Async Operations
|
||||
## CompletableFuture Async İşlemleri
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -533,10 +531,10 @@ public class DocumentCacheService {
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration as YAML
|
||||
## YAML Yapılandırması
|
||||
|
||||
```yaml
|
||||
# application.yml
|
||||
# application.yml (uygulama yapılandırması)
|
||||
"%dev":
|
||||
quarkus:
|
||||
datasource:
|
||||
@@ -580,7 +578,7 @@ public class DocumentCacheService {
|
||||
username: ${RABBITMQ_USER}
|
||||
password: ${RABBITMQ_PASSWORD}
|
||||
|
||||
# Camel configuration
|
||||
# Camel yapılandırması
|
||||
camel:
|
||||
rabbitmq:
|
||||
queue:
|
||||
@@ -588,7 +586,7 @@ camel:
|
||||
invoice-processing: invoice-processing-queue
|
||||
```
|
||||
|
||||
## Health Checks
|
||||
## Sağlık Kontrolleri
|
||||
|
||||
```java
|
||||
@Readiness
|
||||
@@ -626,7 +624,7 @@ public class CamelHealthCheck implements HealthCheck {
|
||||
}
|
||||
```
|
||||
|
||||
## Dependencies (Maven)
|
||||
## Bağımlılıklar (Maven)
|
||||
|
||||
```xml
|
||||
<properties>
|
||||
@@ -657,7 +655,7 @@ public class CamelHealthCheck implements HealthCheck {
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<!-- Quarkus Core -->
|
||||
<!-- Quarkus Çekirdek -->
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-arc</artifactId>
|
||||
@@ -667,7 +665,7 @@ public class CamelHealthCheck implements HealthCheck {
|
||||
<artifactId>quarkus-config-yaml</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Camel Extensions -->
|
||||
<!-- Camel Uzantıları -->
|
||||
<dependency>
|
||||
<groupId>org.apache.camel.quarkus</groupId>
|
||||
<artifactId>camel-quarkus-spring-rabbitmq</artifactId>
|
||||
@@ -689,7 +687,7 @@ public class CamelHealthCheck implements HealthCheck {
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Logging -->
|
||||
<!-- Loglama -->
|
||||
<dependency>
|
||||
<groupId>io.quarkiverse.logging.logback</groupId>
|
||||
<artifactId>quarkus-logging-logback</artifactId>
|
||||
@@ -701,56 +699,56 @@ public class CamelHealthCheck implements HealthCheck {
|
||||
</dependencies>
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
## En İyi Uygulamalar
|
||||
|
||||
### Architecture
|
||||
- Use `@RequiredArgsConstructor` with Lombok for constructor injection
|
||||
- Keep service layer thin; delegate complex logic to specialized classes
|
||||
- Use Camel routes for message routing and integration patterns
|
||||
- Prefer Panache Repository pattern for data access
|
||||
### Mimari
|
||||
- Constructor injection için Lombok üzerinden `@RequiredArgsConstructor` kullanın
|
||||
- Service katmanını ince tutun; karmaşık mantığı uzmanlaşmış sınıflara devredin
|
||||
- Mesaj yönlendirme ve entegrasyon desenleri için Camel route'larını kullanın
|
||||
- Veri erişimi için Panache Repository desenini tercih edin
|
||||
|
||||
### Event-Driven
|
||||
- Always track operations with EventService (success/error events)
|
||||
- Use Camel `direct:` endpoints for in-memory routing
|
||||
- Use `spring-rabbitmq` component for RabbitMQ integration
|
||||
- Implement async publishing with `ProducerTemplate.asyncSendBody()`
|
||||
- EventService ile işlemleri her zaman takip edin (başarı/hata eventleri)
|
||||
- Bellek içi yönlendirme için Camel `direct:` endpoint'leri kullanın
|
||||
- RabbitMQ entegrasyonu için `spring-rabbitmq` bileşenini kullanın
|
||||
- `ProducerTemplate.asyncSendBody()` ile async yayınlama uygulayın
|
||||
|
||||
### Logging
|
||||
- Use Logback with Logstash encoder for structured logging
|
||||
- Propagate LogContext through service calls with `SafeAutoCloseable`
|
||||
- Add contextual information to LogContext for request tracing
|
||||
- Use `@Slf4j` instead of manual logger instantiation
|
||||
### Loglama
|
||||
- Yapılandırılmış loglama için Logstash encoder ile Logback kullanın
|
||||
- LogContext'i `SafeAutoCloseable` ile servis çağrıları boyunca yayın
|
||||
- İstek takibi için LogContext'e bağlamsal bilgi ekleyin
|
||||
- Manuel logger oluşturma yerine `@Slf4j` kullanın
|
||||
|
||||
### Async Operations
|
||||
- Use CompletableFuture for non-blocking I/O operations
|
||||
- Call `.join()` when you need to wait for completion
|
||||
- Handle exceptions from CompletableFuture properly
|
||||
- Pass LogContext to async operations for tracing
|
||||
### Async İşlemler
|
||||
- Bloklamayan I/O işlemleri için CompletableFuture kullanın
|
||||
- Tamamlanmayı beklemek gerektiğinde `.join()` çağırın
|
||||
- CompletableFuture'dan gelen exception'ları düzgün şekilde ele alın
|
||||
- Takip için async işlemlere LogContext geçirin
|
||||
|
||||
### Configuration
|
||||
- Use YAML configuration (`quarkus-config-yaml`)
|
||||
- Profile-aware configuration for dev/test/prod environments
|
||||
- Externalize sensitive configuration to environment variables
|
||||
- Use `@ConfigProperty` for type-safe config injection
|
||||
### Yapılandırma
|
||||
- YAML yapılandırmasını kullanın (`quarkus-config-yaml`)
|
||||
- Dev/test/prod ortamları için profil-duyarlı yapılandırma
|
||||
- Hassas yapılandırmayı ortam değişkenlerine dışsallaştırın
|
||||
- Tip-güvenli yapılandırma injection için `@ConfigProperty` kullanın
|
||||
|
||||
### Validation
|
||||
- Validate at resource layer with `@Valid`
|
||||
- Use Bean Validation annotations on DTOs
|
||||
- Map exceptions to proper HTTP responses with `@Provider`
|
||||
- Resource katmanında `@Valid` ile doğrulayın
|
||||
- DTO'larda Bean Validation annotasyonları kullanın
|
||||
- Exception'ları `@Provider` ile uygun HTTP yanıtlarına eşleyin
|
||||
|
||||
### Transactions
|
||||
- Use `@Transactional` on service methods that modify data
|
||||
- Keep transactions short and focused
|
||||
- Avoid calling async operations within transactions
|
||||
### Transaction'lar
|
||||
- Veri değiştiren service metodlarında `@Transactional` kullanın
|
||||
- Transaction'ları kısa ve odaklı tutun
|
||||
- Transaction'lar içinden async işlem çağırmaktan kaçının
|
||||
|
||||
### Testing
|
||||
- Use `camel-quarkus-junit5` for route testing
|
||||
- Use AssertJ for assertions
|
||||
- Mock all external dependencies
|
||||
- Test conditional flow logic thoroughly
|
||||
### Test
|
||||
- Route testi için `camel-quarkus-junit5` kullanın
|
||||
- Assertion'lar için AssertJ kullanın
|
||||
- Tüm harici bağımlılıkları mock'layın
|
||||
- Koşullu akış mantığını kapsamlı biçimde test edin
|
||||
|
||||
### Quarkus-Specific
|
||||
- Stay on latest LTS version (3.x)
|
||||
- Use Quarkus dev mode for hot reload
|
||||
- Add health checks for production readiness
|
||||
- Test native compilation compatibility periodically
|
||||
### Quarkus'a Özgü
|
||||
- En son LTS sürümünde kalın (3.x)
|
||||
- Hot reload için Quarkus dev modunu kullanın
|
||||
- Production hazırlığı için sağlık kontrolleri ekleyin
|
||||
- Native derleme uyumluluğunu periyodik olarak test edin
|
||||
|
||||
@@ -4,29 +4,27 @@ description: Quarkus Security best practices for authentication, authorization,
|
||||
origin: ECC
|
||||
---
|
||||
|
||||
> **Not / Note**: Bu dosya henuz Turkceye cevrilmemistir, su anda Ingilizce orijinaldir. Ceviri PR'lari memnuniyetle karsilanir.
|
||||
# Quarkus Güvenlik İncelemesi
|
||||
|
||||
# Quarkus Security Review
|
||||
Kimlik doğrulama, yetkilendirme ve girdi doğrulama ile Quarkus uygulamalarını güvenli hale getirmek için en iyi uygulamalar.
|
||||
|
||||
Best practices for securing Quarkus applications with authentication, authorization, and input validation.
|
||||
## Ne Zaman Aktif Edilir
|
||||
|
||||
## When to Activate
|
||||
- Kimlik doğrulama ekleme (JWT, OIDC, Basic Auth)
|
||||
- `@RolesAllowed` veya SecurityIdentity ile yetkilendirme uygulama
|
||||
- Kullanıcı girişini doğrulama (Bean Validation, özel doğrulayıcılar)
|
||||
- CORS veya güvenlik başlıklarını yapılandırma
|
||||
- Gizli bilgileri yönetme (Vault, ortam değişkenleri, config kaynakları)
|
||||
- Rate limiting veya brute-force koruması ekleme
|
||||
- Bağımlılıkları CVE için tarama
|
||||
- MicroProfile JWT veya SmallRye JWT ile çalışma
|
||||
|
||||
- Adding authentication (JWT, OIDC, Basic Auth)
|
||||
- Implementing authorization with @RolesAllowed or SecurityIdentity
|
||||
- Validating user input (Bean Validation, custom validators)
|
||||
- Configuring CORS or security headers
|
||||
- Managing secrets (Vault, environment variables, config sources)
|
||||
- Adding rate limiting or brute-force protection
|
||||
- Scanning dependencies for CVEs
|
||||
- Working with MicroProfile JWT or SmallRye JWT
|
||||
## Kimlik Doğrulama
|
||||
|
||||
## Authentication
|
||||
|
||||
### JWT Authentication
|
||||
### JWT Kimlik Doğrulama
|
||||
|
||||
```java
|
||||
// Resource protected with JWT
|
||||
// JWT ile korunan resource
|
||||
@Path("/api/protected")
|
||||
@Authenticated
|
||||
public class ProtectedResource {
|
||||
@@ -50,7 +48,7 @@ public class ProtectedResource {
|
||||
}
|
||||
```
|
||||
|
||||
Configuration (application.properties):
|
||||
Yapılandırma (application.properties):
|
||||
```properties
|
||||
mp.jwt.verify.publickey.location=publicKey.pem
|
||||
mp.jwt.verify.issuer=https://auth.example.com
|
||||
@@ -61,7 +59,7 @@ quarkus.oidc.client-id=backend-service
|
||||
quarkus.oidc.credentials.secret=${OIDC_SECRET}
|
||||
```
|
||||
|
||||
### Custom Authentication Filter
|
||||
### Özel Kimlik Doğrulama Filtresi
|
||||
|
||||
```java
|
||||
@Provider
|
||||
@@ -77,7 +75,7 @@ public class CustomAuthFilter implements ContainerRequestFilter {
|
||||
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
// Validate token and set SecurityIdentity
|
||||
// Token'ı doğrula ve SecurityIdentity'yi ayarla
|
||||
if (!validateToken(token)) {
|
||||
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
|
||||
}
|
||||
@@ -85,15 +83,15 @@ public class CustomAuthFilter implements ContainerRequestFilter {
|
||||
}
|
||||
|
||||
private boolean validateToken(String token) {
|
||||
// Token validation logic
|
||||
// Token doğrulama mantığı
|
||||
return true;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Authorization
|
||||
## Yetkilendirme
|
||||
|
||||
### Role-Based Access Control
|
||||
### Rol Tabanlı Erişim Kontrolü
|
||||
|
||||
```java
|
||||
@Path("/api/admin")
|
||||
@@ -125,7 +123,7 @@ public class UserResource {
|
||||
@Path("/{id}")
|
||||
@RolesAllowed("USER")
|
||||
public Response getUser(@PathParam("id") Long id) {
|
||||
// Check ownership
|
||||
// Sahipliği kontrol et
|
||||
if (!securityIdentity.hasRole("ADMIN") &&
|
||||
!isOwner(id, securityIdentity.getPrincipal().getName())) {
|
||||
return Response.status(Response.Status.FORBIDDEN).build();
|
||||
@@ -139,7 +137,7 @@ public class UserResource {
|
||||
}
|
||||
```
|
||||
|
||||
### Programmatic Security
|
||||
### Programatik Güvenlik
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -163,18 +161,18 @@ public class SecurityService {
|
||||
}
|
||||
```
|
||||
|
||||
## Input Validation
|
||||
## Girdi Doğrulama
|
||||
|
||||
### Bean Validation
|
||||
|
||||
```java
|
||||
// BAD: No validation
|
||||
// KÖTÜ: Validation yok
|
||||
@POST
|
||||
public Response createUser(UserDto dto) {
|
||||
return Response.ok(userService.create(dto)).build();
|
||||
}
|
||||
|
||||
// GOOD: Validated DTO
|
||||
// İYİ: Doğrulanmış DTO
|
||||
public record CreateUserDto(
|
||||
@NotBlank @Size(max = 100) String name,
|
||||
@NotBlank @Email String email,
|
||||
@@ -190,7 +188,7 @@ public Response createUser(@Valid CreateUserDto dto) {
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Validators
|
||||
### Özel Doğrulayıcılar
|
||||
|
||||
```java
|
||||
@Target({ElementType.FIELD, ElementType.PARAMETER})
|
||||
@@ -210,35 +208,35 @@ public class UsernameValidator implements ConstraintValidator<ValidUsername, Str
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
// Kullanım
|
||||
public record CreateUserDto(
|
||||
@ValidUsername String username,
|
||||
@NotBlank @Email String email
|
||||
) {}
|
||||
```
|
||||
|
||||
## SQL Injection Prevention
|
||||
## SQL Injection Önleme
|
||||
|
||||
### Panache Active Record (Safe by Default)
|
||||
### Panache Active Record (Varsayılan Olarak Güvenli)
|
||||
|
||||
```java
|
||||
// GOOD: Parameterized queries with Panache
|
||||
// İYİ: Panache ile parametreli sorgular
|
||||
List<User> users = User.list("email = ?1 and active = ?2", email, true);
|
||||
|
||||
Optional<User> user = User.find("username", username).firstResultOptional();
|
||||
|
||||
// GOOD: Named parameters
|
||||
// İYİ: İsimlendirilmiş parametreler
|
||||
List<User> users = User.list("email = :email and age > :minAge",
|
||||
Parameters.with("email", email).and("minAge", 18));
|
||||
```
|
||||
|
||||
### Native Queries (Use Parameters)
|
||||
### Native Sorgular (Parametre Kullanın)
|
||||
|
||||
```java
|
||||
// BAD: String concatenation
|
||||
// KÖTÜ: String birleştirme
|
||||
@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)
|
||||
|
||||
// GOOD: Parameterized native query
|
||||
// İYİ: Parametreli native sorgu
|
||||
@Entity
|
||||
public class User extends PanacheEntity {
|
||||
public static List<User> findByEmailNative(String email) {
|
||||
@@ -250,7 +248,7 @@ public class User extends PanacheEntity {
|
||||
}
|
||||
```
|
||||
|
||||
## Password Hashing
|
||||
## Parola Hash'leme
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -265,7 +263,7 @@ public class PasswordService {
|
||||
}
|
||||
}
|
||||
|
||||
// In service
|
||||
// Servis içinde
|
||||
@ApplicationScoped
|
||||
public class UserService {
|
||||
@Inject
|
||||
@@ -290,7 +288,7 @@ public class UserService {
|
||||
}
|
||||
```
|
||||
|
||||
## CORS Configuration
|
||||
## CORS Yapılandırması
|
||||
|
||||
```properties
|
||||
# application.properties
|
||||
@@ -303,12 +301,12 @@ quarkus.http.cors.access-control-max-age=24H
|
||||
quarkus.http.cors.access-control-allow-credentials=true
|
||||
```
|
||||
|
||||
## Secrets Management
|
||||
## Gizli Bilgi Yönetimi
|
||||
|
||||
```properties
|
||||
# application.properties - NO SECRETS HERE
|
||||
# application.properties - BURADA GİZLİ BİLGİ YOK
|
||||
|
||||
# Use environment variables
|
||||
# Ortam değişkenlerini kullanın
|
||||
quarkus.datasource.username=${DB_USER}
|
||||
quarkus.datasource.password=${DB_PASSWORD}
|
||||
quarkus.oidc.credentials.secret=${OIDC_CLIENT_SECRET}
|
||||
@@ -318,14 +316,14 @@ quarkus.vault.url=https://vault.example.com
|
||||
quarkus.vault.authentication.kubernetes.role=my-role
|
||||
```
|
||||
|
||||
### HashiCorp Vault Integration
|
||||
### HashiCorp Vault Entegrasyonu
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
public class SecretService {
|
||||
|
||||
@ConfigProperty(name = "api-key")
|
||||
String apiKey; // Fetched from Vault
|
||||
String apiKey; // Vault'tan alınır
|
||||
|
||||
public String getSecret(String key) {
|
||||
return ConfigProvider.getConfig().getValue(key, String.class);
|
||||
@@ -333,7 +331,7 @@ public class SecretService {
|
||||
}
|
||||
```
|
||||
|
||||
## Rate Limiting
|
||||
## Rate Limiting (Hız Sınırlama)
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -344,7 +342,7 @@ public class RateLimitFilter implements ContainerRequestFilter {
|
||||
public void filter(ContainerRequestContext requestContext) {
|
||||
String clientId = getClientIdentifier(requestContext);
|
||||
RateLimiter limiter = limiters.computeIfAbsent(clientId,
|
||||
k -> RateLimiter.create(100.0)); // 100 requests per second
|
||||
k -> RateLimiter.create(100.0)); // Saniyede 100 istek
|
||||
|
||||
if (!limiter.tryAcquire()) {
|
||||
requestContext.abortWith(
|
||||
@@ -356,13 +354,13 @@ public class RateLimitFilter implements ContainerRequestFilter {
|
||||
}
|
||||
|
||||
private String getClientIdentifier(ContainerRequestContext ctx) {
|
||||
// Use IP, API key, or user ID
|
||||
// IP, API anahtarı veya kullanıcı ID'si kullanın
|
||||
return ctx.getHeaderString("X-Forwarded-For");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Security Headers
|
||||
## Güvenlik Başlıkları
|
||||
|
||||
```java
|
||||
@Provider
|
||||
@@ -372,10 +370,10 @@ public class SecurityHeadersFilter implements ContainerResponseFilter {
|
||||
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
|
||||
MultivaluedMap<String, Object> headers = response.getHeaders();
|
||||
|
||||
// Prevent clickjacking
|
||||
// Clickjacking'i önle
|
||||
headers.putSingle("X-Frame-Options", "DENY");
|
||||
|
||||
// XSS protection
|
||||
// XSS koruması
|
||||
headers.putSingle("X-Content-Type-Options", "nosniff");
|
||||
headers.putSingle("X-XSS-Protection", "1; mode=block");
|
||||
|
||||
@@ -389,7 +387,7 @@ public class SecurityHeadersFilter implements ContainerResponseFilter {
|
||||
}
|
||||
```
|
||||
|
||||
## Audit Logging
|
||||
## Denetim Loglama
|
||||
|
||||
```java
|
||||
@ApplicationScoped
|
||||
@@ -409,7 +407,7 @@ public class AuditService {
|
||||
}
|
||||
}
|
||||
|
||||
// Usage in resource
|
||||
// Resource içinde kullanım
|
||||
@Path("/api/sensitive")
|
||||
public class SensitiveResource {
|
||||
@Inject
|
||||
@@ -424,7 +422,7 @@ public class SensitiveResource {
|
||||
}
|
||||
```
|
||||
|
||||
## Dependency Security Scanning
|
||||
## Bağımlılık Güvenliği Taraması
|
||||
|
||||
```bash
|
||||
# Maven
|
||||
@@ -437,19 +435,19 @@ mvn org.owasp:dependency-check-maven:check
|
||||
quarkus extension list --installable
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
## En İyi Uygulamalar
|
||||
|
||||
- Always use HTTPS in production
|
||||
- Enable JWT or OIDC for stateless authentication
|
||||
- Use `@RolesAllowed` for declarative authorization
|
||||
- Validate all input with Bean Validation
|
||||
- Hash passwords with BCrypt (never plaintext)
|
||||
- Store secrets in Vault or environment variables
|
||||
- Use parameterized queries to prevent SQL injection
|
||||
- Add security headers to all responses
|
||||
- Implement rate limiting for public endpoints
|
||||
- Audit sensitive operations
|
||||
- Keep dependencies updated and scan for CVEs
|
||||
- Use SecurityIdentity for programmatic checks
|
||||
- Set appropriate CORS policies
|
||||
- Test authentication and authorization paths
|
||||
- Production'da her zaman HTTPS kullanın
|
||||
- Stateless kimlik doğrulama için JWT veya OIDC etkinleştirin
|
||||
- Bildirimsel yetkilendirme için `@RolesAllowed` kullanın
|
||||
- Bean Validation ile tüm girişleri doğrulayın
|
||||
- Parolaları BCrypt ile hash'leyin (asla düz metin saklamayın)
|
||||
- Gizli bilgileri Vault veya ortam değişkenlerinde saklayın
|
||||
- SQL injection'ı önlemek için parametreli sorgular kullanın
|
||||
- Tüm yanıtlara güvenlik başlıkları ekleyin
|
||||
- Genel endpoint'lerde rate limiting uygulayın
|
||||
- Hassas işlemleri denetleyin
|
||||
- Bağımlılıkları güncel tutun ve CVE için tarayın
|
||||
- Programatik kontroller için SecurityIdentity kullanın
|
||||
- Uygun CORS politikaları belirleyin
|
||||
- Kimlik doğrulama ve yetkilendirme yollarını test edin
|
||||
|
||||
@@ -4,33 +4,31 @@ description: Test-driven development for Quarkus 3.x LTS using JUnit 5, Mockito,
|
||||
origin: ECC
|
||||
---
|
||||
|
||||
> **Not / Note**: Bu dosya henuz Turkceye cevrilmemistir, su anda Ingilizce orijinaldir. Ceviri PR'lari memnuniyetle karsilanir.
|
||||
# Quarkus TDD İş Akışı
|
||||
|
||||
# Quarkus TDD Workflow
|
||||
80%+ kapsam (unit + integration) ile Quarkus 3.x servisleri için TDD rehberi. Apache Camel ile event-driven mimariler için optimize edilmiştir.
|
||||
|
||||
TDD guidance for Quarkus 3.x services with 80%+ coverage (unit + integration). Optimized for event-driven architectures with Apache Camel.
|
||||
## Ne Zaman Kullanılır
|
||||
|
||||
## When to Use
|
||||
- Yeni özellikler veya REST endpoint'leri
|
||||
- Bug düzeltmeleri veya refactoring'ler
|
||||
- Veri erişim mantığı, güvenlik kuralları veya reaktif akışlar ekleme
|
||||
- Apache Camel route'larını ve event handler'larını test etme
|
||||
- RabbitMQ ile event-driven servisleri test etme
|
||||
- Koşullu akış mantığını test etme
|
||||
- CompletableFuture async işlemlerini doğrulama
|
||||
- LogContext yayılımını test etme
|
||||
|
||||
- New features or REST endpoints
|
||||
- Bug fixes or refactors
|
||||
- Adding data access logic, security rules, or reactive streams
|
||||
- Testing Apache Camel routes and event handlers
|
||||
- Testing event-driven services with RabbitMQ
|
||||
- Testing conditional flow logic
|
||||
- Validating CompletableFuture async operations
|
||||
- Testing LogContext propagation
|
||||
## İş Akışı
|
||||
|
||||
## Workflow
|
||||
1. Önce testleri yazın (başarısız olmalılar)
|
||||
2. Geçmek için minimal kod uygulayın
|
||||
3. Testleri yeşil tutarken refactor edin
|
||||
4. JaCoCo ile kapsamı zorlayın (%80+ hedef)
|
||||
|
||||
1. Write tests first (they should fail)
|
||||
2. Implement minimal code to pass
|
||||
3. Refactor with tests green
|
||||
4. Enforce coverage with JaCoCo (80%+ target)
|
||||
## @Nested Organizasyonlu Unit Testler
|
||||
|
||||
## Unit Tests with @Nested Organization
|
||||
|
||||
Follow this structured approach for comprehensive, readable tests:
|
||||
Kapsamlı ve okunabilir testler için bu yapılandırılmış yaklaşımı izleyin:
|
||||
|
||||
```java
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@@ -62,7 +60,7 @@ class As2ProcessingServiceTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// ARRANGE - Common test data
|
||||
// ARRANGE - Ortak test verisi
|
||||
testFilePath = Path.of("/tmp/test-invoice.xml");
|
||||
|
||||
testLogContext = new LogContext();
|
||||
@@ -81,11 +79,11 @@ class As2ProcessingServiceTest {
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for processFile")
|
||||
@DisplayName("processFile için testler")
|
||||
class ProcessFile {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should successfully process non-CHORUS file with all validations")
|
||||
@DisplayName("CHORUS olmayan dosyayı tüm validasyonlarla başarıyla işlemeli")
|
||||
void givenNonChorusFile_whenProcessFile_thenAllValidationsApplied() throws Exception {
|
||||
// ARRANGE
|
||||
testLogContext.put(As2Constants.CHORUS_FLOW, "false");
|
||||
@@ -125,7 +123,7 @@ class As2ProcessingServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should bypass schematron validation for CHORUS_FLOW")
|
||||
@DisplayName("CHORUS_FLOW için schematron validasyonu atlanmalı")
|
||||
void givenChorusFlow_whenProcessFile_thenSchematronBypassed() throws Exception {
|
||||
// ARRANGE
|
||||
testLogContext.put(As2Constants.CHORUS_FLOW, "true");
|
||||
@@ -162,7 +160,7 @@ class As2ProcessingServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should create error event when file upload fails")
|
||||
@DisplayName("Dosya yükleme başarısız olduğunda hata eventi oluşturulmalı")
|
||||
void givenUploadFailure_whenProcessFile_thenErrorEventCreated() throws Exception {
|
||||
// ARRANGE
|
||||
testLogContext.put(As2Constants.CHORUS_FLOW, "false");
|
||||
@@ -174,7 +172,7 @@ class As2ProcessingServiceTest {
|
||||
when(invoiceFlowValidator.computeFlowProfile(any(), any()))
|
||||
.thenReturn(FlowProfile.BASIC);
|
||||
|
||||
documentInfo.setPath(""); // Blank path triggers error
|
||||
documentInfo.setPath(""); // Boş path hatayı tetikler
|
||||
when(fileStorageService.uploadOriginalFile(any(), anyLong(), any(), any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(documentInfo));
|
||||
|
||||
@@ -196,7 +194,7 @@ class As2ProcessingServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle CompletableFuture.join() failure")
|
||||
@DisplayName("CompletableFuture.join() başarısızlığı ele alınmalı")
|
||||
void givenAsyncUploadFailure_whenProcessFile_thenExceptionThrown() throws Exception {
|
||||
// ARRANGE
|
||||
testLogContext.put(As2Constants.CHORUS_FLOW, "false");
|
||||
@@ -221,7 +219,7 @@ class As2ProcessingServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should throw exception when file path is null")
|
||||
@DisplayName("Dosya yolu null olduğunda exception fırlatılmalı")
|
||||
void givenNullFilePath_whenProcessFile_thenThrowsException() {
|
||||
// ARRANGE
|
||||
Path nullPath = null;
|
||||
@@ -238,20 +236,20 @@ class As2ProcessingServiceTest {
|
||||
}
|
||||
```
|
||||
|
||||
### Key Testing Patterns
|
||||
### Temel Test Desenleri
|
||||
|
||||
1. **@Nested Classes**: Group tests by method being tested
|
||||
2. **@DisplayName**: Provide readable test descriptions for test reports
|
||||
3. **Naming Convention**: `givenX_whenY_thenZ` for clarity
|
||||
4. **AAA Pattern**: Explicit `// ARRANGE`, `// ACT`, `// ASSERT` comments
|
||||
5. **@BeforeEach**: Setup common test data to reduce duplication
|
||||
6. **assertDoesNotThrow**: Test success scenarios without catching exceptions
|
||||
7. **assertThrows**: Test exception scenarios with message validation using AssertJ
|
||||
8. **Comprehensive Coverage**: Test happy paths, null inputs, edge cases, exceptions
|
||||
9. **Verify Interactions**: Use Mockito `verify()` to ensure methods are called correctly
|
||||
10. **Never Verify**: Use `never()` to ensure methods are NOT called in error scenarios
|
||||
1. **@Nested Sınıflar**: Testleri test edilen metoda göre gruplandırın
|
||||
2. **@DisplayName**: Test raporlarında okunabilir açıklamalar sağlayın
|
||||
3. **İsimlendirme Kuralı**: Netlik için `givenX_whenY_thenZ`
|
||||
4. **AAA Deseni**: Açık `// ARRANGE`, `// ACT`, `// ASSERT` yorumları
|
||||
5. **@BeforeEach**: Tekrarı azaltmak için ortak test verisi kurulumu
|
||||
6. **assertDoesNotThrow**: Exception yakalamadan başarı senaryolarını test edin
|
||||
7. **assertThrows**: AssertJ kullanarak mesaj doğrulamalı exception senaryolarını test edin
|
||||
8. **Kapsamlı Kapsam**: Mutlu yolları, null girdileri, edge case'leri, exception'ları test edin
|
||||
9. **Etkileşimleri Doğrulama**: Metodların doğru çağrıldığından emin olmak için Mockito `verify()` kullanın
|
||||
10. **Hiçbir Zaman Doğrulama**: Hata senaryolarında metodların ÇAĞRILMADIĞINI sağlamak için `never()` kullanın
|
||||
|
||||
## Testing Camel Routes
|
||||
## Camel Route Testi
|
||||
|
||||
```java
|
||||
@QuarkusTest
|
||||
@@ -271,25 +269,25 @@ class BusinessRulesRouteTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// ARRANGE - Test data
|
||||
// ARRANGE - Test verisi
|
||||
testPayload = new BusinessRulesPayload();
|
||||
testPayload.setDocumentId(1L);
|
||||
testPayload.setFlowProfile(FlowProfile.BASIC);
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for business-rules-publisher route")
|
||||
@DisplayName("business-rules-publisher route için testler")
|
||||
class BusinessRulesPublisher {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should successfully publish message to RabbitMQ")
|
||||
@DisplayName("Mesajı başarıyla RabbitMQ'ya yayınlamalı")
|
||||
void givenValidPayload_whenPublish_thenMessageSentToQueue() throws Exception {
|
||||
// ARRANGE
|
||||
MockEndpoint mockRabbitMQ = camelContext.getEndpoint("mock:rabbitmq", MockEndpoint.class);
|
||||
mockRabbitMQ.expectedMessageCount(1);
|
||||
mockRabbitMQ.expectedBodiesReceived(testPayload);
|
||||
|
||||
// Replace real endpoint with mock for testing
|
||||
// Test için gerçek endpoint'i mock ile değiştir
|
||||
camelContext.getRouteController().stopRoute("business-rules-publisher");
|
||||
AdviceWith.adviceWith(camelContext, "business-rules-publisher", advice -> {
|
||||
advice.replaceFromWith("direct:business-rules-publisher");
|
||||
@@ -309,7 +307,7 @@ class BusinessRulesRouteTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle marshalling to JSON")
|
||||
@DisplayName("JSON'a marshalling'i ele almalı")
|
||||
void givenPayload_whenPublish_thenMarshalledToJson() throws Exception {
|
||||
// ARRANGE
|
||||
MockEndpoint mockMarshal = new MockEndpoint("mock:marshal");
|
||||
@@ -335,11 +333,11 @@ class BusinessRulesRouteTest {
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for document-processing route")
|
||||
@DisplayName("document-processing route için testler")
|
||||
class DocumentProcessing {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should route invoice to correct processor")
|
||||
@DisplayName("Faturayı doğru işlemciye yönlendirmeli")
|
||||
void givenInvoiceType_whenProcess_thenRoutesToInvoiceProcessor() throws Exception {
|
||||
// ARRANGE
|
||||
MockEndpoint mockInvoice = camelContext.getEndpoint("mock:invoice", MockEndpoint.class);
|
||||
@@ -360,7 +358,7 @@ class BusinessRulesRouteTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle validation errors gracefully")
|
||||
@DisplayName("Validasyon hatalarını zarif şekilde ele almalı")
|
||||
void givenValidationError_whenProcess_thenRoutesToErrorHandler() throws Exception {
|
||||
// ARRANGE
|
||||
MockEndpoint mockError = camelContext.getEndpoint("mock:error", MockEndpoint.class);
|
||||
@@ -373,7 +371,7 @@ class BusinessRulesRouteTest {
|
||||
});
|
||||
camelContext.getRouteController().startRoute("document-processing");
|
||||
|
||||
// Mock validator to throw exception
|
||||
// Validator'ı exception fırlatacak şekilde mock'la
|
||||
when(eventService.validate(any())).thenThrow(new ValidationException("Invalid document"));
|
||||
|
||||
// ACT
|
||||
@@ -390,7 +388,7 @@ class BusinessRulesRouteTest {
|
||||
}
|
||||
```
|
||||
|
||||
## Testing Event Services
|
||||
## Event Service Testi
|
||||
|
||||
```java
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@@ -416,11 +414,11 @@ class EventServiceTest {
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for createSuccessEvent")
|
||||
@DisplayName("createSuccessEvent için testler")
|
||||
class CreateSuccessEvent {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should create success event with correct attributes")
|
||||
@DisplayName("Doğru niteliklerle başarı eventi oluşturulmalı")
|
||||
void givenValidPayload_whenCreateSuccessEvent_thenEventPersisted() throws Exception {
|
||||
// ARRANGE
|
||||
when(objectMapper.writeValueAsString(testPayload)).thenReturn("{\"documentId\":1}");
|
||||
@@ -439,7 +437,7 @@ class EventServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should throw exception when payload is null")
|
||||
@DisplayName("Payload null olduğunda exception fırlatılmalı")
|
||||
void givenNullPayload_whenCreateSuccessEvent_thenThrowsException() {
|
||||
// ARRANGE
|
||||
Object nullPayload = null;
|
||||
@@ -456,11 +454,11 @@ class EventServiceTest {
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for createErrorEvent")
|
||||
@DisplayName("createErrorEvent için testler")
|
||||
class CreateErrorEvent {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should create error event with error message")
|
||||
@DisplayName("Hata mesajıyla hata eventi oluşturulmalı")
|
||||
void givenError_whenCreateErrorEvent_thenEventPersistedWithMessage() throws Exception {
|
||||
// ARRANGE
|
||||
String errorMessage = "Processing failed";
|
||||
@@ -480,7 +478,7 @@ class EventServiceTest {
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@DisplayName("Should reject invalid error messages")
|
||||
@DisplayName("Geçersiz hata mesajları reddedilmeli")
|
||||
@ValueSource(strings = {"", " "})
|
||||
void givenBlankErrorMessage_whenCreateErrorEvent_thenThrowsException(String blankMessage) {
|
||||
// ACT & ASSERT
|
||||
@@ -495,7 +493,7 @@ class EventServiceTest {
|
||||
}
|
||||
```
|
||||
|
||||
## Testing CompletableFuture
|
||||
## CompletableFuture Testi
|
||||
|
||||
```java
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@@ -523,11 +521,11 @@ class FileStorageServiceTest {
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for uploadOriginalFile")
|
||||
@DisplayName("uploadOriginalFile için testler")
|
||||
class UploadOriginalFile {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should successfully upload file and return document info")
|
||||
@DisplayName("Dosyayı başarıyla yüklemeli ve belge bilgisi döndürmeli")
|
||||
void givenValidFile_whenUpload_thenReturnsDocumentInfo() throws Exception {
|
||||
// ARRANGE
|
||||
when(executorService.submit(any(Callable.class))).thenAnswer(invocation -> {
|
||||
@@ -555,7 +553,7 @@ class FileStorageServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle S3 upload failure")
|
||||
@DisplayName("S3 yükleme başarısızlığını ele almalı")
|
||||
void givenS3Failure_whenUpload_thenCompletableFutureFails() {
|
||||
// ARRANGE
|
||||
when(executorService.submit(any(Callable.class))).thenAnswer(invocation -> {
|
||||
@@ -575,7 +573,7 @@ class FileStorageServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should propagate LogContext to async operation")
|
||||
@DisplayName("LogContext'i async işleme yaymalı")
|
||||
void givenLogContext_whenUpload_thenContextPropagated() throws Exception {
|
||||
// ARRANGE
|
||||
AtomicReference<LogContext> capturedContext = new AtomicReference<>();
|
||||
@@ -598,7 +596,7 @@ class FileStorageServiceTest {
|
||||
}
|
||||
```
|
||||
|
||||
## Resource Layer Tests (REST Assured)
|
||||
## Resource Katmanı Testleri (REST Assured)
|
||||
|
||||
```java
|
||||
@QuarkusTest
|
||||
@@ -609,11 +607,11 @@ class DocumentResourceTest {
|
||||
DocumentService documentService;
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for GET /api/documents")
|
||||
@DisplayName("GET /api/documents için testler")
|
||||
class ListDocuments {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return list of documents")
|
||||
@DisplayName("Belge listesini döndürmeli")
|
||||
void givenDocumentsExist_whenList_thenReturnsOk() {
|
||||
// ARRANGE
|
||||
List<Document> documents = List.of(createDocument(1L, "DOC-001"));
|
||||
@@ -630,11 +628,11 @@ class DocumentResourceTest {
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("Tests for POST /api/documents")
|
||||
@DisplayName("POST /api/documents için testler")
|
||||
class CreateDocument {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should create document and return 201")
|
||||
@DisplayName("Belge oluşturmalı ve 201 döndürmeli")
|
||||
void givenValidRequest_whenCreate_thenReturns201() {
|
||||
// ARRANGE
|
||||
Document document = createDocument(1L, "DOC-001");
|
||||
@@ -659,7 +657,7 @@ class DocumentResourceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return 400 for invalid input")
|
||||
@DisplayName("Geçersiz girdi için 400 döndürmeli")
|
||||
void givenInvalidRequest_whenCreate_thenReturns400() {
|
||||
// ACT & ASSERT
|
||||
given()
|
||||
@@ -686,7 +684,7 @@ class DocumentResourceTest {
|
||||
}
|
||||
```
|
||||
|
||||
## Integration Tests with Real Database
|
||||
## Gerçek Veritabanıyla Entegrasyon Testleri
|
||||
|
||||
```java
|
||||
@QuarkusTest
|
||||
@@ -696,9 +694,9 @@ class DocumentIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
@DisplayName("Should create and retrieve document via API")
|
||||
@DisplayName("Belge oluşturulmalı ve API üzerinden alınabilmeli")
|
||||
void givenNewDocument_whenCreateAndRetrieve_thenSuccessful() {
|
||||
// ACT - Create via API
|
||||
// ACT - API üzerinden oluştur
|
||||
Long id = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
@@ -714,7 +712,7 @@ class DocumentIntegrationTest {
|
||||
.statusCode(201)
|
||||
.extract().path("id");
|
||||
|
||||
// ASSERT - Retrieve via API
|
||||
// ASSERT - API üzerinden al
|
||||
given()
|
||||
.when().get("/api/documents/" + id)
|
||||
.then()
|
||||
@@ -724,9 +722,9 @@ class DocumentIntegrationTest {
|
||||
}
|
||||
```
|
||||
|
||||
## Coverage with JaCoCo
|
||||
## JaCoCo ile Kapsam
|
||||
|
||||
### Maven Configuration (Complete)
|
||||
### Maven Yapılandırması (Tam)
|
||||
|
||||
```xml
|
||||
<plugin>
|
||||
@@ -734,7 +732,7 @@ class DocumentIntegrationTest {
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<version>0.8.13</version>
|
||||
<executions>
|
||||
<!-- Prepare agent for test execution -->
|
||||
<!-- Test yürütmesi için agent'ı hazırla -->
|
||||
<execution>
|
||||
<id>prepare-agent</id>
|
||||
<goals>
|
||||
@@ -742,7 +740,7 @@ class DocumentIntegrationTest {
|
||||
</goals>
|
||||
</execution>
|
||||
|
||||
<!-- Generate coverage report -->
|
||||
<!-- Kapsam raporu oluştur -->
|
||||
<execution>
|
||||
<id>report</id>
|
||||
<phase>verify</phase>
|
||||
@@ -751,7 +749,7 @@ class DocumentIntegrationTest {
|
||||
</goals>
|
||||
</execution>
|
||||
|
||||
<!-- Enforce coverage thresholds -->
|
||||
<!-- Kapsam eşiklerini zorla -->
|
||||
<execution>
|
||||
<id>check</id>
|
||||
<goals>
|
||||
@@ -781,20 +779,20 @@ class DocumentIntegrationTest {
|
||||
</plugin>
|
||||
```
|
||||
|
||||
Run tests with coverage:
|
||||
Kapsam ile testleri çalıştırın:
|
||||
```bash
|
||||
mvn clean test
|
||||
mvn jacoco:report
|
||||
mvn jacoco:check
|
||||
|
||||
# Report at: target/site/jacoco/index.html
|
||||
# Rapor: target/site/jacoco/index.html
|
||||
```
|
||||
|
||||
## Test Dependencies
|
||||
## Test Bağımlılıkları
|
||||
|
||||
```xml
|
||||
<dependencies>
|
||||
<!-- Quarkus Testing -->
|
||||
<!-- Quarkus Test -->
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-junit5</artifactId>
|
||||
@@ -813,7 +811,7 @@ mvn jacoco:check
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- AssertJ (preferred over JUnit assertions) -->
|
||||
<!-- AssertJ (JUnit assertion'larına tercih edilir) -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
@@ -828,7 +826,7 @@ mvn jacoco:check
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Camel Testing -->
|
||||
<!-- Camel Test -->
|
||||
<dependency>
|
||||
<groupId>org.apache.camel.quarkus</groupId>
|
||||
<artifactId>camel-quarkus-junit5</artifactId>
|
||||
@@ -837,74 +835,74 @@ mvn jacoco:check
|
||||
</dependencies>
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
## En İyi Uygulamalar
|
||||
|
||||
### Test Organization
|
||||
- Use `@Nested` classes to group tests by method being tested
|
||||
- Use `@DisplayName` for readable test descriptions visible in reports
|
||||
- Follow `givenX_whenY_thenZ` naming convention for test methods
|
||||
- Use `@BeforeEach` for common test data setup to reduce duplication
|
||||
### Test Organizasyonu
|
||||
- Testleri test edilen metoda göre gruplandırmak için `@Nested` sınıflar kullanın
|
||||
- Raporlarda görünür okunabilir açıklamalar için `@DisplayName` kullanın
|
||||
- Test metodları için `givenX_whenY_thenZ` isimlendirme kuralını izleyin
|
||||
- Tekrarı azaltmak için ortak test verisi kurulumunda `@BeforeEach` kullanın
|
||||
|
||||
### Test Structure
|
||||
- Follow AAA pattern with explicit comments (`// ARRANGE`, `// ACT`, `// ASSERT`)
|
||||
- Use `assertDoesNotThrow` for success scenarios
|
||||
- Use `assertThrows` for exception scenarios with message validation
|
||||
- Verify exception messages match expected values using AssertJ `contains()` or `isEqualTo()`
|
||||
### Test Yapısı
|
||||
- Açık yorumlarla AAA desenini izleyin (`// ARRANGE`, `// ACT`, `// ASSERT`)
|
||||
- Başarı senaryoları için `assertDoesNotThrow` kullanın
|
||||
- Mesaj doğrulamalı exception senaryoları için `assertThrows` kullanın
|
||||
- AssertJ `contains()` veya `isEqualTo()` kullanarak exception mesajlarının beklenen değerlerle eşleştiğini doğrulayın
|
||||
|
||||
### Test Coverage
|
||||
- Test happy paths for all public methods
|
||||
- Test null input handling
|
||||
- Test edge cases (empty collections, boundary values, negative IDs, blank strings)
|
||||
- Test exception scenarios comprehensively
|
||||
- Mock all external dependencies (repositories, services, Camel endpoints)
|
||||
- Aim for 80%+ line coverage, 70%+ branch coverage
|
||||
### Test Kapsamı
|
||||
- Tüm public metodlar için mutlu yolları test edin
|
||||
- Null girdi işlemeyi test edin
|
||||
- Edge case'leri test edin (boş koleksiyonlar, sınır değerleri, negatif ID'ler, boş string'ler)
|
||||
- Exception senaryolarını kapsamlı biçimde test edin
|
||||
- Tüm harici bağımlılıkları mock'layın (repository'ler, servisler, Camel endpoint'leri)
|
||||
- %80+ satır kapsamı, %70+ branch kapsamı hedefleyin
|
||||
|
||||
### Assertions
|
||||
- **Always use AssertJ** (`assertThat`) instead of JUnit assertions
|
||||
- Use fluent AssertJ API for readability: `assertThat(list).hasSize(3).contains(item)`
|
||||
- For exceptions: `assertThatThrownBy(() -> ...).isInstanceOf(...).hasMessageContaining(...)`
|
||||
- For collections: `extracting()`, `filteredOn()`, `containsExactly()`
|
||||
### Assertion'lar
|
||||
- JUnit assertion'ları yerine **her zaman AssertJ** (`assertThat`) kullanın
|
||||
- Okunabilirlik için akıcı AssertJ API'si kullanın: `assertThat(list).hasSize(3).contains(item)`
|
||||
- Exception'lar için: `assertThatThrownBy(() -> ...).isInstanceOf(...).hasMessageContaining(...)`
|
||||
- Koleksiyonlar için: `extracting()`, `filteredOn()`, `containsExactly()`
|
||||
|
||||
### Testing Integration
|
||||
- Use `@QuarkusTest` for integration tests
|
||||
- Use `@InjectMock` to mock dependencies in Quarkus tests
|
||||
- Prefer REST Assured for API testing
|
||||
- Use `@TestProfile` for test-specific configuration
|
||||
### Entegrasyon Testi
|
||||
- Entegrasyon testleri için `@QuarkusTest` kullanın
|
||||
- Quarkus testlerinde bağımlılıkları mock'lamak için `@InjectMock` kullanın
|
||||
- API testi için REST Assured'ı tercih edin
|
||||
- Test'e özel yapılandırma için `@TestProfile` kullanın
|
||||
|
||||
### Event-Driven Testing
|
||||
- Test Camel routes with `AdviceWith` and `MockEndpoint`
|
||||
- Use `@CamelQuarkusTest` annotation (if using standalone Camel tests)
|
||||
- Verify message content, headers, and routing logic
|
||||
- Test error handling routes separately
|
||||
- Mock external systems (RabbitMQ, S3, databases) in unit tests
|
||||
### Event-Driven Test
|
||||
- `AdviceWith` ve `MockEndpoint` ile Camel route'larını test edin
|
||||
- `@CamelQuarkusTest` annotasyonu kullanın (bağımsız Camel testleri kullanıyorsanız)
|
||||
- Mesaj içeriğini, başlıklarını ve yönlendirme mantığını doğrulayın
|
||||
- Hata işleme route'larını ayrı ayrı test edin
|
||||
- Unit testlerde harici sistemleri (RabbitMQ, S3, veritabanları) mock'layın
|
||||
|
||||
### Camel Route Testing
|
||||
- Use `MockEndpoint` for asserting message flow
|
||||
- Use `AdviceWith` to modify routes for testing (replace endpoints with mocks)
|
||||
- Test message transformation and marshalling
|
||||
- Test exception handling and dead letter queues
|
||||
### Camel Route Testi
|
||||
- Mesaj akışını doğrulamak için `MockEndpoint` kullanın
|
||||
- Test için route'ları değiştirmek üzere `AdviceWith` kullanın (endpoint'leri mock'larla değiştirin)
|
||||
- Mesaj dönüşümünü ve marshalling'i test edin
|
||||
- Exception işleme ve dead letter queue'ları test edin
|
||||
|
||||
### Testing Async Operations
|
||||
- Test CompletableFuture success and failure scenarios
|
||||
- Use `.join()` in tests to wait for async completion
|
||||
- Test exception propagation from CompletableFuture
|
||||
- Verify LogContext propagation to async operations
|
||||
### Async İşlem Testi
|
||||
- CompletableFuture başarı ve başarısızlık senaryolarını test edin
|
||||
- Async tamamlanmayı beklemek için testlerde `.join()` kullanın
|
||||
- CompletableFuture'dan exception yayılımını test edin
|
||||
- LogContext yayılımını async işlemlere doğrulayın
|
||||
|
||||
### Performance
|
||||
- Keep tests fast and isolated
|
||||
- Run tests in continuous mode: `mvn quarkus:test`
|
||||
- Use parameterized tests (`@ParameterizedTest`) for input variations
|
||||
- Build reusable test data builders or factory methods
|
||||
### Performans
|
||||
- Testleri hızlı ve izole tutun
|
||||
- Testleri sürekli modda çalıştırın: `mvn quarkus:test`
|
||||
- Girdi varyasyonları için parametreli testler (`@ParameterizedTest`) kullanın
|
||||
- Yeniden kullanılabilir test verisi builder'ları veya factory metodları oluşturun
|
||||
|
||||
### Quarkus-Specific
|
||||
- Stay on latest LTS version (Quarkus 3.x)
|
||||
- Test native compilation compatibility periodically
|
||||
- Use Quarkus test profiles for different scenarios
|
||||
- Leverage Quarkus dev services for local testing
|
||||
- Use `@InjectMock` instead of `@MockBean` (Quarkus-specific)
|
||||
### Quarkus'a Özgü
|
||||
- En son LTS sürümünde kalın (Quarkus 3.x)
|
||||
- Native derleme uyumluluğunu periyodik olarak test edin
|
||||
- Farklı senaryolar için Quarkus test profillerini kullanın
|
||||
- Yerel test için Quarkus dev servislerinden yararlanın
|
||||
- `@MockBean` yerine `@InjectMock` kullanın (Quarkus'a özgü)
|
||||
|
||||
### Verification Best Practices
|
||||
- Always verify interactions on mocked dependencies
|
||||
- Use `verify(mock, never())` to ensure methods are NOT called in error scenarios
|
||||
- Use `argThat()` for complex argument matching
|
||||
- Verify the order of calls when it matters: `InOrder` from Mockito
|
||||
### Doğrulama En İyi Uygulamaları
|
||||
- Mock'lanmış bağımlılıklardaki etkileşimleri her zaman doğrulayın
|
||||
- Hata senaryolarında metodların ÇAĞRILMADIĞINI sağlamak için `verify(mock, never())` kullanın
|
||||
- Karmaşık argüman eşleştirme için `argThat()` kullanın
|
||||
- Önem taşıdığında çağrı sırasını doğrulayın: Mockito'dan `InOrder`
|
||||
|
||||
@@ -4,22 +4,20 @@ description: "Verification loop for Quarkus projects: build, static analysis, te
|
||||
origin: ECC
|
||||
---
|
||||
|
||||
> **Not / Note**: Bu dosya henuz Turkceye cevrilmemistir, su anda Ingilizce orijinaldir. Ceviri PR'lari memnuniyetle karsilanir.
|
||||
# Quarkus Doğrulama Döngüsü
|
||||
|
||||
# Quarkus Verification Loop
|
||||
PR'lardan önce, büyük değişikliklerden sonra ve deployment öncesi çalıştırın.
|
||||
|
||||
Run before PRs, after major changes, and pre-deploy.
|
||||
## Ne Zaman Aktif Edilir
|
||||
|
||||
## When to Activate
|
||||
- Quarkus servisi için pull request açmadan önce
|
||||
- Büyük refactoring veya bağımlılık yükseltmelerinden sonra
|
||||
- Staging veya production için deployment öncesi doğrulama
|
||||
- Tam build → lint → test → güvenlik taraması → native derleme pipeline'ı çalıştırma
|
||||
- Test kapsamının eşikleri karşıladığını doğrulama (%80+)
|
||||
- Native image uyumluluğunu test etme
|
||||
|
||||
- Before opening a pull request for a Quarkus service
|
||||
- After major refactoring or dependency upgrades
|
||||
- Pre-deployment verification for staging or production
|
||||
- Running full build → lint → test → security scan → native compilation pipeline
|
||||
- Validating test coverage meets thresholds (80%+)
|
||||
- Testing native image compatibility
|
||||
|
||||
## Phase 1: Build
|
||||
## Faz 1: Build
|
||||
|
||||
```bash
|
||||
# Maven
|
||||
@@ -29,9 +27,9 @@ mvn clean verify -DskipTests
|
||||
./gradlew clean assemble -x test
|
||||
```
|
||||
|
||||
If build fails, stop and fix compilation errors.
|
||||
Build başarısız olursa, durdurun ve derleme hatalarını düzeltin.
|
||||
|
||||
## Phase 2: Static Analysis
|
||||
## Faz 2: Static Analiz
|
||||
|
||||
### Checkstyle, PMD, SpotBugs (Maven)
|
||||
|
||||
@@ -39,7 +37,7 @@ If build fails, stop and fix compilation errors.
|
||||
mvn checkstyle:check pmd:check spotbugs:check
|
||||
```
|
||||
|
||||
### SonarQube (if configured)
|
||||
### SonarQube (yapılandırılmışsa)
|
||||
|
||||
```bash
|
||||
mvn sonar:sonar \
|
||||
@@ -48,33 +46,33 @@ mvn sonar:sonar \
|
||||
-Dsonar.login=${SONAR_TOKEN}
|
||||
```
|
||||
|
||||
### Common Issues to Address
|
||||
### Ele Alınacak Yaygın Sorunlar
|
||||
|
||||
- Unused imports or variables
|
||||
- Complex methods (high cyclomatic complexity)
|
||||
- Potential null pointer dereferences
|
||||
- Security issues flagged by SpotBugs
|
||||
- Kullanılmayan import'lar veya değişkenler
|
||||
- Karmaşık metodlar (yüksek cyclomatic complexity)
|
||||
- Potansiyel null pointer dereference'ları
|
||||
- SpotBugs tarafından işaretlenen güvenlik sorunları
|
||||
|
||||
## Phase 3: Tests + Coverage
|
||||
## Faz 3: Testler + Kapsam
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
# Tüm testleri çalıştır
|
||||
mvn clean test
|
||||
|
||||
# Generate coverage report
|
||||
# Kapsam raporu oluştur
|
||||
mvn jacoco:report
|
||||
|
||||
# Enforce coverage threshold (80%)
|
||||
# Kapsam eşiğini zorla (%80)
|
||||
mvn jacoco:check
|
||||
|
||||
# Or with Gradle
|
||||
# Veya Gradle ile
|
||||
./gradlew test jacocoTestReport jacocoTestCoverageVerification
|
||||
```
|
||||
|
||||
### Test Categories
|
||||
### Test Kategorileri
|
||||
|
||||
#### Unit Tests
|
||||
Test service logic with mocked dependencies:
|
||||
#### Unit Testler
|
||||
Mock'lanmış bağımlılıklarla servis mantığını test edin:
|
||||
|
||||
```java
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@@ -99,8 +97,8 @@ class UserServiceTest {
|
||||
}
|
||||
```
|
||||
|
||||
#### Integration Tests
|
||||
Test with real database (Testcontainers):
|
||||
#### Entegrasyon Testleri
|
||||
Gerçek veritabanıyla (Testcontainers) test edin:
|
||||
|
||||
```java
|
||||
@QuarkusTest
|
||||
@@ -126,8 +124,8 @@ class UserRepositoryIntegrationTest {
|
||||
}
|
||||
```
|
||||
|
||||
#### API Tests
|
||||
Test REST endpoints with REST Assured:
|
||||
#### API Testleri
|
||||
REST Assured ile REST endpoint'lerini test edin:
|
||||
|
||||
```java
|
||||
@QuarkusTest
|
||||
@@ -160,34 +158,34 @@ class UserResourceTest {
|
||||
}
|
||||
```
|
||||
|
||||
### Coverage Report
|
||||
### Kapsam Raporu
|
||||
|
||||
Check `target/site/jacoco/index.html` for detailed coverage:
|
||||
- Overall line coverage (target: 80%+)
|
||||
- Branch coverage (target: 70%+)
|
||||
- Identify uncovered critical paths
|
||||
Ayrıntılı kapsam için `target/site/jacoco/index.html` sayfasını kontrol edin:
|
||||
- Genel satır kapsamı (hedef: %80+)
|
||||
- Branch kapsamı (hedef: %70+)
|
||||
- Kapsanmamış kritik yolları belirleyin
|
||||
|
||||
## Phase 4: Security Scanning
|
||||
## Faz 4: Güvenlik Taraması
|
||||
|
||||
### Dependency Vulnerabilities (Maven)
|
||||
### Bağımlılık Güvenlik Açıkları (Maven)
|
||||
|
||||
```bash
|
||||
mvn org.owasp:dependency-check-maven:check
|
||||
```
|
||||
|
||||
Review `target/dependency-check-report.html` for CVEs.
|
||||
CVE'ler için `target/dependency-check-report.html` raporunu inceleyin.
|
||||
|
||||
### Quarkus Security Audit
|
||||
### Quarkus Güvenlik Denetimi
|
||||
|
||||
```bash
|
||||
# Check vulnerable extensions
|
||||
# Güvenlik açığı olan extension'ları kontrol et
|
||||
mvn quarkus:audit
|
||||
|
||||
# List all extensions
|
||||
# Tüm extension'ları listele
|
||||
mvn quarkus:list-extensions
|
||||
```
|
||||
|
||||
### OWASP ZAP (API Security Testing)
|
||||
### OWASP ZAP (API Güvenlik Testi)
|
||||
|
||||
```bash
|
||||
docker run -t owasp/zap2docker-stable zap-api-scan.py \
|
||||
@@ -195,52 +193,52 @@ docker run -t owasp/zap2docker-stable zap-api-scan.py \
|
||||
-f openapi
|
||||
```
|
||||
|
||||
### Common Security Checks
|
||||
### Yaygın Güvenlik Kontrolleri
|
||||
|
||||
- [ ] All secrets in environment variables (not in code)
|
||||
- [ ] Input validation on all endpoints
|
||||
- [ ] Authentication/authorization configured
|
||||
- [ ] CORS properly configured
|
||||
- [ ] Security headers set
|
||||
- [ ] Passwords hashed with BCrypt
|
||||
- [ ] SQL injection protection (parameterized queries)
|
||||
- [ ] Rate limiting on public endpoints
|
||||
- [ ] Tüm gizli bilgiler ortam değişkenlerinde (kodda değil)
|
||||
- [ ] Tüm endpoint'lerde girdi doğrulama
|
||||
- [ ] Kimlik doğrulama/yetkilendirme yapılandırılmış
|
||||
- [ ] CORS düzgün yapılandırılmış
|
||||
- [ ] Güvenlik başlıkları ayarlanmış
|
||||
- [ ] Parolalar BCrypt ile hash'lenmiş
|
||||
- [ ] SQL injection koruması (parametreli sorgular)
|
||||
- [ ] Genel endpoint'lerde rate limiting
|
||||
|
||||
## Phase 5: Native Compilation
|
||||
## Faz 5: Native Derleme
|
||||
|
||||
Test GraalVM native image compatibility:
|
||||
GraalVM native image uyumluluğunu test edin:
|
||||
|
||||
```bash
|
||||
# Build native executable
|
||||
# Native executable oluştur
|
||||
mvn package -Dnative
|
||||
|
||||
# Or with container
|
||||
# Veya container ile
|
||||
mvn package -Dnative -Dquarkus.native.container-build=true
|
||||
|
||||
# Test native executable
|
||||
# Native executable'ı test et
|
||||
./target/*-runner
|
||||
|
||||
# Run basic smoke tests
|
||||
# Temel smoke testleri çalıştır
|
||||
curl http://localhost:8080/q/health/live
|
||||
curl http://localhost:8080/q/health/ready
|
||||
```
|
||||
|
||||
### Native Image Troubleshooting
|
||||
### Native Image Sorun Giderme
|
||||
|
||||
Common issues:
|
||||
- **Reflection**: Add reflection config for dynamic classes
|
||||
- **Resources**: Include resources with `quarkus.native.resources.includes`
|
||||
- **JNI**: Register JNI classes if using native libraries
|
||||
Yaygın sorunlar:
|
||||
- **Reflection**: Dinamik sınıflar için reflection yapılandırması ekleyin
|
||||
- **Resources**: `quarkus.native.resources.includes` ile kaynakları dahil edin
|
||||
- **JNI**: Native kütüphaneler kullanıyorsanız JNI sınıflarını kaydedin
|
||||
|
||||
Example reflection config:
|
||||
Örnek reflection yapılandırması:
|
||||
```java
|
||||
@RegisterForReflection(targets = {MyDynamicClass.class})
|
||||
public class ReflectionConfiguration {}
|
||||
```
|
||||
|
||||
## Phase 6: Performance Testing
|
||||
## Faz 6: Performans Testi
|
||||
|
||||
### Load Testing with K6
|
||||
### K6 ile Yük Testi
|
||||
|
||||
```javascript
|
||||
// load-test.js
|
||||
@@ -264,20 +262,20 @@ export default function () {
|
||||
}
|
||||
```
|
||||
|
||||
Run:
|
||||
Çalıştırın:
|
||||
```bash
|
||||
k6 run load-test.js
|
||||
```
|
||||
|
||||
### Metrics to Monitor
|
||||
### İzlenecek Metrikler
|
||||
|
||||
- Response time (p50, p95, p99)
|
||||
- Throughput (requests/sec)
|
||||
- Error rate
|
||||
- Memory usage
|
||||
- CPU usage
|
||||
- Yanıt süresi (p50, p95, p99)
|
||||
- Throughput (istek/saniye)
|
||||
- Hata oranı
|
||||
- Bellek kullanımı
|
||||
- CPU kullanımı
|
||||
|
||||
## Phase 7: Health Checks
|
||||
## Faz 7: Sağlık Kontrolleri
|
||||
|
||||
```bash
|
||||
# Liveness
|
||||
@@ -286,14 +284,14 @@ curl http://localhost:8080/q/health/live
|
||||
# Readiness
|
||||
curl http://localhost:8080/q/health/ready
|
||||
|
||||
# All health checks
|
||||
# Tüm sağlık kontrolleri
|
||||
curl http://localhost:8080/q/health
|
||||
|
||||
# Metrics (if enabled)
|
||||
# Metrikler (etkinleştirilmişse)
|
||||
curl http://localhost:8080/q/metrics
|
||||
```
|
||||
|
||||
Expected responses:
|
||||
Beklenen yanıtlar:
|
||||
```json
|
||||
{
|
||||
"status": "UP",
|
||||
@@ -306,24 +304,24 @@ Expected responses:
|
||||
}
|
||||
```
|
||||
|
||||
## Phase 8: Container Image Build
|
||||
## Faz 8: Container Image Build
|
||||
|
||||
```bash
|
||||
# Build container image
|
||||
# Container image oluştur
|
||||
mvn package -Dquarkus.container-image.build=true
|
||||
|
||||
# Or with specific registry
|
||||
# Veya belirli registry ile
|
||||
mvn package \
|
||||
-Dquarkus.container-image.build=true \
|
||||
-Dquarkus.container-image.registry=docker.io \
|
||||
-Dquarkus.container-image.group=myorg \
|
||||
-Dquarkus.container-image.tag=1.0.0
|
||||
|
||||
# Test container
|
||||
# Container'ı test et
|
||||
docker run -p 8080:8080 myorg/my-quarkus-app:1.0.0
|
||||
```
|
||||
|
||||
### Container Security Scan
|
||||
### Container Güvenlik Taraması
|
||||
|
||||
```bash
|
||||
# Trivy
|
||||
@@ -333,103 +331,103 @@ trivy image myorg/my-quarkus-app:1.0.0
|
||||
grype myorg/my-quarkus-app:1.0.0
|
||||
```
|
||||
|
||||
## Phase 9: Configuration Validation
|
||||
## Faz 9: Yapılandırma Doğrulama
|
||||
|
||||
```bash
|
||||
# Check all configuration properties
|
||||
# Tüm yapılandırma özelliklerini kontrol et
|
||||
mvn quarkus:info
|
||||
|
||||
# List all config sources
|
||||
# Tüm yapılandırma kaynaklarını listele
|
||||
curl http://localhost:8080/q/dev/io.quarkus.quarkus-vertx-http/config
|
||||
```
|
||||
|
||||
### Environment-Specific Checks
|
||||
### Ortama Özgü Kontroller
|
||||
|
||||
- [ ] Database URLs configured per environment
|
||||
- [ ] Secrets externalized (Vault, env vars)
|
||||
- [ ] Logging levels appropriate
|
||||
- [ ] CORS origins set correctly
|
||||
- [ ] Rate limiting configured
|
||||
- [ ] Monitoring/tracing enabled
|
||||
- [ ] Veritabanı URL'leri ortam başına yapılandırılmış
|
||||
- [ ] Gizli bilgiler dışsallaştırılmış (Vault, ortam değişkenleri)
|
||||
- [ ] Loglama seviyeleri uygun
|
||||
- [ ] CORS origin'leri doğru ayarlanmış
|
||||
- [ ] Rate limiting yapılandırılmış
|
||||
- [ ] İzleme/tracing etkinleştirilmiş
|
||||
|
||||
## Phase 10: Documentation Review
|
||||
## Faz 10: Dokümantasyon İncelemesi
|
||||
|
||||
- [ ] OpenAPI/Swagger docs up to date (`/q/swagger-ui`)
|
||||
- [ ] README has setup instructions
|
||||
- [ ] API changes documented
|
||||
- [ ] Migration guide for breaking changes
|
||||
- [ ] Configuration properties documented
|
||||
- [ ] OpenAPI/Swagger dokümanları güncel (`/q/swagger-ui`)
|
||||
- [ ] README kurulum talimatlarını içeriyor
|
||||
- [ ] API değişiklikleri belgelenmiş
|
||||
- [ ] Breaking change'ler için migration rehberi
|
||||
- [ ] Yapılandırma özellikleri belgelenmiş
|
||||
|
||||
Generate OpenAPI spec:
|
||||
OpenAPI spec oluşturun:
|
||||
```bash
|
||||
curl http://localhost:8080/q/openapi -o openapi.json
|
||||
```
|
||||
|
||||
## Verification Checklist
|
||||
## Doğrulama Kontrol Listesi
|
||||
|
||||
### Code Quality
|
||||
- [ ] Build passes without warnings
|
||||
- [ ] Static analysis clean (no high/medium issues)
|
||||
- [ ] Code follows team conventions
|
||||
- [ ] No commented-out code or TODOs in PR
|
||||
### Kod Kalitesi
|
||||
- [ ] Build uyarısız geçiyor
|
||||
- [ ] Static analiz temiz (yüksek/orta sorun yok)
|
||||
- [ ] Kod ekip kurallarını takip ediyor
|
||||
- [ ] PR'da yorum satırına alınmış kod veya TODO yok
|
||||
|
||||
### Testing
|
||||
- [ ] All tests pass
|
||||
- [ ] Code coverage ≥ 80%
|
||||
- [ ] Integration tests with real database
|
||||
- [ ] Security tests pass
|
||||
- [ ] Performance within acceptable limits
|
||||
### Test
|
||||
- [ ] Tüm testler geçiyor
|
||||
- [ ] Kod kapsamı ≥ %80
|
||||
- [ ] Gerçek veritabanıyla entegrasyon testleri
|
||||
- [ ] Güvenlik testleri geçiyor
|
||||
- [ ] Performans kabul edilebilir sınırlar içinde
|
||||
|
||||
### Security
|
||||
- [ ] No dependency vulnerabilities
|
||||
- [ ] Authentication/authorization tested
|
||||
- [ ] Input validation complete
|
||||
- [ ] Secrets not in source code
|
||||
- [ ] Security headers configured
|
||||
### Güvenlik
|
||||
- [ ] Bağımlılık güvenlik açığı yok
|
||||
- [ ] Kimlik doğrulama/yetkilendirme test edilmiş
|
||||
- [ ] Girdi doğrulama tamamlanmış
|
||||
- [ ] Gizli bilgiler kaynak kodda değil
|
||||
- [ ] Güvenlik başlıkları yapılandırılmış
|
||||
|
||||
### Deployment
|
||||
- [ ] Native compilation successful
|
||||
- [ ] Container image builds
|
||||
- [ ] Health checks respond correctly
|
||||
- [ ] Configuration valid for target environment
|
||||
- [ ] Native derleme başarılı
|
||||
- [ ] Container image oluşturuluyor
|
||||
- [ ] Sağlık kontrolleri doğru yanıt veriyor
|
||||
- [ ] Hedef ortam için yapılandırma geçerli
|
||||
|
||||
### Native Image
|
||||
- [ ] Native executable builds
|
||||
- [ ] Native tests pass
|
||||
- [ ] Startup time < 100ms
|
||||
- [ ] Memory footprint acceptable
|
||||
- [ ] Native executable oluşturuluyor
|
||||
- [ ] Native testler geçiyor
|
||||
- [ ] Başlangıç süresi < 100ms
|
||||
- [ ] Bellek ayak izi kabul edilebilir
|
||||
|
||||
## Automated Verification Script
|
||||
## Otomatik Doğrulama Script'i
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
echo "=== Phase 1: Build ==="
|
||||
echo "=== Faz 1: Build ==="
|
||||
mvn clean verify -DskipTests
|
||||
|
||||
echo "=== Phase 2: Static Analysis ==="
|
||||
echo "=== Faz 2: Static Analiz ==="
|
||||
mvn checkstyle:check pmd:check spotbugs:check
|
||||
|
||||
echo "=== Phase 3: Tests + Coverage ==="
|
||||
echo "=== Faz 3: Testler + Kapsam ==="
|
||||
mvn test jacoco:report jacoco:check
|
||||
|
||||
echo "=== Phase 4: Security Scan ==="
|
||||
echo "=== Faz 4: Güvenlik Taraması ==="
|
||||
mvn org.owasp:dependency-check-maven:check
|
||||
|
||||
echo "=== Phase 5: Native Compilation ==="
|
||||
echo "=== Faz 5: Native Derleme ==="
|
||||
mvn package -Dnative -Dquarkus.native.container-build=true
|
||||
|
||||
echo "=== All Phases Complete ==="
|
||||
echo "Review reports:"
|
||||
echo " - Coverage: target/site/jacoco/index.html"
|
||||
echo " - Security: target/dependency-check-report.html"
|
||||
echo "=== Tüm Fazlar Tamamlandı ==="
|
||||
echo "Raporları inceleyin:"
|
||||
echo " - Kapsam: target/site/jacoco/index.html"
|
||||
echo " - Güvenlik: target/dependency-check-report.html"
|
||||
echo " - Native: target/*-runner"
|
||||
```
|
||||
|
||||
## CI/CD Integration
|
||||
## CI/CD Entegrasyonu
|
||||
|
||||
### GitHub Actions Example
|
||||
### GitHub Actions Örneği
|
||||
|
||||
```yaml
|
||||
name: Verification
|
||||
@@ -469,15 +467,15 @@ jobs:
|
||||
files: target/site/jacoco/jacoco.xml
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
## En İyi Uygulamalar
|
||||
|
||||
- Run verification loop before every PR
|
||||
- Automate in CI/CD pipeline
|
||||
- Fix issues immediately; don't accumulate debt
|
||||
- Keep coverage above 80%
|
||||
- Update dependencies regularly
|
||||
- Test native compilation periodically
|
||||
- Monitor performance trends
|
||||
- Document breaking changes
|
||||
- Review security scan results
|
||||
- Validate configuration for each environment
|
||||
- Her PR öncesi doğrulama döngüsünü çalıştırın
|
||||
- CI/CD pipeline'ında otomatize edin
|
||||
- Sorunları hemen düzeltin; borç biriktirmeyin
|
||||
- Kapsamı %80'in üzerinde tutun
|
||||
- Bağımlılıkları düzenli olarak güncelleyin
|
||||
- Native derlemeyi periyodik olarak test edin
|
||||
- Performans trendlerini izleyin
|
||||
- Breaking change'leri belgeleyin
|
||||
- Güvenlik tarama sonuçlarını inceleyin
|
||||
- Her ortam için yapılandırmayı doğrulayın
|
||||
|
||||
Reference in New Issue
Block a user