commit 7ca665397ee907b65a850b829384981a384a4c88 Author: kric_jspark Date: Mon Oct 12 12:37:45 2026 +0900 261012_01_FST: first commit diff --git a/.agent-harness/references/kri-common/crypto-contract.md b/.agent-harness/references/kri-common/crypto-contract.md new file mode 100644 index 0000000..fecaf7b --- /dev/null +++ b/.agent-harness/references/kri-common/crypto-contract.md @@ -0,0 +1,14 @@ + + +# KriCommon Crypto Contract + +- Crypto APIs are under `com.kri.common.feature.crypto.*` and do not use a central key database. +- AES uses PBKDF2-HMAC-SHA256 key derivation with salt and defaults to AES-256-GCM; callers may supply a master key, salt, IV, AAD, and detached or appended GCM tag representation for legacy interoperability. +- `kri.crypto.aes.keys` and per-call master keys are supported operational compromises. Never log them or commit real values. +- Per-call key material takes precedence over configured keys, and encrypted values retain key ID and KDF metadata for decryption compatibility. +- AES-GCM always requires its authentication tag. Use `AES_256_CBC_PKCS5` only for explicitly identified legacy data that has no tag, and do not treat CBC as authenticated encryption. +- `DigestService` supports SHA-256/SHA-512 plus legacy-only MD5/SHA-1. `AdaptiveHashService` uses BCrypt for short secrets; do not use MD5, SHA-1, or a fast digest for new password or secret storage. diff --git a/.agent-harness/references/kri-common/platform-capabilities.md b/.agent-harness/references/kri-common/platform-capabilities.md new file mode 100644 index 0000000..510ecac --- /dev/null +++ b/.agent-harness/references/kri-common/platform-capabilities.md @@ -0,0 +1,34 @@ + + +# KriCommon Platform Capabilities + +## Dependency and Configuration Boundary + +- Include the matching Spring starter for any optional Web, Security, JPA, Redis, AOP, or Swagger integration the service enables; KriCommon intentionally declares many integrations as compile-only. +- KriCommon configuration uses only `kri.*`. Established groups include `kri.auth.jwt`, `kri.auth.apikey`, `kri.crypto`, `kri.security`, `kri.swagger`, `kri.web`, `kri.web.mdc`, `kri.http.bypass`, `kri.redis`, `kri.scheduling`, and `kri.error.expose`. +- Read the version-matched README and configuration-property classes before setting a property; do not infer a property name or default from an older service. +- Supply production JWT secrets, API keys, credentials, allowlists, and service URLs through the consumer's approved secret and configuration system. Never rely on library example or default secrets in production. +- Preserve consumer override points. KriCommon's default security chain is created only when the consumer does not provide one, and overridable beans should remain explicit. +- Adding a path to API-key allowed paths scopes where API-key authentication is attempted; it does not make the path public or grant authorization. + +## Optional Capabilities + +- JWT and API-key authentication integrate with Spring Security. API-key JPA preload requires Spring Data JPA; a consumer-provided claims provider can be used without JPA. +- Common Web may register error handling, tracing/MDC, request-user resolution, enum conversion, and CORS behavior. Check for overlap before defining consumer-local equivalents. +- Swagger support requires springdoc and defines the shared Bearer/API-key schemes and grouped paths. +- Redis and scheduling are opt-in through their `kri.*.enabled` settings and matching runtime dependencies. +- HTTP bypass targets are server-configured. Never accept an arbitrary full target URL from a frontend; retain allowed-path checks and do not forward hop-by-hop headers. +- The external API client returns response bodies as documented, while bypass responses preserve raw bytes and target `Content-Type`. +- Bypass filters all HTTP/2 pseudo headers (names starting with `:`) in addition to existing hop-by-hop headers; use the response status accessor instead of forwarding `:status`. +- `kri.http.bypass.targets..throw-on-error` defaults to `false`. When enabled, the final response after response customizers throws public `com.kri.common.feature.http.ExternalApiResponseException` for non-2xx status; existing targets retain response-return behavior by default. +- `BypassResponse.requireSuccess()` and `ExternalApiResponse.requireSuccess()` explicitly enforce the same non-2xx guard. `ExternalApiClient` keeps its existing default behavior and decoded `getBody()` API, and `getBodyBytes()` exposes a defensive copy of the original received bytes, including compressed and binary error bodies. +- A response customizer's `ExternalApiResponseException`, including one thrown by `requireSuccess()`, propagates unchanged; other customizer failures keep the existing `BYPASS_RESPONSE_CUSTOMIZE_FAILED` behavior. Response charset parsing ignores charset-like text inside other quoted `Content-Type` parameters and retains the UTF-8 fallback. +- With Spring MVC and Servlet API present and `kri.web.enabled=true` (default), `ExternalApiErrorAutoConfiguration` registers a handler for this dedicated exception before the general error advice. It relays the original status, body bytes, `Content-Type`, and `Content-Encoding`, including empty bodies; authentication, cookie, and transport headers are not relayed by the error handler. Enable this policy only for targets whose raw errors may be exposed to clients. Connection failures remain distinct from upstream HTTP errors. +- A consumer-provided error handler bean named `externalApiResponseAdvice` replaces the default without importing runtime types; explicitly caught/controller-handled exceptions also remain under the consumer's control. +- `ExternalApiClient` multipart requests generate their own boundary and ignore a caller-supplied `Content-Type`. Multipart headers and `formField` values use UTF-8, while file bodies preserve the supplied bytes. +- Multipart filenames, including non-ASCII names, are sent unchanged in the quoted `filename` parameter as raw UTF-8. No ASCII fallback or `filename*` parameter is added; CR/LF rejection and quote/backslash escaping still apply. +- `JsonUtil` requires the consumer's explicit `ObjectMapper`; shared date/time helpers define KST as `Asia/Seoul` and also expose UTC semantics. diff --git a/.agent-harness/references/kri-common/upgrade-and-verification.md b/.agent-harness/references/kri-common/upgrade-and-verification.md new file mode 100644 index 0000000..864a074 --- /dev/null +++ b/.agent-harness/references/kri-common/upgrade-and-verification.md @@ -0,0 +1,13 @@ + + +# KriCommon Upgrade and Verification + +- Review KriCommon release notes, README changes, configuration defaults, auto-configuration conditions, and affected public APIs before upgrading. +- Commit dependency-lock or resolved-version changes according to the consumer repository's policy. +- Run the consumer's focused compile and tests after an upgrade, including application-context startup tests when auto-configuration or security behavior is affected. +- Keep `.agent/project.md` near 2-3 KiB as a routing document. Do not delete material rules to meet the budget; move conditional schema, query, API, and migration details to routed `.agent/references/` documents. +- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope. diff --git a/.agent/profile.yml b/.agent/profile.yml new file mode 100644 index 0000000..b1f98a6 --- /dev/null +++ b/.agent/profile.yml @@ -0,0 +1,21 @@ +schema_version: 1 + +project: + id: kart-server + name: "kart-server" + type: internal-service + layer: backend + legacy: false + +stack: + - java-springboot + +shared_contracts: + consumes: + - kri-common + +databases: + - id: primary + engine: mssql + role: primary + access: read-write diff --git a/.agent/project.md b/.agent/project.md new file mode 100644 index 0000000..f0c761e --- /dev/null +++ b/.agent/project.md @@ -0,0 +1,18 @@ +# kart-server Project Instruction Router + +## Required Project References + +Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session. + +| Task scope | Required reference | +|---|---| +| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` | + +If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current. + +## Harness Workflow + +- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly. +- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`. +- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8. +- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source. diff --git a/.agent/references/repository-rules.md b/.agent/references/repository-rules.md new file mode 100644 index 0000000..9934c65 --- /dev/null +++ b/.agent/references/repository-rules.md @@ -0,0 +1,8 @@ +## Generated Spring Boot Repository Rules + +- This backend application was generated by `@kri/create-spring-app` with Java 17 and Spring Boot 3.5.7. +- Consume KriCommon through `com.kri.common:starter:beta.1.6.8`; do not change that approved version or duplicate shared behavior without explicit approval. +- The selected primary database is `mssql`. Preserve its configured dialect, driver, transaction, schema, and migration conventions. +- Keep controllers thin and preserve the generated service, DTO, persistence, configuration, QueryDSL, JDBC, and optional MyBatis boundaries. +- `AGENTS.md` and `CLAUDE.md` are central-harness generated outputs. Never edit them directly; update `.agent/profile.yml` or `.agent/project.md` and recompose. +- Use the repository Gradle Wrapper and run `.\gradlew.bat compileJava` followed by focused tests for relevant changes. diff --git a/.agents/skills/attention-aware-communication/SKILL.md b/.agents/skills/attention-aware-communication/SKILL.md new file mode 100644 index 0000000..e27dde4 --- /dev/null +++ b/.agents/skills/attention-aware-communication/SKILL.md @@ -0,0 +1,41 @@ +--- +name: attention-aware-communication +description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work. +--- + + +# Attention-Aware Communication + +This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires. + +## Default: Attention-kind + +- Put the bottom line in the first sentence and use plain Korean. +- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements. +- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly. +- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer. +- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections. +- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context. +- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe. + +## Progress and Completion: Rundown + +Use Rundown formatting when a task has multiple steps or mixed states: + +- Start with a one-line outcome that includes any blocker. +- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories. +- Put each blocker or material risk on its own line. +- Report only observed states. Mark an unknown as unknown and state what check would resolve it. +- End with the next action or a small numbered choice only when the user must decide. + +## Explicit-Only: Spartan + +Use Spartan style only when the user explicitly asks for it: + +- Lead with the complete answer in one sentence. +- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries. +- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer. +- If the user also asks for depth, provide the full detail in short, separated blocks. diff --git a/.agents/skills/karpathy-guidelines/SKILL.md b/.agents/skills/karpathy-guidelines/SKILL.md new file mode 100644 index 0000000..bbb7791 --- /dev/null +++ b/.agents/skills/karpathy-guidelines/SKILL.md @@ -0,0 +1,37 @@ +--- +name: karpathy-guidelines +description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria. +--- + + +# Karpathy Guidelines + +Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope. + +## Think Before Coding + +- Inspect the relevant code and repository conventions before choosing a solution. +- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope. +- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it. + +## Simplicity First + +- Implement the smallest complete solution that satisfies the observable requirement. +- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use. +- Prefer an existing repository pattern or standard-library capability over a new local framework. + +## Surgical Changes + +- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment. +- Preserve existing naming, structure, public behavior, and formatting outside that boundary. +- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing. + +## Goal-Driven Execution + +- Translate the request into observable success criteria before implementation. +- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate. +- Iterate only within the approved scope until the criteria pass or a concrete blocker is established. +- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence. diff --git a/.agents/skills/project-reference-loader/SKILL.md b/.agents/skills/project-reference-loader/SKILL.md new file mode 100644 index 0000000..febb5b7 --- /dev/null +++ b/.agents/skills/project-reference-loader/SKILL.md @@ -0,0 +1,29 @@ +--- +name: project-reference-loader +description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning. +--- + + +# Project Reference Loader + +Use the repository's generated `AGENTS.md` as the routing entrypoint. + +## Workflow + +1. Find the `Required Project References` and shared-contract reference routes that match the current task. +2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session. +3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist. +4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`. +5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing. + +## Change Handling + +- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository. +- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract. +- Never edit generated `.agent-harness/references/` copies directly. +- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does. + +Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations. diff --git a/.agents/skills/verification-before-completion/SKILL.md b/.agents/skills/verification-before-completion/SKILL.md new file mode 100644 index 0000000..05e21ed --- /dev/null +++ b/.agents/skills/verification-before-completion/SKILL.md @@ -0,0 +1,38 @@ +--- +name: verification-before-completion +description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish. +--- + + +# Verification Before Completion + +No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action. + +## Verification Gate + +Before making a success claim: + +1. State the exact claim internally and identify which observable check can prove or disprove it. +2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property. +3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes. +4. Compare the evidence with the claim and the approved acceptance criteria. +5. Report only the status supported by that evidence. + +## Evidence Rules + +- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements. +- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof. +- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files. +- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement. +- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim. +- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim. + +## Reporting + +- Cite the commands or inspections actually run and summarize their observed results. +- If a required check cannot run, state the actual incomplete or blocked status and the exact reason. +- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification. +- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved. diff --git a/.claude/skills/attention-aware-communication/SKILL.md b/.claude/skills/attention-aware-communication/SKILL.md new file mode 100644 index 0000000..e27dde4 --- /dev/null +++ b/.claude/skills/attention-aware-communication/SKILL.md @@ -0,0 +1,41 @@ +--- +name: attention-aware-communication +description: Shape substantive answers, progress updates, and completion reports for fast, accurate reading without reducing the underlying work. +--- + + +# Attention-Aware Communication + +This skill changes presentation only. Investigate, implement, and verify as deeply as the task requires. + +## Default: Attention-kind + +- Put the bottom line in the first sentence and use plain Korean. +- Say the least that fully answers, then stop. Remove preambles, padding, repetition, and closing restatements. +- Never omit a number, scope condition, risk, prerequisite, uncertainty, or other fact that could cause the user to act incorrectly. +- For genuine breadth, explain the one or two most important points first, name the remaining areas, and let the user choose whether to expand them. Do not use this to defer required caveats or a complete focused answer. +- When the user asks for a detailed explanation, walkthrough, rationale, or full picture, suspend brevity and provide the necessary detail in scannable sections. +- When asked for a deliverable such as a command, message, snippet, or commit text, return the deliverable without unnecessary framing unless safety or correctness requires context. +- Ask one blocking question at a time and put it last. Keep working when a non-blocking assumption is safe. + +## Progress and Completion: Rundown + +Use Rundown formatting when a task has multiple steps or mixed states: + +- Start with a one-line outcome that includes any blocker. +- Distinguish verified completion, work in progress, work not started, and unknown state. Omit empty categories. +- Put each blocker or material risk on its own line. +- Report only observed states. Mark an unknown as unknown and state what check would resolve it. +- End with the next action or a small numbered choice only when the user must decide. + +## Explicit-Only: Spartan + +Use Spartan style only when the user explicitly asks for it: + +- Lead with the complete answer in one sentence. +- Be terse, blunt, and direct; remove warmth, hedging, transitions, narration, and summaries. +- Keep all load-bearing facts, warnings, and conditions even when they make the answer longer. +- If the user also asks for depth, provide the full detail in short, separated blocks. diff --git a/.claude/skills/karpathy-guidelines/SKILL.md b/.claude/skills/karpathy-guidelines/SKILL.md new file mode 100644 index 0000000..bbb7791 --- /dev/null +++ b/.claude/skills/karpathy-guidelines/SKILL.md @@ -0,0 +1,37 @@ +--- +name: karpathy-guidelines +description: Keep implementation, refactoring, and code review assumption-aware, simple, surgical, and tied to verifiable success criteria. +--- + + +# Karpathy Guidelines + +Use these guidelines while implementing, refactoring, or reviewing code. They refine execution quality but do not expand the approved task scope. + +## Think Before Coding + +- Inspect the relevant code and repository conventions before choosing a solution. +- Surface an assumption when different choices would materially change behavior, compatibility, data, or scope. +- Ask only when the decision cannot be discovered safely and a reasonable assumption would be risky. Otherwise proceed with the smallest reasonable assumption and report it. + +## Simplicity First + +- Implement the smallest complete solution that satisfies the observable requirement. +- Do not add speculative abstractions, extension points, configuration, fallback paths, or dependencies for hypothetical future use. +- Prefer an existing repository pattern or standard-library capability over a new local framework. + +## Surgical Changes + +- Every changed line must trace to the approved objective, required validation, or a necessary compatibility adjustment. +- Preserve existing naming, structure, public behavior, and formatting outside that boundary. +- Do not mix the task with unrelated cleanup. Remove dead code, duplication, or ceremony introduced by the current change before finishing. + +## Goal-Driven Execution + +- Translate the request into observable success criteria before implementation. +- Choose the narrowest check that can fail for the behavior being changed, then run broader repository checks when appropriate. +- Iterate only within the approved scope until the criteria pass or a concrete blocker is established. +- Before reporting completion, inspect the final diff for unnecessary code and use `verification-before-completion` for fresh evidence. diff --git a/.claude/skills/project-reference-loader/SKILL.md b/.claude/skills/project-reference-loader/SKILL.md new file mode 100644 index 0000000..febb5b7 --- /dev/null +++ b/.claude/skills/project-reference-loader/SKILL.md @@ -0,0 +1,29 @@ +--- +name: project-reference-loader +description: Load the current project-specific and shared reference documents routed by AGENTS.md before substantive repository analysis, implementation, debugging, review, or planning. +--- + + +# Project Reference Loader + +Use the repository's generated `AGENTS.md` as the routing entrypoint. + +## Workflow + +1. Find the `Required Project References` and shared-contract reference routes that match the current task. +2. Read the current contents of every matching file before relying on remembered project behavior, even when the file was read earlier in the session. +3. If the task crosses multiple scopes, read every matching reference. Do not load unrelated references merely because they exist. +4. Treat routed references as binding project instructions within their stated scope. Resolve conflicts using the precedence rules in `AGENTS.md`. +5. If a required reference is missing, unreadable, outside the repository, or internally inconsistent, stop the affected work and report the exact problem instead of guessing. + +## Change Handling + +- Edit authored project detail under `.agent/references/` when the durable rule belongs only to that repository. +- Edit the provider's `.agent/consumer-references/` when the rule is part of a shared consumer contract. +- Never edit generated `.agent-harness/references/` copies directly. +- Changing `.agent/references/` does not require recomposing `AGENTS.md` when its route is unchanged; changing routing, `project.md`, `consumer.md`, or shared reference sources does. + +Before completion, confirm that the references used still exist and that the result does not contradict them. This skill does not expand authorization to edit, commit, push, deploy, connect to external systems, or perform destructive operations. diff --git a/.claude/skills/verification-before-completion/SKILL.md b/.claude/skills/verification-before-completion/SKILL.md new file mode 100644 index 0000000..05e21ed --- /dev/null +++ b/.claude/skills/verification-before-completion/SKILL.md @@ -0,0 +1,38 @@ +--- +name: verification-before-completion +description: Require fresh, claim-specific evidence before reporting work complete, fixed, passing, ready, or safe to commit or publish. +--- + + +# Verification Before Completion + +No completion claim without fresh evidence. This workflow verifies status; it does not authorize a commit, push, deployment, database operation, or other protected action. + +## Verification Gate + +Before making a success claim: + +1. State the exact claim internally and identify which observable check can prove or disprove it. +2. Run the relevant command or inspection fresh after the final change. Use repository-defined commands; do not invent a substitute that proves a different property. +3. Read the complete result needed for the claim, including the exit code, failure count, skipped checks, and generated changes. +4. Compare the evidence with the claim and the approved acceptance criteria. +5. Report only the status supported by that evidence. + +## Evidence Rules + +- A passing lint does not prove compilation, a passing build does not prove runtime behavior, and a passing narrow test does not prove unrelated requirements. +- For a regression test, establish that it is capable of detecting the defect when practical; do not treat an always-passing test as proof. +- Recheck the worktree or final diff after generators, formatters, tests, or builds that may create or alter files. +- Separate verified results, failures, checks not run, and pre-existing failures. Never quietly merge them into a success statement. +- For delegated work, inspect the returned changes and run the relevant verification yourself before accepting the completion claim. +- For absence or universal claims such as “no occurrences” or “all projects,” use a check whose scope actually covers the claim. + +## Reporting + +- Cite the commands or inspections actually run and summarize their observed results. +- If a required check cannot run, state the actual incomplete or blocked status and the exact reason. +- Do not use “should work,” “probably passes,” “seems correct,” or similar language as a substitute for verification. +- Do not claim completion while a required check is failing or while known correctness, encoding, security, or generated-output drift remains unresolved. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..63ad95f --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +/gradlew text eol=lf +*.bat text eol=crlf +*.jar binary +/AGENTS.md text eol=lf +/CLAUDE.md text eol=lf +/.agent/*.md text eol=lf +/.agent/**/*.md text eol=lf +/.agent/*.yml text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8ff615d --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/ +*.iws +*.iml +*.ipr +out/ + +### VS Code ### +.vscode/ + +### Logs / runtime files ### +logs/ +upload-file/ +*.log + +### OS ### +.DS_Store +Thumbs.db + +# Local environment files +.env +.env.* +!.env.example diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..e539f56 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,279 @@ + + +# KRI Development Base Instructions + +This document defines the shared working rules for KRI development repositories. +Keep project-specific facts and commands in the project profile and project rules. + +## Instruction Resolution + +Apply repository instructions in this order: + +1. Base rules +2. Project-type rules +3. Technology-stack rules +4. Shared consumer contracts +5. Project-specific rules +6. The explicitly approved task scope + +Later and more specific instructions may override earlier general instructions only within their stated scope. + +- Apply a shared consumer contract only when `.agent/profile.yml` declares it. +- Do not silently resolve a material instruction conflict. Report the conflicting rules and request a decision before changing files. +- Rules involving destructive actions, credentials, external systems, production, deployment, databases, or Git publication require explicit authorization even when a later rule is less restrictive. + +## Communication + +- Respond to the user in Korean unless the user requests another language. +- Keep code identifiers, commands, paths, protocol names, and external API terms in their original form. +- Follow the repository's existing language conventions for code comments and user-facing messages. +- Lead with the result or decision, then provide only the detail needed to verify it. +- Do not create or retain a full session transcript. + +### Attention-Aware Response Style + +- Use `attention-aware-communication` for substantive answers, progress updates, and completion reports. +- Default to concise, bottom-line-first Korean without omitting a condition, risk, number, or uncertainty needed for a correct decision. +- Give full detail when the user requests depth. Use Spartan style only when explicitly requested. +- Presentation rules never reduce investigation, implementation, validation, or reporting obligations. + +## Work Authorization + +- The default workflow is discussion first and explicit execution approval second. +- During discussion, perform only read-only investigation needed to understand the task and propose a concrete plan, unless the user prohibits inspection. +- Read-only investigation may include file inspection, code search, encoding checks, `git status`, `git diff`, `git log`, and sanitized official-documentation lookup. +- Before execution approval, do not edit files, install dependencies, run builds or tests, start services, connect to databases, or change local or external state. +- Before requesting approval, describe the intended scope, affected areas, validation plan, and material risks. +- Treat approval as limited to the presented scope. Pause and discuss again if the work materially expands. +- If the user explicitly requests immediate execution without prior discussion, the discussion gate may be skipped for the stated scope. +- Fast-track authorization does not implicitly authorize protected operations such as destructive commands, production changes, deployments, database mutations, Git publication, or external messages. + +## Local Development Environment + +- Primary OS: Windows 11. +- Primary shell: PowerShell. +- Use Git Bash only when the repository already depends on Bash or POSIX shell behavior. +- Prefer repository-provided wrappers and scripts over globally installed commands. +- Do not assume that GNU utilities, WSL, Docker, or a Unix-compatible shell are available unless the project profile confirms them. +- Detect Java, Node.js, .NET, Python, package-manager, and database-tool versions from repository configuration. +- Do not install or modify global toolchains as part of a project task. + +Preferred human-facing tools: + +- Classic ASP: Visual Studio Code +- Java and Spring Boot: IntelliJ IDEA +- C# and .NET: JetBrains Rider +- JavaScript, TypeScript, and Next.js: JetBrains WebStorm +- Python: JetBrains PyCharm +- Microsoft SQL Server: SQL Server Management Studio +- Other databases: JetBrains DataGrip + +- These preferences do not authorize launching or controlling a GUI application. +- Prefer IDE-independent commands that can also run in CI. +- Do not modify global IDE settings. +- Do not create or modify `.idea`, `.vscode`, workspace, or run-configuration files unless the approved task requires it. +- Preserve existing shared IDE configuration when it is already tracked. + +## PowerShell and Path Safety + +- Quote paths containing spaces, brackets, parentheses, Korean characters, or PowerShell metacharacters. +- Prefer `-LiteralPath` when operating on an exact filesystem path. +- Use project-relative paths in committed configuration and documentation. Do not commit machine-specific paths such as `D:\_____Dev\...`. +- Do not pass filesystem targets between PowerShell, `cmd.exe`, and Bash for destructive or recursive operations. +- Keep a filesystem operation within one shell from target resolution through execution. +- Before a recursive delete or move, resolve and verify every absolute target. +- Never use a drive root, workspace root, user profile, unresolved variable, wildcard, or broad glob as a recursive delete target. +- Prefer recoverable operations when practical. + +## Change Discipline + +- Preserve all existing user changes, including uncommitted and untracked work. +- Keep changes minimal but complete for the approved objective. +- Avoid unrelated cleanup, formatting, renaming, dependency upgrades, and architectural refactoring. +- Do not overwrite or revert unrelated changes. +- Stop and report when the requested change overlaps existing work in a way that cannot be handled safely. +- Prefer changing an authoritative source over editing generated output. +- Treat files marked as generated as read-only unless regeneration is part of the approved plan. +- Do not edit vendored dependencies, build outputs, caches, or generated clients unless explicitly required. +- Do not regenerate a broad set of files for a narrow change without first explaining the expected output scope. + +## Text Encoding and Korean Content Safety + +- Treat the existing file encoding, BOM state, and line-ending style as part of the file's contract. +- Preserve Korean comments, user-facing messages, error messages, identifiers, and documentation exactly unless the task explicitly requires changing them. +- Do not assume that garbled terminal output means the file itself is corrupted. Verify bytes and encoding before modifying suspicious text. +- Before editing an existing text file, determine its current encoding and BOM state when repository configuration does not already guarantee them. +- Do not convert encoding, add or remove a BOM, or normalize line endings as a side effect of an unrelated change. +- Avoid whole-file rewrites for small changes. +- Do not rewrite source files through `Get-Content | Set-Content`, `Out-File`, shell redirection, or another method whose encoding behavior is implicit. +- Do not use a patching or formatting tool on a non-UTF-8 file unless it is known to preserve that file's encoding. +- Treat a console display problem and an on-disk encoding problem as separate issues. +- After editing Korean text, inspect the diff for replacement characters (`�`), mojibake, unexpected escapes, BOM changes, and unrelated line-ending changes. +- Run `.agent/tools/check-encoding.ps1` when it is available and the change touches Korean text or a non-default encoding. +- If encoding cannot be identified confidently, stop before writing and report the affected file and evidence. +- For a new text file, follow repository configuration. If no rule exists, use UTF-8 without BOM. + +## Git Safety + +- Use `git status`, `git diff`, and `git log` for read-only investigation. +- Do not run `commit`, `push`, `pull`, `fetch`, `merge`, `rebase`, `reset`, `checkout`, `switch`, `stash`, `clean`, `tag`, or force operations unless that specific operation is explicitly approved. +- Source-edit approval does not include commit or push approval. +- Never amend an existing commit unless explicitly requested. +- Before an approved commit, show the intended files, validation results, and proposed commit message. +- Never push directly to a protected branch unless the user names the target branch and explicitly authorizes the push. + +## Dependencies and External Actions + +- Use the package manager, lockfile, and toolchain already selected by the repository. +- Do not install global packages. +- Do not add, remove, or upgrade a dependency unless it was included in the approved plan. +- Pause for approval if an unplanned dependency becomes necessary. +- Keep lockfiles synchronized with approved dependency changes. +- Do not deploy, publish packages, create releases, send messages or email, call business APIs, or modify external services unless explicitly requested. +- Never upload proprietary source code, internal documents, credentials, customer data, or database contents to an external service. +- Remove secrets and unnecessary internal identifiers from external search queries. + +## Database Safety + +- Treat writing or reviewing SQL as source code separately from executing SQL against a database. +- SQL files, migrations, schema proposals, and query drafts may be created within an approved source-change scope. +- Do not connect to a shared, staging, or production database without explicit authorization for that environment. +- Read-only queries against a non-local database also require authorization because results may contain sensitive data. +- Do not execute DDL, DML, stored procedures, migrations, administrative commands, or data-correction scripts against a non-disposable database without separate authorization for the exact target and operation. +- Source-change approval does not authorize migration execution. +- Use a disposable local or test database for approved validation only after verifying its identity and disposable nature. +- Never place credentials, connection strings, or sensitive query results in source files, logs, generated documents, or chat output. + +## Secrets and Sensitive Data + +- Never add credentials, tokens, passwords, private keys, connection strings, session identifiers, or production data to source control. +- Read sensitive files only when the approved task requires it and no safer source exists. +- Prefer inspecting configuration keys and schemas without displaying secret values. +- Never echo secrets into terminal output, chat responses, logs, diffs, generated documents, test fixtures, or screenshots. +- Redact sensitive values when reporting errors or command output. +- If a possible secret is discovered, do not repeat it. Report only its location, type, and recommended containment action. +- Do not rotate, revoke, copy, or otherwise modify credentials unless that exact action is explicitly authorized. + +## Workflow Skills + +- Use `project-reference-loader` before substantive repository analysis, planning, implementation, debugging, or review. Read only the current project and shared references routed for that task, and reread them for each related task even if they were loaded earlier in the session. +- Use `karpathy-guidelines` when implementing, refactoring, or reviewing code. It keeps assumptions visible, changes surgical, and success criteria verifiable. +- Use `verification-before-completion` before claiming that work is complete, fixed, passing, ready, or safe to commit or publish. +- A skill does not expand task scope or authorize Git publication, database execution, deployment, destructive actions, or external communication. + +## Validation + +- Discover supported build, test, lint, type-check, and formatting commands from repository files and project instructions. Do not invent commands. +- Include intended validation in the discussion-phase plan. +- After approved changes, run the narrowest relevant validation first, then broader checks when appropriate. +- Limit formatting to files within the approved scope. +- Do not run tests that require a shared database, production service, paid external API, or sensitive data unless separately authorized. +- Do not claim that a check passed unless it was executed successfully. +- If a check cannot be run, state the exact reason. +- Distinguish a current-change failure from a pre-existing failure or an undetermined failure. +- Do not fix unrelated failures without expanding the approved scope. +- Inspect the worktree after validation for unexpected generated files, formatting churn, encoding changes, or lockfile changes. + +## Artifacts and Session Records + +- Do not create full-session transcripts, automatic HTML copies, analysis reports, or extra documentation unless explicitly requested. +- Store durable information in the repository's existing documentation structure. +- Do not place generated reports or temporary analysis files in the repository root. +- Remove task-specific temporary files created by the current task after validation when removal is safe. + +## Completion Report + +When implementation is complete, report in Korean: + +- what changed and why; +- the main affected files or components; +- validation commands actually executed and their results; +- checks not executed and the reason; +- remaining risks, assumptions, or follow-up work; +- database, deployment, dependency, encoding, and compatibility impact when applicable. + +- Do not report completion while required validation is failing or known encoding corruption is unresolved. +- Keep the report concise and do not include a full session transcript. + +## Internal Service Project Rules + +- Internal-only usage does not reduce security, privacy, compatibility, or validation requirements. +- Preserve authentication, authorization, role boundaries, auditability, and personal-data protections. +- Identify affected user workflows before changing visible behavior. +- Treat Frontend and Backend repositories as separate deployable systems with an explicit API contract between them. +- Coordinate request, response, authentication, error, and versioning changes across both sides when the approved scope includes both repositories. +- Do not silently require a simultaneous Frontend and Backend deployment. +- Prefer backward-compatible transitions when deployments may occur independently. +- Include migration and rollback considerations for database, API, and configuration changes. +- Do not modernize legacy code as an unrelated side effect. +- Apply Classic ASP text-safety rules only when the project profile declares the `classic-asp` stack. +- Do not access or modify production data merely because the service is internal. + +## Java and Spring Boot + +- Treat the configured JDK, Spring Boot, Gradle, plugin, dependency, and package versions as authoritative. +- Use the repository's Gradle Wrapper. Do not substitute a machine-global Gradle installation. +- Preserve the established package layout and controller, application/service, domain, and persistence boundaries. +- Keep controllers thin, place business rules in the established service/domain layer, and prefer constructor injection. +- Apply request and configuration validation at boundaries and preserve the project's exception and response conventions. +- Make transaction boundaries explicit and narrow; do not add broad transactions to hide lifecycle or query problems. +- Preserve authentication, authorization, auditing, logging, and secret-management conventions. +- Do not edit generated QueryDSL or other generated sources. Change their source definitions and regenerate only when the repository workflow requires it. +- Use the approved KriCommon contract when the project profile includes it; do not duplicate shared backend behavior locally. +- Run the narrowest relevant Gradle compile, test, static-analysis, and build tasks. + +## Microsoft SQL Server + +- Use T-SQL syntax and behavior only for data sources whose declared engine is `mssql`. +- Preserve the configured SQL Server version, database and schema names, collation, naming, migration, and access conventions. +- Parameterize values. Do not build SQL by concatenating untrusted input. +- Preserve Unicode behavior and use the repository's established `nvarchar`/`nchar` and parameter conventions where Korean or other Unicode text is possible. +- Treat stored-procedure parameters, result sets, return values, transaction behavior, and error behavior as public contracts. +- Consider indexes and actual execution characteristics for changed filters, joins, ordering, grouping, and pagination. +- Do not introduce MySQL or other dialect syntax into MSSQL paths. +- Keep read-only legacy integrations read-only. A source-code change approval authorizes SQL analysis and script drafting only; execution requires separate explicit approval and the declared data-source access level. + +## KriCommon Consumer Contract + +- Consume KriCommon as `com.kri.common:starter:` through the repository's established Gradle version-management convention. +- Import service-facing APIs from `com.kri.common.feature.*`; treat `com.kri.common.runtime.*` as internal. +- Prefer a shared feature or approved extension point over duplicating authentication, HTTP, error, enum, Excel, Redis, JSON, date/time, JPA, crypto, or utility behavior locally. +- For HTTP/2 header safety and original upstream error propagation, use the shared HTTP/bypass features documented in the routed platform-capabilities reference instead of implementing consumer-local header filters and raw-response exception handlers. +- Response customizers may call `requireSuccess()`; its upstream exception propagates unchanged. Response charset parsing ignores charset-like text inside other quoted header parameters. +- Do not modify KriCommon or another consumer repository unless it is explicitly included in the approved task scope. + +### Required Shared References + +Before each related task, read the current contents of every matching reference, even if it was read earlier in the session. + +| Task scope | Required reference | +|---|---| +| Dependency, configuration, security, Web, Swagger, Redis, scheduling, HTTP, JSON, or date/time behavior | `.agent-harness/references/kri-common/platform-capabilities.md` | +| Encryption, hashing, key material, or legacy crypto interoperability | `.agent-harness/references/kri-common/crypto-contract.md` | +| KriCommon version upgrade or consumer verification | `.agent-harness/references/kri-common/upgrade-and-verification.md` | + +If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriCommon's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead. + +# kart-server Project Instruction Router + +## Required Project References + +Before each related task, read the current contents of every matching reference below, even if it was read earlier in the session. + +| Task scope | Required reference | +|---|---| +| Any substantive analysis, planning, implementation, debugging, review, or documentation work in this repository | `.agent/references/repository-rules.md` | + +If a task spans multiple scopes, read every matching reference. Do not assume remembered content is current. + +## Harness Workflow + +- `AGENTS.md` and `CLAUDE.md` are generated outputs. Never edit them directly. +- Edit `.agent/project.md` only when routing changes. Store durable project detail in `.agent/references/`. +- A reference-only content change does not require recomposition when its route is unchanged. Run harness verification to validate routing and UTF-8. +- Recompose and verify after changing `.agent/project.md`, `.agent/profile.yml`, or another composed instruction source. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..2291cc1 --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +# kart-server + +KART 백엔드 API + +## 기술 구성 + +- Java 17 +- Spring Boot 3.5.7 +- `com.kri.common:starter:beta.1.6.4` +- JPA + QueryDSL + JdbcTemplate +- EmbeddedId 예제 +- MyBatis는 생성 옵션에 따라 포함 + +## Gitea Maven 인증 + +Windows 사용자 Gradle 설정: + +```text +%USERPROFILE%\.gradle\gradle.properties +``` + +```properties +giteaUser=사용자명 +giteaToken=Gitea토큰 +``` + +또는 다음 환경변수를 사용할 수 있습니다. + +```text +GITEA_MAVEN_USER +GITEA_MAVEN_TOKEN +``` + +## 실행 + +Windows: + +```powershell +.\gradlew.bat bootRun +``` + +Linux/macOS: + +```bash +./gradlew bootRun +``` + +프로필 지정: + +```powershell +.\gradlew.bat bootRun --args="--spring.profiles.active=local" +``` + +## 빌드 + +```powershell +.\gradlew.bat clean build +``` + +## 인증 설정 + +공용 Starter 설정으로 제어합니다. + +```yaml +kri: + security: + enabled: true + auth: + apikey: + enabled: false +``` + +프로젝트 내부에 JWT/API Key 필터를 중복 구현하지 않습니다. + +## Agent Harness + +- 프로젝트 ID: `kart-server` +- 프로젝트 유형: `internal-service` +- 권위 원본: `.agent/profile.yml`, `.agent/project.md`, `.agent/references/*.md` + +`AGENTS.md`와 `CLAUDE.md`는 중앙 Agent Harness가 합성합니다. 두 파일을 직접 수정하지 않습니다. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..05344d8 --- /dev/null +++ b/build.gradle @@ -0,0 +1,103 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.5.7' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.kri.kart.server' +version = '0.0.1-SNAPSHOT' +description = 'KART 백엔드 API' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +def giteaUser = findProperty('giteaUser') + ?: System.getenv('GITEA_MAVEN_USER') + ?: '' +def giteaToken = findProperty('giteaToken') + ?: System.getenv('GITEA_MAVEN_TOKEN') + ?: '' + +repositories { + mavenCentral() + + maven { + name = 'gitea' + url = uri('https://gitea.kric.com/api/packages/KRi/maven') + credentials { + username = giteaUser + password = giteaToken + } + } +} + +configurations.configureEach { + resolutionStrategy.cacheDynamicVersionsFor 0, 'seconds' +} + +dependencies { + implementation 'com.kri.common:starter:beta.1.6.8' + + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-jdbc' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.11' + + implementation 'io.github.openfeign.querydsl:querydsl-jpa:7.1' + annotationProcessor 'com.querydsl:querydsl-apt:5.0.0:jakarta' + annotationProcessor 'jakarta.annotation:jakarta.annotation-api' + annotationProcessor 'jakarta.persistence:jakarta.persistence-api' + + runtimeOnly 'com.microsoft.sqlserver:mssql-jdbc:13.2.1.jre11' + implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.5' + + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + + developmentOnly 'org.springframework.boot:spring-boot-devtools' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.security:spring-security-test' + testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:3.0.5' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +def querydslDir = layout.buildDirectory.dir('generated/querydsl').get().asFile + +sourceSets { + main.java.srcDirs += [querydslDir] +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.generatedSourceOutputDirectory.set(file(querydslDir)) +} + +tasks.withType(Test).configureEach { + jvmArgs '-Dfile.encoding=UTF-8' +} + +tasks.withType(JavaExec).configureEach { + jvmArgs '-Dfile.encoding=UTF-8' +} + +tasks.named('test') { + useJUnitPlatform() +} + +tasks.named('clean') { + doLast { + delete querydslDir + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..0e829de --- /dev/null +++ b/gradle.properties @@ -0,0 +1,5 @@ +# Keep the Gradle daemon on the platform charset so Windows JDK 17 can read +# worker classpath files containing non-ASCII project paths. +org.gradle.jvmargs=-Xmx2g +org.gradle.parallel=true +org.gradle.caching=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d4081da --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..e4c76d9 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'kart-server' diff --git a/src/main/java/com/kri/kart/server/KartServerApplication.java b/src/main/java/com/kri/kart/server/KartServerApplication.java new file mode 100644 index 0000000..46a8098 --- /dev/null +++ b/src/main/java/com/kri/kart/server/KartServerApplication.java @@ -0,0 +1,14 @@ +package com.kri.kart.server; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; + +@SpringBootApplication +@ConfigurationPropertiesScan +public class KartServerApplication { + + public static void main(String[] args) { + SpringApplication.run(KartServerApplication.class, args); + } +} diff --git a/src/main/java/com/kri/kart/server/common/consts/ExampleConstant.java b/src/main/java/com/kri/kart/server/common/consts/ExampleConstant.java new file mode 100644 index 0000000..8bfd907 --- /dev/null +++ b/src/main/java/com/kri/kart/server/common/consts/ExampleConstant.java @@ -0,0 +1,9 @@ +package com.kri.kart.server.common.consts; + +public final class ExampleConstant { + + public static final int DEFAULT_BATCH_SIZE = 1_000; + + private ExampleConstant() { + } +} diff --git a/src/main/java/com/kri/kart/server/common/enums/ExampleStatus.java b/src/main/java/com/kri/kart/server/common/enums/ExampleStatus.java new file mode 100644 index 0000000..34484d6 --- /dev/null +++ b/src/main/java/com/kri/kart/server/common/enums/ExampleStatus.java @@ -0,0 +1,6 @@ +package com.kri.kart.server.common.enums; + +public enum ExampleStatus { + ACTIVE, + INACTIVE +} diff --git a/src/main/java/com/kri/kart/server/common/util/StringNormalizer.java b/src/main/java/com/kri/kart/server/common/util/StringNormalizer.java new file mode 100644 index 0000000..6dcc971 --- /dev/null +++ b/src/main/java/com/kri/kart/server/common/util/StringNormalizer.java @@ -0,0 +1,13 @@ +package com.kri.kart.server.common.util; + +public final class StringNormalizer { + + private StringNormalizer() { + } + + public static String trimToNull(String value) { + if (value == null) return null; + String normalized = value.trim(); + return normalized.isEmpty() ? null : normalized; + } +} diff --git a/src/main/java/com/kri/kart/server/common/validation/package-info.java b/src/main/java/com/kri/kart/server/common/validation/package-info.java new file mode 100644 index 0000000..16c88e4 --- /dev/null +++ b/src/main/java/com/kri/kart/server/common/validation/package-info.java @@ -0,0 +1,4 @@ +/** + * 프로젝트 전용 Bean Validation annotation과 validator를 배치합니다. + */ +package com.kri.kart.server.common.validation; diff --git a/src/main/java/com/kri/kart/server/config/FileStorageProperties.java b/src/main/java/com/kri/kart/server/config/FileStorageProperties.java new file mode 100644 index 0000000..f33b4c8 --- /dev/null +++ b/src/main/java/com/kri/kart/server/config/FileStorageProperties.java @@ -0,0 +1,14 @@ +package com.kri.kart.server.config; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@Getter +@Setter +@ConfigurationProperties(prefix = "kri.file") +public class FileStorageProperties { + + private String baseDir = "./upload-file"; + private String resourcePattern = "/files/**"; +} diff --git a/src/main/java/com/kri/kart/server/config/JdbcConfig.java b/src/main/java/com/kri/kart/server/config/JdbcConfig.java new file mode 100644 index 0000000..6b4c03f --- /dev/null +++ b/src/main/java/com/kri/kart/server/config/JdbcConfig.java @@ -0,0 +1,15 @@ +package com.kri.kart.server.config; + +import javax.sql.DataSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; + +@Configuration +public class JdbcConfig { + + @Bean + public JdbcTemplate jdbcTemplate(DataSource dataSource) { + return new JdbcTemplate(dataSource); + } +} diff --git a/src/main/java/com/kri/kart/server/config/QueryDSLConfig.java b/src/main/java/com/kri/kart/server/config/QueryDSLConfig.java new file mode 100644 index 0000000..a6a74df --- /dev/null +++ b/src/main/java/com/kri/kart/server/config/QueryDSLConfig.java @@ -0,0 +1,19 @@ +package com.kri.kart.server.config; + +import com.querydsl.jpa.impl.JPAQueryFactory; +import jakarta.persistence.EntityManager; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@RequiredArgsConstructor +public class QueryDSLConfig { + + private final EntityManager entityManager; + + @Bean + public JPAQueryFactory jpaQueryFactory() { + return new JPAQueryFactory(entityManager); + } +} diff --git a/src/main/java/com/kri/kart/server/config/WebResourceConfig.java b/src/main/java/com/kri/kart/server/config/WebResourceConfig.java new file mode 100644 index 0000000..14499bc --- /dev/null +++ b/src/main/java/com/kri/kart/server/config/WebResourceConfig.java @@ -0,0 +1,26 @@ +package com.kri.kart.server.config; + +import java.nio.file.Path; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@RequiredArgsConstructor +public class WebResourceConfig implements WebMvcConfigurer { + + private final FileStorageProperties fileStorageProperties; + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + String location = Path.of(fileStorageProperties.getBaseDir()) + .toAbsolutePath() + .normalize() + .toUri() + .toString(); + + registry.addResourceHandler(fileStorageProperties.getResourcePattern()) + .addResourceLocations(location.endsWith("/") ? location : location + "/"); + } +} diff --git a/src/main/java/com/kri/kart/server/controller/ExampleController.java b/src/main/java/com/kri/kart/server/controller/ExampleController.java new file mode 100644 index 0000000..3a72928 --- /dev/null +++ b/src/main/java/com/kri/kart/server/controller/ExampleController.java @@ -0,0 +1,38 @@ +package com.kri.kart.server.controller; + +import com.kri.kart.server.dto.request.CreateExampleRequest; +import com.kri.kart.server.dto.response.ExampleResponse; +import com.kri.kart.server.service.ExampleService; +import jakarta.validation.Valid; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/v1/examples") +public class ExampleController { + + private final ExampleService exampleService; + + @GetMapping + public List search( + @RequestParam(defaultValue = "") String keyword, + @RequestParam(defaultValue = "20") int limit + ) { + return exampleService.search(keyword, limit); + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public ExampleResponse create(@Valid @RequestBody CreateExampleRequest request) { + return exampleService.create(request); + } +} diff --git a/src/main/java/com/kri/kart/server/controller/PingController.java b/src/main/java/com/kri/kart/server/controller/PingController.java new file mode 100644 index 0000000..7d27b4a --- /dev/null +++ b/src/main/java/com/kri/kart/server/controller/PingController.java @@ -0,0 +1,14 @@ +package com.kri.kart.server.controller; + +import java.util.Map; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class PingController { + + @GetMapping("/ping") + public Map ping() { + return Map.of("status", "ok"); + } +} diff --git a/src/main/java/com/kri/kart/server/dto/request/CreateExampleRequest.java b/src/main/java/com/kri/kart/server/dto/request/CreateExampleRequest.java new file mode 100644 index 0000000..1f7d2d4 --- /dev/null +++ b/src/main/java/com/kri/kart/server/dto/request/CreateExampleRequest.java @@ -0,0 +1,12 @@ +package com.kri.kart.server.dto.request; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; + +public record CreateExampleRequest( + @NotNull @Positive Long groupId, + @NotNull @Positive Integer sequence, + @NotBlank String name +) { +} diff --git a/src/main/java/com/kri/kart/server/dto/response/ExampleResponse.java b/src/main/java/com/kri/kart/server/dto/response/ExampleResponse.java new file mode 100644 index 0000000..a964cb5 --- /dev/null +++ b/src/main/java/com/kri/kart/server/dto/response/ExampleResponse.java @@ -0,0 +1,19 @@ +package com.kri.kart.server.dto.response; + +import com.kri.kart.server.persistence.entity.ExampleEntity; + +public record ExampleResponse( + Long groupId, + Integer sequence, + String name, + String status +) { + public static ExampleResponse from(ExampleEntity entity) { + return new ExampleResponse( + entity.getId().getGroupId(), + entity.getId().getSequence(), + entity.getName(), + entity.getStatus().name() + ); + } +} diff --git a/src/main/java/com/kri/kart/server/persistence/entity/ExampleEntity.java b/src/main/java/com/kri/kart/server/persistence/entity/ExampleEntity.java new file mode 100644 index 0000000..c0fd210 --- /dev/null +++ b/src/main/java/com/kri/kart/server/persistence/entity/ExampleEntity.java @@ -0,0 +1,42 @@ +package com.kri.kart.server.persistence.entity; + +import com.kri.kart.server.common.enums.ExampleStatus; +import com.kri.kart.server.persistence.entity.id.ExampleEntityId; +import jakarta.persistence.Column; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Table; +import lombok.AccessLevel; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@Entity +@Table(name = "t_example") +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class ExampleEntity { + + @EmbeddedId + private ExampleEntityId id; + + @Column(name = "name", nullable = false, length = 100) + private String name; + + @Enumerated(EnumType.STRING) + @Column(name = "status", nullable = false, length = 20) + private ExampleStatus status; + + @Builder + public ExampleEntity(ExampleEntityId id, String name, ExampleStatus status) { + this.id = id; + this.name = name; + this.status = status == null ? ExampleStatus.ACTIVE : status; + } + + public void changeName(String name) { + this.name = name; + } +} diff --git a/src/main/java/com/kri/kart/server/persistence/entity/id/ExampleEntityId.java b/src/main/java/com/kri/kart/server/persistence/entity/id/ExampleEntityId.java new file mode 100644 index 0000000..b2c6b62 --- /dev/null +++ b/src/main/java/com/kri/kart/server/persistence/entity/id/ExampleEntityId.java @@ -0,0 +1,28 @@ +package com.kri.kart.server.persistence.entity.id; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import java.io.Serial; +import java.io.Serializable; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@Embeddable +@EqualsAndHashCode +@AllArgsConstructor +@NoArgsConstructor(access = AccessLevel.PROTECTED) +public class ExampleEntityId implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + @Column(name = "group_id", nullable = false) + private Long groupId; + + @Column(name = "sequence", nullable = false) + private Integer sequence; +} diff --git a/src/main/java/com/kri/kart/server/persistence/jdbc/ExampleBulkItem.java b/src/main/java/com/kri/kart/server/persistence/jdbc/ExampleBulkItem.java new file mode 100644 index 0000000..405ce50 --- /dev/null +++ b/src/main/java/com/kri/kart/server/persistence/jdbc/ExampleBulkItem.java @@ -0,0 +1,9 @@ +package com.kri.kart.server.persistence.jdbc; + +public record ExampleBulkItem( + Long groupId, + Integer sequence, + String name, + String status +) { +} diff --git a/src/main/java/com/kri/kart/server/persistence/jdbc/ExampleBulkJdbcRepository.java b/src/main/java/com/kri/kart/server/persistence/jdbc/ExampleBulkJdbcRepository.java new file mode 100644 index 0000000..4c2a1ca --- /dev/null +++ b/src/main/java/com/kri/kart/server/persistence/jdbc/ExampleBulkJdbcRepository.java @@ -0,0 +1,47 @@ +package com.kri.kart.server.persistence.jdbc; + +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.jdbc.core.BatchPreparedStatementSetter; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +@Repository +@RequiredArgsConstructor +public class ExampleBulkJdbcRepository { + + private final JdbcTemplate jdbcTemplate; + + public void insertAll(List items, int batchSize) { + if (items == null || items.isEmpty()) return; + + String sql = """ + insert into t_example (group_id, sequence, name, status) + values (?, ?, ?, ?) + """; + + int safeBatchSize = Math.max(batchSize, 1); + for (int from = 0; from < items.size(); from += safeBatchSize) { + int to = Math.min(from + safeBatchSize, items.size()); + List batch = items.subList(from, to); + + jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { + @Override + public void setValues(PreparedStatement statement, int index) throws SQLException { + ExampleBulkItem item = batch.get(index); + statement.setLong(1, item.groupId()); + statement.setInt(2, item.sequence()); + statement.setString(3, item.name()); + statement.setString(4, item.status()); + } + + @Override + public int getBatchSize() { + return batch.size(); + } + }); + } + } +} diff --git a/src/main/java/com/kri/kart/server/persistence/mapper/ExampleMapper.java b/src/main/java/com/kri/kart/server/persistence/mapper/ExampleMapper.java new file mode 100644 index 0000000..20ea6a6 --- /dev/null +++ b/src/main/java/com/kri/kart/server/persistence/mapper/ExampleMapper.java @@ -0,0 +1,11 @@ +package com.kri.kart.server.persistence.mapper; + +import com.kri.kart.server.dto.response.ExampleResponse; +import java.util.List; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +@Mapper +public interface ExampleMapper { + List findByName(@Param("keyword") String keyword); +} diff --git a/src/main/java/com/kri/kart/server/persistence/query/ExamplePredicates.java b/src/main/java/com/kri/kart/server/persistence/query/ExamplePredicates.java new file mode 100644 index 0000000..9c0c3f3 --- /dev/null +++ b/src/main/java/com/kri/kart/server/persistence/query/ExamplePredicates.java @@ -0,0 +1,15 @@ +package com.kri.kart.server.persistence.query; + +import com.kri.kart.server.persistence.entity.QExampleEntity; +import com.querydsl.core.types.dsl.BooleanExpression; + +public final class ExamplePredicates { + + private ExamplePredicates() { + } + + public static BooleanExpression nameContains(QExampleEntity example, String keyword) { + if (keyword == null || keyword.isBlank()) return null; + return example.name.containsIgnoreCase(keyword.trim()); + } +} diff --git a/src/main/java/com/kri/kart/server/persistence/repository/ExampleQueryRepository.java b/src/main/java/com/kri/kart/server/persistence/repository/ExampleQueryRepository.java new file mode 100644 index 0000000..70c69f4 --- /dev/null +++ b/src/main/java/com/kri/kart/server/persistence/repository/ExampleQueryRepository.java @@ -0,0 +1,8 @@ +package com.kri.kart.server.persistence.repository; + +import com.kri.kart.server.persistence.entity.ExampleEntity; +import java.util.List; + +public interface ExampleQueryRepository { + List findByNameContains(String keyword, int limit); +} diff --git a/src/main/java/com/kri/kart/server/persistence/repository/ExampleQueryRepositoryImpl.java b/src/main/java/com/kri/kart/server/persistence/repository/ExampleQueryRepositoryImpl.java new file mode 100644 index 0000000..2f87ef3 --- /dev/null +++ b/src/main/java/com/kri/kart/server/persistence/repository/ExampleQueryRepositoryImpl.java @@ -0,0 +1,25 @@ +package com.kri.kart.server.persistence.repository; + +import static com.kri.kart.server.persistence.entity.QExampleEntity.exampleEntity; + +import com.kri.kart.server.persistence.entity.ExampleEntity; +import com.kri.kart.server.persistence.query.ExamplePredicates; +import com.querydsl.jpa.impl.JPAQueryFactory; +import java.util.List; +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +public class ExampleQueryRepositoryImpl implements ExampleQueryRepository { + + private final JPAQueryFactory jpaQueryFactory; + + @Override + public List findByNameContains(String keyword, int limit) { + return jpaQueryFactory + .selectFrom(exampleEntity) + .where(ExamplePredicates.nameContains(exampleEntity, keyword)) + .orderBy(exampleEntity.id.groupId.asc(), exampleEntity.id.sequence.asc()) + .limit(Math.max(limit, 1)) + .fetch(); + } +} diff --git a/src/main/java/com/kri/kart/server/persistence/repository/ExampleRepository.java b/src/main/java/com/kri/kart/server/persistence/repository/ExampleRepository.java new file mode 100644 index 0000000..a632bde --- /dev/null +++ b/src/main/java/com/kri/kart/server/persistence/repository/ExampleRepository.java @@ -0,0 +1,9 @@ +package com.kri.kart.server.persistence.repository; + +import com.kri.kart.server.persistence.entity.ExampleEntity; +import com.kri.kart.server.persistence.entity.id.ExampleEntityId; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ExampleRepository + extends JpaRepository, ExampleQueryRepository { +} diff --git a/src/main/java/com/kri/kart/server/scheduler/ExampleScheduler.java b/src/main/java/com/kri/kart/server/scheduler/ExampleScheduler.java new file mode 100644 index 0000000..c9d8a75 --- /dev/null +++ b/src/main/java/com/kri/kart/server/scheduler/ExampleScheduler.java @@ -0,0 +1,21 @@ +package com.kri.kart.server.scheduler; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@ConditionalOnProperty( + prefix = "app.scheduler.example", + name = "enabled", + havingValue = "true" +) +public class ExampleScheduler { + + @Scheduled(cron = "${app.scheduler.example.cron:0 0 1 * * *}") + public void execute() { + log.info("Example scheduler executed"); + } +} diff --git a/src/main/java/com/kri/kart/server/service/ExampleService.java b/src/main/java/com/kri/kart/server/service/ExampleService.java new file mode 100644 index 0000000..d882669 --- /dev/null +++ b/src/main/java/com/kri/kart/server/service/ExampleService.java @@ -0,0 +1,37 @@ +package com.kri.kart.server.service; + +import com.kri.kart.server.common.enums.ExampleStatus; +import com.kri.kart.server.dto.request.CreateExampleRequest; +import com.kri.kart.server.dto.response.ExampleResponse; +import com.kri.kart.server.persistence.entity.ExampleEntity; +import com.kri.kart.server.persistence.entity.id.ExampleEntityId; +import com.kri.kart.server.persistence.repository.ExampleRepository; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +@Transactional(readOnly = true) +public class ExampleService { + + private final ExampleRepository exampleRepository; + + @Transactional + public ExampleResponse create(CreateExampleRequest request) { + ExampleEntity entity = ExampleEntity.builder() + .id(new ExampleEntityId(request.groupId(), request.sequence())) + .name(request.name()) + .status(ExampleStatus.ACTIVE) + .build(); + return ExampleResponse.from(exampleRepository.save(entity)); + } + + public List search(String keyword, int limit) { + return exampleRepository.findByNameContains(keyword == null ? "" : keyword, limit) + .stream() + .map(ExampleResponse::from) + .toList(); + } +} diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 0000000..406227f --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -0,0 +1,10 @@ +spring: + datasource: + url: "${DB_URL}" + username: "${DB_USERNAME}" + password: "${DB_PASSWORD}" + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + +logging: + level: + org.hibernate.SQL: DEBUG diff --git a/src/main/resources/application-local.yml b/src/main/resources/application-local.yml new file mode 100644 index 0000000..817a80d --- /dev/null +++ b/src/main/resources/application-local.yml @@ -0,0 +1,6 @@ +spring: + datasource: + url: "${DB_URL:jdbc:sqlserver://localhost:1433;databaseName=sample;encrypt=false}" + username: "${DB_USERNAME:sample}" + password: "${DB_PASSWORD:sample}" + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml new file mode 100644 index 0000000..874a0ec --- /dev/null +++ b/src/main/resources/application-prod.yml @@ -0,0 +1,10 @@ +spring: + datasource: + url: "${DB_URL}" + username: "${DB_USERNAME}" + password: "${DB_PASSWORD}" + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + +kri: + swagger: + enabled: ${KRI_SWAGGER_ENABLED:false} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..61b1074 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,81 @@ +server: + port: 4015 + forward-headers-strategy: framework + +spring: + application: + name: kart-server + profiles: + default: local + jpa: + open-in-view: false + hibernate: + ddl-auto: none + properties: + hibernate: + jdbc: + batch_size: 1000 + order_inserts: true + order_updates: true + format_sql: true + servlet: + multipart: + max-file-size: 20MB + max-request-size: 20MB + +logging: + file: + path: ./logs + +springdoc: + writer-with-order-by-keys: true + swagger-ui: + tags-sorter: alpha + operations-sorter: method + +kri: + auth: + apikey: + enabled: ${KRI_API_KEY_ENABLED:false} + key: ${KRI_API_KEY:} + header-name: ${KRI_API_KEY_HEADER_NAME:X-API-Key} + service-code: ${KRI_API_KEY_SERVICE_CODE:kart-server} + preload-on-startup: ${KRI_API_KEY_PRELOAD_ON_STARTUP:false} + admin-api-enabled: ${KRI_API_KEY_ADMIN_ENABLED:false} + admin-allow-ips: [] + security: + enabled: ${KRI_SECURITY_ENABLED:true} + public-paths: + - /v3/api-docs/** + - /swagger-ui.html + - /swagger-ui/** + - /ping + - /files/** + swagger: + enabled: ${KRI_SWAGGER_ENABLED:true} + title: "kart-server API" + description: "KART 백엔드 API" + version: "v1.0.0" + base-package: "com.kri.kart.server" + allowed-ips: [] + file: + base-dir: ${FILE_STORAGE_BASE_DIR:./upload-file} + resource-pattern: /files/** + web: + enabled: true + redis: + enabled: false + scheduling: + enabled: true + +app: + scheduler: + example: + enabled: ${EXAMPLE_SCHEDULER_ENABLED:false} + cron: ${EXAMPLE_SCHEDULER_CRON:0 0 1 * * *} + +mybatis: + mapper-locations: classpath:/mybatis/mapper/**/*.xml + type-aliases-package: com.kri.kart.server.persistence.entity + configuration: + map-underscore-to-camel-case: true diff --git a/src/main/resources/mybatis/mapper/ExampleMapper.xml b/src/main/resources/mybatis/mapper/ExampleMapper.xml new file mode 100644 index 0000000..0d0df6b --- /dev/null +++ b/src/main/resources/mybatis/mapper/ExampleMapper.xml @@ -0,0 +1,16 @@ + + + + + diff --git a/src/test/java/com/kri/kart/server/PackageStructureTest.java b/src/test/java/com/kri/kart/server/PackageStructureTest.java new file mode 100644 index 0000000..4f15402 --- /dev/null +++ b/src/test/java/com/kri/kart/server/PackageStructureTest.java @@ -0,0 +1,13 @@ +package com.kri.kart.server; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class PackageStructureTest { + + @Test + void templateIsGenerated() { + assertTrue(true); + } +}