📁 Java HTTP Server Project Documentation
Overview
This is a comprehensive, self-hosted multi-tenant web hosting platform built from scratch in Java.
The system provides users with complete website hosting capabilities, including file management,
database access, PHP execution, blog creation, and media streaming—all through an intuitive
web-based interface.
Architecture
Backend (Java)
- Custom HTTP Server: Built on Java's com.sun.net.httpserver framework
- Multi-threaded Execution: Separate thread pools for normal requests (20 threads) and video streaming (8 threads)
- Dual Executor Design: DelegatingHandler intelligently routes video requests to a dedicated executor to prevent streaming from blocking standard file serving
Frontend (JavaScript + PHP)
- Pure JavaScript: No frameworks—vanilla JS with modular ES6 imports
- Ace Editor Integration: Full-featured code editor for in-browser file editing
- PHP Interface Layer: Session management and authentication handled via PHP
- Real-time Updates: Dynamic file browsing without page refreshes
Database
- MySQL: User accounts, invitations, messages, and metadata
- Per-User Isolation: Each user can have their own database with restricted access
- Connection Pooling: Efficient database resource management
Core Features
1. Multi-Tenant User Management
- User registration with invite codes
- Domain-based routing (each user gets their own domain)
- Per-user directory structure: /home/lukas/users/{username}/
- Session-based authentication with Java session management
- Password hashing via PHP's password_hash() function
2. File Management System
Web-based File Explorer: Navigate directories, create folders, upload/download files
In-browser Code Editor: Edit HTML, CSS, JavaScript, and PHP files with syntax highlighting
File Type Support:
- Text files (HTML, CSS, JS, PHP)
- Images (JPEG, PNG, GIF, SVG, WebP, HEIC, TIFF, etc.)
- Videos (MP4, MOV, AVI) with streaming support
- PDFs
File Operations:
- Drag-and-Drop Upload: Support for both individual files and entire folder structures
- Create, read, update, delete, rename, move files and folders
- Real-time file browser with visual feedback
3. PHP Script Execution
- CGI Integration: Processes PHP files via php-cgi with custom configuration
- Per-User PHP.ini: Each user has isolated PHP settings with security restrictions
- Security Restrictions:
- open_basedir restrictions to user's directory
- Disabled dangerous functions (exec, shell_exec, system, etc.)
- Resource limits (32MB memory, 5s execution time, 2MB upload size)
- GET/POST Support: Full request parameter handling
- Cookie Management: PHP sessions and cookies properly forwarded
- Header Forwarding: HTTP redirects and custom headers work correctly
4. Blog Creation System
- Dual-File Storage:
- HTML content stored in /blog/ directory
- Metadata .blog files stored in /static/
- Blog Editor: Rich text editing with metadata tracking
- Blog Management: Create, edit, rename, delete blog posts
- Direct Publishing: Blogs accessible via .blog extension
5. Video Streaming
- HTTP Range Requests: Proper support for seekable video playback
- Connection Limiting: Maximum 8 concurrent video streams to prevent server overload
- Service Unavailable Handling: Returns 503 when stream limit reached
- Efficient Streaming: Uses FileChannel.transferTo() for zero-copy streaming
- Partial Content Support: Implements HTTP 206 responses for range requests
6. Database Management
- Web-based Interface: Create tables, execute queries, manage data
- Per-User Databases: Optional isolated database per user account
- Query Builder: JSON-based query construction from frontend
- Result Formatting: Automatic JSON serialization of query results
- CRUD Operations: Full create, read, update, delete support
7. Security Features
- Session Management: Java-based session system with cookie validation
- Path Traversal Protection: All file paths normalized and validated
- User Isolation: Users cannot access files outside their directory
- File Type Validation: Upload restrictions based on allowed extensions
- SQL Injection Protection: Prepared statements for all database queries
- Admin Separation: Special handling for admin account with elevated permissions
- Input Sanitization: File names and paths sanitized to prevent malicious input
Technical Highlights
Multipart Form Data Parser
- Custom Implementation: No external libraries—parses multipart/form-data manually
- Binary-Safe: Handles file uploads with any encoding
- Folder Structure Preservation: Maintains relative paths for folder uploads
- Extension Validation: Whitelist-based file type checking
Virtual Host System
- Domain Mapping: DomainsConfig.domainMap routes domains to user directories
- Dynamic Resolution: Requests automatically routed based on Host header
- Fallback Handling: Unknown domains serve default 404 page
Content-Type Detection
- Extension-Based: Automatic MIME type detection for common file types
- Custom Handlers: Special handling for Unity WebGL builds (.unityweb, Brotli compression)
- Charset Support: UTF-8 encoding for text-based content
Advanced Path Resolution
The RootHandler implements sophisticated fallback logic:
- Try exact file match
- Fall back to index.html
- Fall back to index.php
- Fall back to index.blog
- Serve 404 if nothing found
File Structure
/home/lukas/
├── users/
│ └── {username}/
│ ├── static/ # User's web-accessible files
│ │ ├── html/
│ │ ├── css/
│ │ ├── js/
│ │ ├── img/
│ │ └── php/
│ └── blog/ # Blog HTML files
├── JavaServerProject/
│ └── www/
│ └── static/ # Admin/default files
└── php_ini/
└── {username}.ini # Per-user PHP config
API Endpoints
The server exposes 20+ HTTP endpoints:
File Management:
- /listAllFiles - List all files in a directory
- /deleteFile - Delete a specific file
- /getFileContent - Retrieve file contents
- /saveFile - Save or update file contents
- /upload - Upload single or multiple files
- /createFolder - Create a new directory
- /deleteFolder - Recursively delete a directory
- /moveIt - Move or rename files and folders
Blog Management:
- /getBlogContent - Retrieve blog post HTML
- /saveBlog - Create or update blog posts
- /deleteBlog - Delete blog post and metadata
- /renameBlog - Rename blog post files
Authentication:
- /create-session - Create new user session
- /check-session - Validate existing session
- /newuser - Register new user account
- /invite - Validate invitation codes
Database:
- /query - Execute SQL queries
- /deleteRows - Delete database rows
- /createTable - Create new database tables
Utilities:
- /game - Serve Unity WebGL game assets
- /questionForm - Handle contact form submissions
User Interface
The web interface (index.php) provides:
- Burger Menu Navigation: User info, domain settings, file manager, blog creator, logout
- File Browser: Visual representation of directory structure with icons
- Options Panel: Context-sensitive buttons for file operations
- Code Editor: Full-screen Ace editor with syntax highlighting and auto-completion
- Upload Zone: Drag-and-drop area with progress indicator
- Mini Explorer: Modal file picker for "Save As" operations
- Path Breadcrumbs: Current directory display with domain prefix
Performance Optimizations
- Thread Pool Sizing: Separate pools prevent blocking
- Stream Limiting: Prevents video streams from exhausting resources
- File Channel Streaming: Zero-copy file transfers for large files
- Lazy Loading: Files loaded on-demand, not preloaded
- Connection Limits: Configurable maximum concurrent streams (8 for video)
- Atomic Counter: Thread-safe stream tracking with AtomicInteger
Deployment
- Port: HTTP on port 80 (requires root or port forwarding)
- Single JAR: Compiles to standalone executable
- Dependencies:
- Java 11+ (uses com.sun.net.httpserver)
- PHP-CGI for script execution
- MySQL for database
- Standard Linux filesystem
- Configuration Files:
- DomainsConfig.java - Domain to directory mapping
- PhpConfig.java - Domain to username mapping for PHP
- DBConfig.properties - Database connection settings
Use Cases
- Personal Web Hosting: Host your own websites and blogs
- Development Environment: Test and deploy web projects
- Client Hosting: Provide hosting services to multiple clients
- Educational Platform: Learn web development with real hosting environment
- Portfolio Hosting: Manage multiple portfolio sites under one server
Key Classes and Components
Handler Classes
- DelegatingHandler: Routes requests to appropriate executor based on content type
- RootHandler: Main request handler with path resolution and content serving
- UploadHandler: Processes single file uploads via multipart form data
- UploadFolderHandler: Handles folder structure uploads
- ListAllFiles: Returns categorized file listings as JSON
- DeleteFileHandler: Deletes individual files
- DeleteFolderHandler: Recursively removes directories
- FetchFileContent: Retrieves file contents for editing
- SaveFileHandler: Writes file contents to disk
- CreateFolderHandler: Creates new directories
- MoveItHandler: Moves/renames files and folders
- SessionHandler: Creates user sessions
- CheckJavaSession: Validates session tokens
- SaveBlogHandler: Publishes blog posts
- FetchBlogContentHandler: Retrieves blog content for editing
- DeleteBlogHandler: Removes blog posts
- RenameBlogHandler: Renames blog files
Helper Methods
- handleMultipartFormData(): Custom multipart parser for file uploads
- runPhp(): Executes PHP scripts via php-cgi
- parseJsonToMap(): Custom JSON parser without external libraries
- deleteFolder(): Recursive directory deletion
- moveIt(): File/folder move operations
- phpHashPass(): PHP password hashing integration
- phpPassVerify(): PHP password verification
- sanitizeFileName(): Input validation for file names
- sanitizeUserName(): Input validation for usernames
Frontend Modules
DocumentManager (docmanager.js)
Manages the user interface and file browser:
- File listing and navigation
- Editor initialization and control
- File operation UI (create, delete, rename)
- User dashboard and menu
- Modal dialogs and confirmations
UploadManager (upmanager.js)
Handles file upload operations:
- Single and multiple file uploads
- Progress tracking with XMLHttpRequest
- Drag-and-drop support
- File validation and sanitization
- Blog content management
Security Considerations
- No Directory Traversal: All paths normalized with Paths.normalize()
- Whitelist Validation: Only approved file extensions allowed
- Session Timeout: Sessions expire after inactivity
- Password Security: PHP's password_hash() with bcrypt
- SQL Prepared Statements: All queries use parameterized statements
- PHP Sandboxing: open_basedir and disabled functions restrict PHP access
- Input Sanitization: File names sanitized to alphanumeric + underscore
Limitations and Known Issues
- Memory-Based Uploads: Entire uploads loaded into memory (not ideal for very large files)
- No Streaming Uploads: Files must complete upload before processing
- Limited Concurrent Streams: Maximum 8 video streams (configurable)
- No Built-in Backup: Manual backup required
- Single Server: No horizontal scaling or load balancing
Future Enhancement Opportunities
- SSL/TLS support (HTTPS)
- FTP/SFTP access
- Email hosting integration
- Automated backups with versioning
- Resource usage monitoring per user
- Traffic analytics and logging
- Custom domain management UI
- Node.js/Python runtime support
- WebSocket support for real-time features
- CDN integration for static assets
- Automated SSL certificate management (Let's Encrypt)
- Git integration for version control
Summary
This is a production-ready, feature-complete web hosting platform built entirely from scratch
in Java. It demonstrates advanced Java networking, custom HTTP protocol handling, multipart
form parsing, PHP CGI integration, and comprehensive file management—all wrapped in a
user-friendly web interface built with vanilla JavaScript.
The multi-tenant architecture with per-user isolation makes it suitable for hosting multiple
independent websites on a single server while maintaining security and resource boundaries.
The system handles everything from static file serving to dynamic PHP execution, database
management, blog publishing, and video streaming—providing a complete hosting solution
without relying on traditional web servers like Apache or Nginx for core functionality.
With over 3000 lines of Java code and comprehensive JavaScript modules, this project
represents a deep understanding of web protocols, server architecture, security principles,
and full-stack development. It serves as both a functional hosting platform and a learning
resource for understanding how web servers work at a fundamental level.