Developer Guide

Complete guide for developers to set up, configure, and contribute to the Beas Rule Engine

Prerequisites

Before you begin development with the Beas Rule Engine, ensure you have the following tools and technologies installed:

1

Required Software

  • Java 17 or higher - OpenJDK or Oracle JDK
  • Maven 3.6+ - Build tool and dependency management
  • MongoDB 5.0+ - Primary database
  • Git - Version control system
  • IDE - IntelliJ IDEA, Eclipse, or VS Code
Verify Java Installation:
java -version
mvn -version
mongod --version
2

Optional Components

  • Keycloak - For OAuth2 authentication
  • Docker - For containerized deployment
  • Postman - For API testing

Installation & Setup

1

Clone Repository

# Clone the repository
git clone https://github.com/BEAS-Software-Solutions/BEASRE.git
cd beas-rule-engine

# Check out the latest release
git checkout main
2

Build Project

# Clean and compile
mvn clean compile

# Run tests
mvn test

# Build JAR file
mvn clean package

# Install to local repository
mvn clean install
3

Run Application

# Run with Maven
mvn spring-boot:run

# Or run the JAR file
java -jar target/beas-rule-engine.jar

# Run with specific profile
mvn spring-boot:run -Dspring-boot.run.profiles=dev

Configuration

1

Environment Variables

Set up environment variables for secure configuration:

Create environment file:
# Copy example file
cp env-example.sh .env

# Edit the file with your values
nano .env

# Source the environment variables
source .env
Required Environment Variables:
# MongoDB Configuration
export MONGODB_HOST=localhost
export MONGODB_PORT=27017
export MONGODB_DATABASE=beasre
export MONGODB_USERNAME=admin
export MONGODB_PASSWORD=password

# Cryptography Keys
export CRYPTO_KEY=your-32-character-key
export CRYPTO_IV=your-16-character-iv

# Server Configuration
export SERVER_PORT=8070
export SERVER_CONTEXT_PATH=/beasre

# Keycloak Configuration (Optional)
export KEYCLOAK_AUTH_SERVER_URL=http://localhost:8080/auth
export KEYCLOAK_REALM=beasre
export KEYCLOAK_RESOURCE=beas-rule-engine
2

Application Properties

Configure application properties in src/main/resources/application.yaml:

spring:
  application:
    name: beas-rule-engine
  data:
    mongodb:
      host: ${MONGODB_HOST:localhost}
      port: ${MONGODB_PORT:27017}
      database: ${MONGODB_DATABASE:beasre}
      username: ${MONGODB_USERNAME:}
      password: ${MONGODB_PASSWORD:}
      authentication-database: admin

server:
  port: ${SERVER_PORT:8070}
  servlet:
    context-path: ${SERVER_CONTEXT_PATH:/beasre}

cryptography:
  key: ${CRYPTO_KEY}
  iv: ${CRYPTO_IV}

logging:
  level:
    com.beassolution.rule: DEBUG
    org.springframework.data.mongodb: DEBUG

Development Guidelines

1

Coding Standards

Java Coding Standards:
  • Use Java 17 features (records, pattern matching, switch expressions)
  • Follow Google Java Style Guide
  • Use meaningful variable and method names
  • Add comprehensive JavaDoc comments
  • Keep methods small and focused
Example Java 17 Code:
// Use records for DTOs
public record RuleRequest(
    String ruleName,
    Map<String, Object> parameters,
    Object payload
) {
    // Validation logic
}

// Use pattern matching
public String processRule(Object rule) {
    return switch (rule) {
        case String s -> "String rule: " + s;
        case Rule r -> "Complex rule: " + r.getName();
        case null -> "Null rule";
        default -> "Unknown rule type";
    };
}
2

Project Structure

Directory Structure:
src/
├── main/
│   ├── java/
│   │   └── com/beassolution/rule/
│   │       ├── advice/           # Global advice and exception handling
│   │       ├── components/       # Core components (cache, crypto)
│   │       ├── config/          # Configuration classes
│   │       ├── controller/      # REST controllers
│   │       ├── crypto/          # Cryptography services
│   │       ├── dto/             # Data transfer objects
│   │       ├── engine/          # Rule engine core
│   │       ├── exception/       # Custom exceptions
│   │       ├── listener/        # Event listeners
│   │       ├── model/           # Entity models
│   │       ├── repository/      # Data access layer
│   │       ├── rsql/            # RSQL query support
│   │       ├── service/         # Business logic services
│   │       └── util/            # Utility classes
│   └── resources/
│       ├── application.yaml     # Application configuration
│       └── application-*.yaml   # Profile-specific configs
└── test/
    └── java/
        └── com/beassolution/rule/
            ├── controller/       # Controller tests
            ├── service/          # Service tests
            └── integration/      # Integration tests
3

Adding New Features

Feature Development Process:
  1. Create a feature branch from main
  2. Implement the feature following the layered architecture
  3. Add comprehensive tests
  4. Update documentation
  5. Create a pull request
Example Feature Implementation:
// 1. Create model
@Entity
public class NewFeature {
    @Id
    private String id;
    private String name;
    // ... other fields
}

// 2. Create repository
@Repository
public interface NewFeatureRepository extends MongoRepository<NewFeature, String> {
    // Custom queries
}

// 3. Create service
@Service
public class NewFeatureService extends BaseService<NewFeature> {
    // Business logic
}

// 4. Create controller
@RestController
@RequestMapping("/api/v1/new-feature")
public class NewFeatureController extends BaseController<NewFeature> {
    // REST endpoints
}

Testing

1

Unit Testing

Write comprehensive unit tests for all components:

Example Unit Test:
@ExtendWith(MockitoExtension.class)
class RuleEngineServiceTest {
    
    @Mock
    private RuleRepository ruleRepository;
    
    @InjectMocks
    private RuleEngineService ruleEngineService;
    
    @Test
    void testEvaluateRule() {
        // Given
        RuleRequest request = new RuleRequest("test-rule", Map.of(), "payload");
        Rule rule = new Rule("test-rule", "return true;");
        
        when(ruleRepository.findByName("test-rule")).thenReturn(Optional.of(rule));
        
        // When
        RuleResponse response = ruleEngineService.evaluateRule(request);
        
        // Then
        assertThat(response).isNotNull();
        assertThat(response.getResult()).isEqualTo(true);
        verify(ruleRepository).findByName("test-rule");
    }
}
2

Integration Testing

Example Integration Test:
@SpringBootTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class RuleEngineIntegrationTest {
    
    @Autowired
    private TestRestTemplate restTemplate;
    
    @Test
    void testRuleEvaluationEndpoint() {
        // Given
        RuleRequest request = new RuleRequest("test-rule", Map.of(), "payload");
        
        // When
        ResponseEntity<RuleResponse> response = restTemplate.postForEntity(
            "/beasre/v1/rule-engine/evaluate",
            request,
            RuleResponse.class
        );
        
        // Then
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getBody()).isNotNull();
    }
}
3

Running Tests

# Run all tests
mvn test

# Run specific test class
mvn test -Dtest=RuleEngineServiceTest

# Run tests with coverage
mvn test jacoco:report

# Run integration tests
mvn test -Dtest=*IntegrationTest

Deployment

1

Docker Deployment

Build Docker Image:
# Build the application
mvn clean package

# Build Docker image
docker build -t beas-rule-engine .

# Run container
docker run -d \
  --name beas-rule-engine \
  -p 8070:8070 \
  -e MONGODB_HOST=mongodb \
  -e CRYPTO_KEY=your-key \
  -e CRYPTO_IV=your-iv \
  beas-rule-engine
2

Kubernetes Deployment

Kubernetes YAML:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: beas-rule-engine
spec:
  replicas: 3
  selector:
    matchLabels:
      app: beas-rule-engine
  template:
    metadata:
      labels:
        app: beas-rule-engine
    spec:
      containers:
      - name: beas-rule-engine
        image: beas-rule-engine:latest
        ports:
        - containerPort: 8070
        env:
        - name: MONGODB_HOST
          value: "mongodb-service"
        - name: CRYPTO_KEY
          valueFrom:
            secretKeyRef:
              name: beas-secrets
              key: crypto-key

Contributing

1

Contribution Guidelines

How to Contribute:
  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Update documentation
  7. Submit a pull request
Code Review Process:
  • All changes require code review
  • Ensure code follows style guidelines
  • Add appropriate tests
  • Update relevant documentation
2

Issue Reporting

When reporting issues, please include:

  • Detailed description of the problem
  • Steps to reproduce
  • Expected vs actual behavior
  • Environment details (OS, Java version, etc.)
  • Logs and error messages