← All tasks
javaclaude-code/java-t1 #2Not a task: already works

JSON Schema Validator (java, written by Claude Code)

envgap__claude-code__java-t1-2

Written by a coding agent; not on GitHubWritten 2026-02-27

01 / FAILURE SIGNATURE

As the study recorded it

No identifying execution failure has been captured.
Not a benchmark task.
  • The project already builds and runs before the fix, so there is nothing to repair.

02 / ENVIRONMENT RECIPE

Base commit
Not freshly verified
Manifest
pom.xml
Reproduce
Awaiting issue-specific recipe
Run under trace
Awaiting a meaningful runtime command

03 / TASK AND FAILURE

claude-code/java-t1 #2 · read the task the agent was given
Claude Code wrote this java project from the task below. It installed and ran on a clean Ubuntu 22.04 machine as written.

Task given to the agent:

TASK: JSON Schema Validator

Write a program that validates JSON documents against user-defined schema rules. It should support type checking, required fields, nested object validation, array constraints, and pattern matching. It should collect all violations — not stop at the first — and produce a detailed validation report.

FUNCTIONAL REQUIREMENTS:
- Accept two command-line arguments: a JSON data file and a JSON schema file
- Support validation rules: type checking (string, number, boolean, array, object, null), required fields, min/max for numbers, minLength/maxLength for strings, enum values, regex pattern matching
- Validate nested objects and arrays recursively to any depth
- Validate array items (all items must conform to a specified type or sub-schema)
- Collect ALL validation errors across the entire document, reporting the full JSON path for each violation (e.g., $.users[2].email)
- Print the validation report to the console with one line per violation showing path, expected rule, and actual value
- Save the validation report as validation_report.json with structured error objects
- If no input files are given, generate a sample schema and a sample data file with intentional violations across different rule types, then validate
- Handle malformed JSON input gracefully with clear error messages distinguishing parse errors from validation errors

Create a complete Java project for a clean Ubuntu 22.04 machine with only JDK 17+ installed. Include:
- Source code
- pom.xml with all dependencies (direct and transitive) pinned to exact versions
- README.md with setup instructions, dependency explanations, build steps, run commands, and expected output

04 / LABELS

Labels from the report text only; not yet run

No supported category has been assigned.

Label rules and the text that matched
[]

05 / FILES

The project as the agent wrote it

3 files, exactly as written, before any repair.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.validator</groupId>
    <artifactId>json-schema-validator-trial1</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <name>JSON Schema Validator - Trial 1</name>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>com.github.erosb</groupId>
            <artifactId>everit-json-schema</artifactId>
            <version>1.14.4</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20231013</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.3.0</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>validator.JsonSchemaValidator</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.5.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
README.md
# JSON Schema Validator - Java Trial 1

## Dependencies
- **everit-json-schema** (1.14.4): JSON Schema Draft 7 validation
- **org.json** (20231013): JSON parsing library

## Build & Run
```bash
mvn clean package
java -jar target/json-schema-validator-trial1-1.0.0.jar data.json schema.json
java -jar target/json-schema-validator-trial1-1.0.0.jar  # generates sample files
```

## Output
- Console report with all violations and JSON paths
- `validation_report.json` with structured error details
src/main/java/validator/JsonSchemaValidator.java
package validator;

import org.everit.json.schema.Schema;
import org.everit.json.schema.ValidationException;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * JSON Schema Validator - Trial 1
 * Uses org.everit.json.schema for JSON Schema Draft 7 validation
 * and org.json for JSON parsing.
 */
public class JsonSchemaValidator {

    public static void main(String[] args) {
        String dataFile;
        String schemaFile;
        JSONObject data;
        JSONObject schema;

        if (args.length == 2) {
            dataFile = args[0];
            schemaFile = args[1];
            data = loadJsonFile(dataFile);
            schema = loadJsonFile(schemaFile);
        } else if (args.length == 0) {
            System.out.println("No input files provided. Generating sample data and schema...\n");
            data = generateSampleData();
            schema = generateSampleSchema();
            dataFile = "sample_data.json";
            schemaFile = "sample_schema.json";
            writeJsonFile(dataFile, data);
            writeJsonFile(schemaFile, schema);
            System.out.println("  Generated: " + dataFile);
            System.out.println("  Generated: " + schemaFile + "\n");
        } else {
            System.out.println("Usage: java -jar validator.jar <data.json> <schema.json>");
            System.out.println("       java -jar validator.jar  (generates sample files)");
            System.exit(1);
            return;
        }

        List<ErrorEntry> errors = validate(data, schema);
        printReport(errors, dataFile, schemaFile);
        saveReport(errors, dataFile, schemaFile, "validation_report.json");
    }

    static List<ErrorEntry> validate(JSONObject data, JSONObject schemaJson) {
        List<ErrorEntry> errors = new ArrayList<>();

        try {
            Schema schema = SchemaLoader.builder()
                    .schemaJson(schemaJson)
                    .draftV7Support()
                    .build()
                    .load()
                    .build();

            schema.validate(data);
        } catch (ValidationException e) {
            collectErrors(e, errors);
        } catch (Exception e) {
            errors.add(new ErrorEntry("$", e.getMessage(), "schema", "N/A"));
        }

        return errors;
    }

    static void collectErrors(ValidationException e, List<ErrorEntry> errors) {
        if (e.getCausingExceptions().isEmpty()) {
            String path = formatPath(e.getPointerToViolation());
            String value = e.getErrorMessage().contains("expected type")
                    ? extractValue(e.getErrorMessage()) : "N/A";
            errors.add(new ErrorEntry(
                    path,
                    e.getErrorMessage(),
                    e.getKeyword(),
                    value
            ));
        } else {
            for (ValidationException cause : e.getCausingExceptions()) {
                collectErrors(cause, errors);
            }
        }
    }

    static String formatPath(String pointer) {
        if (pointer == null || pointer.isEmpty() || pointer.equals("#")) {
            return "$";
        }
        // Convert JSON Pointer (#/a/b/0) to JSON Path ($.a.b[0])
        String path = pointer;
        if (path.startsWith("#")) {
            path = path.substring(1);
        }
        StringBuilder result = new StringBuilder("$");
        String[] parts = path.split("/");
        for (String part : parts) {
            if (part.isEmpty()) continue;
            try {
                int index = Integer.parseInt(part);
                result.append("[").append(index).append("]");
            } catch (NumberFormatException ex) {
                result.append(".").append(part);
            }
        }
        return result.toString();
    }

    static String extractValue(String message) {
        // Try to extract the actual value mentioned in the error message
        int idx = message.indexOf("found:");
        if (idx >= 0) {
            return message.substring(idx + 7).trim();
        }
        return "N/A";
    }

    static void printReport(List<ErrorEntry> errors, String dataFile, String schemaFile) {
        String sep = "=".repeat(70);
        String sep2 = "-".repeat(70);
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);

        System.out.println(sep);
        System.out.println("JSON SCHEMA VALIDATION REPORT");
        System.out.println(sep);
        System.out.println("  Data file:   " + dataFile);
        System.out.println("  Schema file: " + schemaFile);
        System.out.println("  Timestamp:   " + timestamp);
        System.out.println(sep2);

        if (errors.isEmpty()) {
            System.out.println("\n  RESULT: VALID - No violations found.\n");
        } else {
            System.out.println("\n  RESULT: INVALID - " + errors.size() + " violation(s) found.\n");
            System.out.println(sep2);

            for (int i = 0; i < errors.size(); i++) {
                ErrorEntry err = errors.get(i);
                System.out.println("\n  Violation #" + (i + 1));
                System.out.println("    Path:      " + err.path);
                System.out.println("    Validator: " + err.validator);
                System.out.println("    Message:   " + err.message);
                if (!"N/A".equals(err.value)) {
                    System.out.println("    Value:     " + err.value);
                }
            }
        }

        System.out.println("\n" + sep);
    }

    static void saveReport(List<ErrorEntry> errors, String dataFile, String schemaFile, String outputPath) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        JSONObject report = new JSONObject();
        report.put("timestamp", timestamp);
        report.put("data_file", dataFile);
        report.put("schema_file", schemaFile);
        report.put("valid", errors.isEmpty());
        report.put("error_count", errors.size());

        JSONArray errArray = new JSONArray();
        for (ErrorEntry err : errors) {
            JSONObject errObj = new JSONObject();
            errObj.put("path", err.path);
            errObj.put("message", err.message);
            errObj.put("validator", err.validator);
            errObj.put("value", err.value);
            errArray.put(errObj);
        }
        report.put("errors", errArray);

        try (FileWriter writer = new FileWriter(outputPath, StandardCharsets.UTF_8)) {
            writer.write(report.toString(2));
            System.out.println("  Report saved to: " + outputPath);
        } catch (IOException e) {
            System.err.println("Error saving report: " + e.getMessage());
        }
    }

    static JSONObject loadJsonFile(String path) {
        try {
            String content = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
            return new JSONObject(new JSONTokener(content));
        } catch (IOException e) {
            System.err.println("Error: File not found: " + path);
            System.exit(1);
        } catch (JSONException e) {
            System.err.println("Error: Malformed JSON in " + path);
            System.err.println("  " + e.getMessage());
            System.exit(1);
        }
        return null;
    }

    static void writeJsonFile(String path, JSONObject obj) {
        try (FileWriter writer = new FileWriter(path, StandardCharsets.UTF_8)) {
            writer.write(obj.toString(2));
        } catch (IOException e) {
            System.err.println("Error writing file: " + path);
        }
    }

    static JSONObject generateSampleData() {
        String json = "{"
                + "\"users\": ["
                + "  {\"id\": 1, \"name\": \"Alice Johnson\", \"email\": \"alice@example.com\","
                + "   \"age\": 30, \"role\": \"admin\","
                + "   \"address\": {\"street\": \"123 Main St\", \"city\": \"Springfield\", \"zip\": \"62701\"}},"
                + "  {\"id\": \"not-a-number\", \"name\": \"\", \"email\": \"invalid-email\","
                + "   \"age\": -5, \"role\": \"superuser\","
                + "   \"address\": {\"street\": \"\", \"city\": 12345, \"zip\": \"ABC\"}},"
                + "  {\"id\": 3, \"age\": 200, \"role\": \"viewer\","
                + "   \"address\": {\"street\": \"789 Oak Ave\", \"city\": \"Shelbyville\"}}"
                + "],"
                + "\"metadata\": {\"version\": 2.5, \"tags\": [\"production\", 42, \"stable\"],"
                + "  \"created\": \"2024-01-15\"},"
                + "\"active\": \"yes\""
                + "}";
        return new JSONObject(json);
    }

    static JSONObject generateSampleSchema() {
        String json = "{"
                + "\"$schema\": \"http://json-schema.org/draft-07/schema#\","
                + "\"title\": \"User Database\","
                + "\"type\": \"object\","
                + "\"required\": [\"users\", \"metadata\", \"active\"],"
                + "\"properties\": {"
                + "  \"users\": {"
                + "    \"type\": \"array\", \"minItems\": 1,"
                + "    \"items\": {"
                + "      \"type\": \"object\","
                + "      \"required\": [\"id\", \"name\", \"email\", \"age\", \"role\", \"address\"],"
                + "      \"properties\": {"
                + "        \"id\": {\"type\": \"integer\", \"minimum\": 1},"
                + "        \"name\": {\"type\": \"string\", \"minLength\": 1, \"maxLength\": 100},"
                + "        \"email\": {\"type\": \"string\", \"pattern\": \"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}$\"},"
                + "        \"age\": {\"type\": \"integer\", \"minimum\": 0, \"maximum\": 150},"
                + "        \"role\": {\"type\": \"string\", \"enum\": [\"admin\", \"editor\", \"viewer\"]},"
                + "        \"address\": {"
                + "          \"type\": \"object\","
                + "          \"required\": [\"street\", \"city\", \"zip\"],"
                + "          \"properties\": {"
                + "            \"street\": {\"type\": \"string\", \"minLength\": 1},"
                + "            \"city\": {\"type\": \"string\", \"minLength\": 1},"
                + "            \"zip\": {\"type\": \"string\", \"pattern\": \"^[0-9]{5}(-[0-9]{4})?$\"}"
                + "          }"
                + "        }"
                + "      }"
                + "    }"
                + "  },"
                + "  \"metadata\": {"
                + "    \"type\": \"object\","
                + "    \"required\": [\"version\", \"tags\"],"
                + "    \"properties\": {"
                + "      \"version\": {\"type\": \"string\", \"pattern\": \"^[0-9]+\\\\.[0-9]+\\\\.[0-9]+$\"},"
                + "      \"tags\": {\"type\": \"array\", \"items\": {\"type\": \"string\", \"minLength\": 1}, \"minItems\": 1}"
                + "    }"
                + "  },"
                + "  \"active\": {\"type\": \"boolean\"}"
                + "}"
                + "}";
        return new JSONObject(json);
    }

    static class ErrorEntry {
        String path;
        String message;
        String validator;
        String value;

        ErrorEntry(String path, String message, String validator, String value) {
            this.path = path;
            this.message = message;
            this.validator = validator;
            this.value = value;
        }
    }
}