CreateFolderHandler Documentation
Overview
The CreateFolderHandler class is an HTTP handler that enables authenticated users to create
new directories within their website's file structure. It provides a secure API endpoint for
folder creation operations initiated from the web-based file management interface.
Purpose
This handler is part of the multi-tenant hosting service's file management system, allowing
users to organize their content by creating new folders within their allocated storage space.
It ensures that only authenticated users can create directories and that they can only do so
within their own account boundaries.
Core Functionality
This handler performs the following key operations:
1. Request Validation
- Only accepts POST requests
- Returns HTTP 403 (Forbidden) for non-POST methods
- Expects JSON payload containing the target folder path
2. Authentication & Authorization
- Extracts and validates the session ID from the request via getJavaSessionId()
- Verifies the session through SessionManager.getUsername()
- Rejects requests with invalid or expired sessions (HTTP 403)
- Ensures users can only create folders within their own directory space
3. Path Construction
The handler builds the target directory path based on the authenticated user:
- Standard users: {USER_DIR}/{username}/static/{requested_path}
- Administrator (ADMIN_HOST match): {ADMIN_DIR}/static/{requested_path}
Where:
- USER_DIR is the base directory for user accounts (likely /home/lukas/users/)
- ADMIN_DIR is the special directory for administrative content (likely /home/lukas/JavaServerProject/www)
- {requested_path} is provided in the JSON request body
4. Directory Creation
- Attempts to create the directory using Files.createDirectory()
- Creates only a single directory (not recursive - parent directories must exist)
- Handles collision gracefully when directory already exists
5. Response Handling
Returns a plain text response indicating the operation result:
- "Success": Directory was created successfully
- "Fail": Directory creation failed (typically due to I/O errors or missing parent directories)
Note: If the directory already exists, the handler logs this condition but still
returns "Fail" to the client.
Request Format
Method: POST
Content-Type: application/json
Body:
{
"path": "relative/folder/path"
}
The path value should be relative to the user's static directory
(e.g., "images/thumbnails" or "assets/css").
Response Format
Content-Type: text/plain; charset=UTF-8
Body: Either "Success" or "Fail"
Response Codes
- 200 OK: Request was processed (check response body for success/failure)
- 403 Forbidden: Invalid session or non-POST request method
Security Features
- Session-based authentication: All requests require valid session credentials
- User isolation: Users can only create folders within their own directory structure
- Path scoping: Requested paths are always appended to the user's base directory, preventing directory traversal attacks
- Administrator separation: Special handling for admin accounts with different base paths
Error Handling
- FileAlreadyExistsException: Caught and logged when attempting to create an existing directory; returns "Fail" to client
- Other IOException: Implicitly caught by the handler signature; results in "Fail" response
- Missing parent directories: Will cause creation to fail since createDirectory() is non-recursive
Limitations
- Non-recursive creation: Only creates a single directory level. Parent directories must already exist
- No detailed error messages: Returns generic "Fail" message without specifying the reason (existing directory, missing parent, permissions, etc.)
- Success on any exception: The msg variable defaults to "Fail" and is only set to "Success" after successful creation
Use Cases
This handler is typically invoked when users:
- Create new folders for organizing website content (images, scripts, stylesheets)
- Set up directory structures for new website sections
- Organize uploaded files into categorical folders
- Prepare directories before file upload operations
Dependencies
This handler relies on:
- parseJsonToMap(): Converts JSON request body to a key-value map
- getJavaSessionId(): Extracts session identifier from the HTTP request
- SessionManager.getUsername(): Validates session and retrieves the authenticated username
- USER_DIR: Constant defining the base directory for user accounts
- ADMIN_DIR: Constant defining the base directory for administrative content
- ADMIN_HOST: Constant identifying the administrator username
flowchart TD
A(["Start handle"]) --> B{"Request method
== POST?"}
B -->|No| C["Send 403 Forbidden
Close response body"]
B -->|Yes| D["Read request body
into String with UTF-8"]
C --> T(["End"])
D --> E["Parse JSON body
using parseJsonToMap"]
E --> F["Get sessionId via
getJavaSessionId(exchange)"]
F --> G["Get username from
SessionManager.getUsername(sessionId)"]
G --> H{"Username
is null?"}
H -->|Yes| I["Log: 'Rejected: session not valid'
Send 403 Forbidden
Close response body"]
H -->|No| J["Build base path:
USER_DIR + user + /static/ + map.get(path)"]
I --> T
J --> K{"Username ==
ADMIN_HOST?"}
K -->|Yes| L["Override path:
ADMIN_DIR + /static/ + map.get(path)"]
K -->|No| M["Keep user path"]
L --> N["Initialize msg = 'Fail'
Create Path object: newPath = Paths.get(path)"]
M --> N
N --> O["TRY: Files.createDirectory(newPath)"]
O --> P{"Directory creation
successful?"}
P -->|Success| Q["Set msg = 'Success'"]
P -->|FileAlreadyExistsException| R["CATCH: Log 'Directory already exist: {path}'
msg remains 'Fail'"]
P -->|Other Exception| S["msg remains 'Fail'"]
Q --> U
R --> U
S --> U
U["Convert msg to bytes:
response = msg.getBytes()"]
U --> V["Set Content-Type header:
text/plain; charset=UTF-8"]
V --> W["Send 200 response
with response.length"]
W --> X["Write response bytes
to OutputStream"]
X --> Y["Close OutputStream"]
Y --> T