Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion LEARNINGS.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,37 @@ banks: ["Chase", "Wells Fargo"]

**Benefit**: Catches configuration issues before writing hundreds of lines of code.

### 4. YAML numeric values cause `ClassCastException` in `fetchString()`

**Problem**: Unquoted single-digit numbers in YAML are parsed as integers, not strings. Calling `fetchString()` on them throws `ClassCastException: Integer cannot be cast to String` at runtime.

**Wrong**:
```yaml
doors: [1, 2, 3, 4]
```

**Correct**:
```yaml
doors: ['1', '2', '3', '4']
```

**Rule**: Always quote values in YAML lists that will be accessed via `fetchString()`, even if they look numeric.

### 5. Use `bothify(pattern, true)` for uppercase license plates / codes

**Problem**: `bothify(pattern)` substitutes `?` placeholders with **lowercase** letters, producing values like `"g99-seb5"` instead of `"G99-SEB5"`.

**Solution**: Pass `true` as the second argument to get uppercase output:
```java
// Wrong — generates lowercase letters
return faker.bothify(pattern);

// Correct — generates uppercase letters
return faker.bothify(pattern, true);
```

**When to use**: Any time the generated string should be uppercase (license plates, tracking numbers, codes). See `Shipping.trackingNumberUps()` for the established pattern in this codebase.

---

*Last updated: 2026-02-09*
*Last updated: 2026-02-28*
12 changes: 6 additions & 6 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -81,19 +81,19 @@ yaml-check:
fi
for file in $yaml_files; do
if ! ./mvnw validate -f "$file" &>/dev/null; then
# Fallback to basic syntax check using Python or yq if available
if command -v python3 &>/dev/null; then
python3 -c "import yaml; yaml.safe_load(open('$file'))" || {
# Fallback to basic syntax check using yq or Python if available
if command -v yq &>/dev/null; then
yq eval "$file" > /dev/null || {
echo "YAML validation failed for: $file"
exit 1
}
elif command -v yq &>/dev/null; then
yq eval "$file" > /dev/null || {
elif python3 -c "import yaml" &>/dev/null 2>&1; then
python3 -c "import yaml; yaml.safe_load(open('$file'))" || {
echo "YAML validation failed for: $file"
exit 1
}
else
echo "Warning: No YAML validator available (install python3 or yq)"
echo "Warning: No YAML validator available (install yq or python3 pyyaml)"
exit 0
fi
fi
Expand Down
11 changes: 11 additions & 0 deletions src/main/java/org/thejavaguy/javafaker/Faker.java
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ public class Faker {
private final EnglandFootBall englandfootball;
private final Mountain mountain;
private final Shipping shipping;
private final Vehicle vehicle;

public Faker() {
this(Locale.ENGLISH);
Expand Down Expand Up @@ -226,6 +227,7 @@ public Faker(FakeValuesService fakeValuesService, RandomService random) {
this.englandfootball = new EnglandFootBall(this);
this.mountain = new Mountain(this);
this.shipping = new Shipping(this);
this.vehicle = new Vehicle(this);
}

/**
Expand Down Expand Up @@ -726,6 +728,15 @@ public Shipping shipping() {
return shipping;
}

/**
* Returns a Vehicle instance for generating vehicle-related fake data.
*
* @return a {@link Vehicle} instance
*/
public Vehicle vehicle() {
return vehicle;
}

public String resolve(String key) {
return this.fakeValuesService.resolve(key, this, this);
}
Expand Down
187 changes: 187 additions & 0 deletions src/main/java/org/thejavaguy/javafaker/Vehicle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
package org.thejavaguy.javafaker;

/**
* Generates realistic vehicle-related fake data.
*
* @since 1.x.x
*/
public class Vehicle {

private final Faker faker;

protected Vehicle(Faker faker) {
this.faker = faker;
}

/**
* Returns a random vehicle manufacturer name.
*
* @return vehicle make, e.g., "Toyota", "BMW"
*/
public String make() {
return faker.fakeValuesService().fetchString("vehicle.makes");
}

/**
* Returns a random vehicle model name.
*
* @return vehicle model, e.g., "Camry", "Mustang"
*/
public String model() {
return faker.fakeValuesService().fetchString("vehicle.models");
}

/**
* Returns a random make and model combination.
*
* @return make and model, e.g., "Toyota Camry"
*/
public String makeAndModel() {
return make() + " " + model();
}

/**
* Returns a random vehicle color.
*
* @return color name, e.g., "Red", "Metallic Gray"
*/
public String color() {
return faker.fakeValuesService().fetchString("vehicle.colors");
}

/**
* Returns a random fuel type.
*
* @return fuel type, e.g., "Gasoline", "Electric"
*/
public String fuelType() {
return faker.fakeValuesService().fetchString("vehicle.fuel_types");
}

/**
* Returns a random transmission type.
*
* @return transmission type, e.g., "Automatic", "Manual"
*/
public String transmission() {
return faker.fakeValuesService().fetchString("vehicle.transmissions");
}

/**
* Returns a random drive type.
*
* @return drive type, e.g., "All-Wheel Drive"
*/
public String driveType() {
return faker.fakeValuesService().fetchString("vehicle.drive_types");
}

/**
* Returns a random vehicle type/body style.
*
* @return vehicle type, e.g., "Sedan", "SUV"
*/
public String vehicleType() {
return faker.fakeValuesService().fetchString("vehicle.vehicle_types");
}

/**
* Returns a random door count.
*
* @return door count as string, e.g., "4", "2"
*/
public String doors() {
return faker.fakeValuesService().fetchString("vehicle.doors");
}

/**
* Returns a random car option/feature.
*
* @return car option, e.g., "Sunroof", "Navigation System"
*/
public String carOption() {
return faker.fakeValuesService().fetchString("vehicle.car_options");
}

/**
* Returns a random standard specification.
*
* @return standard spec, e.g., "Air Conditioning", "ABS Brakes"
*/
public String standardSpec() {
return faker.fakeValuesService().fetchString("vehicle.standard_specs");
}

/**
* Generates a random 17-character VIN (Vehicle Identification Number). Follows the standard VIN
* format: WMI (3) + VDS (6) + VIS (8). Uses valid WMI characters (no I, O, Q in positions 1-3,
* 10).
*
* @return a 17-character VIN string, e.g., "1HGBH41JXMN109186"
*/
public String vin() {
return faker.regexify("[A-HJ-NPR-Z0-9]{17}");
}

/**
* Generates a random license plate number based on common patterns.
*
* @return license plate, e.g., "ABC-1234", "123 XYZ"
*/
public String licensePlate() {
String pattern = faker.fakeValuesService().fetchString("vehicle.license_plate_patterns");
return faker.bothify(pattern, true);
}

/**
* Returns a random model year between the specified range.
*
* @param minYear minimum year (inclusive)
* @param maxYear maximum year (inclusive)
* @return a year between minYear and maxYear
*/
public int year(int minYear, int maxYear) {
return faker.random().nextInt(maxYear - minYear + 1) + minYear;
}

/**
* Returns a random model year between 1990 and current year.
*
* @return a model year
*/
public int year() {
int currentYear = java.time.Year.now().getValue();
return year(1990, currentYear);
}

/**
* Returns a random mileage/odometer reading.
*
* @param min minimum mileage
* @param max maximum mileage
* @return mileage value
*/
public int mileage(int min, int max) {
return faker.random().nextInt(max - min + 1) + min;
}

/**
* Returns a random mileage between 0 and 200,000.
*
* @return mileage value
*/
public int mileage() {
return mileage(0, 200000);
}

/**
* Returns a random engine displacement in liters.
*
* @return engine size string, e.g., "2.0L", "3.5L"
*/
public String engine() {
double[] sizes = {1.0, 1.4, 1.5, 1.6, 1.8, 2.0, 2.4, 2.5, 3.0, 3.5, 4.0, 5.0, 5.7, 6.2};
double size = sizes[faker.random().nextInt(sizes.length)];
return String.format("%.1fL", size);
}
}
5 changes: 4 additions & 1 deletion src/main/resources/en/vehicle.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ en:
car_types: ['Cargo Van', 'Convertible', 'Coupe', 'Crew Cab Pickup', 'Extended Cab Pickup', 'Hatchback', 'Minivan', 'Passenger Van', 'Regular Cab Pickup', 'SUV', 'Sedan', 'Wagon']
car_options: ['A/C: Front', 'Airbag: Driver', 'AM/FM Stereo', 'A/C: Rear', 'Airbag: Passenger', 'Cassette Player', 'Cruise Control', 'Airbag: Side', 'CD (Single Disc)', 'Navigation', 'Alarm', 'CD (Multi Disc)', 'Power Locks', 'Antilock Brakes', 'MP3 (Single Disc)', 'Power Steering', 'Fog Lights', 'MP3 (Multi Disc)', 'Keyless Entry', 'Premium Sound', 'Integrated Phone', 'DVD System', 'Bucket Seats', 'Power Windows', 'Alloy Wheels', 'Leather Interior', 'Rear Window Defroster', 'Moonroof/Sunroof', 'Memory Seats', 'Rear Window Wiper', 'Third Row Seats', 'Power Seats', 'Tinted Glass', 'Tow Package']
standard_specs: ["1.8L DOHC 16-valve I4 engine -inc: engine cover", "Engine mounts -inc: (2) solid, (1) liquid-filled", "Front wheel drive", "Battery saver", "Independent strut front suspension w/stabilizer bar", "Torsion beam rear suspension w/stabilizer bar", "Electric speed-sensitive variable-assist pwr steering", "Pwr front vented disc/rear drum brakes", "Compact spare tire", "Body color front/rear bumpers", "Multi-reflector halogen headlamps", "Body color folding remote-controlled pwr mirrors", "Variable intermittent windshield wipers w/mist function", "Intermittent rear wiper w/washer", "Body color door handles", "Roof mounted antenna", "Reclining front bucket seats -inc: active head restraints, double-thickness foam in front seats", "60/40 split fold-down rear seat w/outboard adjustable headrests", "Dual front & rear cup holders", "Tilt steering column", "Silver accent IP trim finisher -inc: silver shifter finisher", "Tachometer", "Fasten seat belt warning light/chime", "Pwr windows", "Remote fuel lid release", "Immobilizer system", "Pwr rear liftgate release", "Air conditioning w/in-cabin microfilter", "Rear window defroster w/timer", "12V pwr outlet", "Silver finish interior door handles", "Driver & front passenger map pockets", "Rear passenger map pockets", "Front & rear passenger folding assist grips", "Carpeted floor & cargo area", "Cargo area lamp", "Anti-lock brake system (ABS) -inc: electronic brake force distribution (EBD), brake assist", "Energy absorbing front/rear bumpers", "Steel side-door impact beams", "Zone body construction -inc: front/rear crumple zones, hood deformation point", "Dual-stage front airbags w/occupant classification system", "Front side-impact airbags", "Front & rear side curtain airbags", "3-point ELR driver seat belt w/pretensioner & load limiter", "3-point ELR/ALR front passenger seat belt w/pretensioner & load limiter", "3-point ELR/ALR rear seat belts at all positions", "Child safety rear door locks", "Rear child seat tether anchors (LATCH)", "Tire pressure monitoring system (TPMS)", "Energy absorbing steering column", "4.6L DOHC 32-valve V8 engine -inc: DI & SFI dual fuel injection, dual variable valve timing w/intelligence & electronically controlled intake (VVT-iE), aluminum block & heads", "Vibration-dampening liquid-filled engine mounts", "Electronic throttle control system w/intelligence (ETCS-i)", "Acoustic control induction system (ACIS)", "8-speed automatic transmission -inc: intelligence (ECT-i), gated shifter, sequential sport-shift mode", "Full-time all-wheel drive", "Front/rear aluminum multi-link double joint suspension w/coil springs", "Front/rear stabilizer bars", "Electric pwr rack & pinion steering (EPS)", "4-wheel ventilated pwr disc brakes -inc: brake override system", "Dual chrome exhaust tips", "Tool kit", "P235/50R18 all-season tires", "Full-size spare tire w/aluminum alloy wheel", "Scratch-resistant paint clearcoating", "Pwr tilt/slide moonroof -inc: 1-touch open/close", "1-piece chrome window surround", "Xenon high-intensity discharge (HID) headlamps -inc: adaptive front lighting system, delayed auto-off", "Integrated fog lamps", "LED lights -inc: brake lamps, tail lamps, license plate", "Electrochromic pwr folding heated mirrors w/memory -inc: puddle lamps, integrated turn signals, auto reverse tilt-down", "Acoustic glass windshield", "Water-repellent windshield & front door glass", "Laminated side window glass", "Rain-sensing wipers", "XM satellite radio receiver -inc: 90 day trial subscription", "Rear bench seat -inc: (3) adjustable headrests", "Center console", "Optitron electroluminescent instrumentation", "Multi-info display -inc: driving range, average MPG, current MPG, average speed, outside temp, elapsed time, maintenance & diagnostic messages", "Eco drive indicator", "Pwr windows -inc: 1-touch open/close", "HomeLink universal transceiver", "Dual-zone automatic climate control system -inc: smog sensor, auto recirculation, clear air filter, pollen filter", "Rear-window defogger w/auto-off timer", "(2) aux 12V pwr outlets -inc: (1) in center console, (1) w/cigarette lighter", "Grain-matched wood trim -inc: center console, dash, door panels", "Electrochromic rearview mirror", "Foldable front door storage pockets", "Dual front illuminated visor vanity mirrors", "Front/rear spot-lamp illumination", "4-wheel/4-channel anti-lock brake system (ABS)", "Electronic control braking (ECB)", "Electronic brakeforce distribution (EBD) w/brake assist (BA) -inc: Smart stop technology", "Electronic parking brake", "Vehicle dynamics integrated management (VDIM) system -inc: vehicle stability control (VSC), traction control (TRAC)", "Front/rear crumple zones", "Daytime running lights (DRL)", "Side-impact door beams", "Dual front 2-stage airbags -inc: passenger occupant classification system w/twin-chamber airbag", "Front/rear side curtain airbags", "Dual front knee airbags", "Back-up camera", "All-position 3-point seat belts -inc: outboard pretensioners & force limiters, dual front pwr shoulder height adjusters, rear outboard emergency auto locking retractors, driver emergency locking retractor", "Child restraint seat anchors for outboard positions", "Rear door child safety locks", "Direct-type tire pressure monitor system", "Impact-dissipating upper interior trim", "Collapsible steering column", "Emergency interior trunk release", "First aid kit", "6.1L SRT V8 \"Hemi\" engine", "3.73 axle ratio", "Quadra-Trac active on demand 4WD system", "200mm front axle", "Dana 44/226mm rear axle", "625-amp maintenance-free battery", "160-amp alternator", "Tip start system", "Pwr accessory delay", "Trailer tow wiring harness", "High performance suspension", "Pwr steering cooler", "Pwr rack & pinion performance tuned steering", "Anti-lock 4-wheel performance disc brakes", "Brake assist", "Dual bright exhaust tips", "Run flat tires", "20\" x 9.0\" front & 20\" x 10.0\" rear aluminum wheels", "Monotone paint", "Black roof molding", "Rear body-color spoiler", "Body color grille", "Chrome bodyside molding", "Black windshield molding", "Body color fascias w/bright insert", "Body color sill extension", "Fog lamps", "Front door tinted glass", "\"Flipper\" liftgate glass", "Rear window wiper/washer", "Body color front license plate brow", "Body color door handles", "6.5\" touch screen display", "Fixed long mast antenna", "Pwr 8-way driver seat w/4-way front passenger seat", "60/40 folding rear seat", "Full-length floor console", "Luxury front & rear floor mats w/logo", "Floor carpeting", "Tilt/telescoping steering column", "Leather-wrapped steering wheel w/audio controls", "Instrument cluster w/tachometer", "Vehicle info center", "Traveler/mini trip computer", "Pwr front windows w/(1) touch up/down feature", "Speed control", "Sentry Key theft deterrent system", "Security alarm", "Bright pedals", "Rear window defroster", "Locking glove box", "Highline door trim panel", "Cloth covered headliner", "Overhead console", "Dual illuminated visor vanity mirrors", "Universal garage door opener", "Passenger assist handles", "Deluxe insulation group", "Cargo compartment lamp", "Glove box lamp", "Rear reading & courtesy lamps", "Illuminated entry", "Leather-wrapped shift knob", "Leather-wrapped parking brake handle", "Carpeted cargo area", "Trim-panel-mounted storage net", "Cargo-area tie down loops", "Cargo compartment cover", "Reversible/waterproof cargo storage", "Driver & front passenger advanced multistage airbags w/occupant sensors", "Supplemental side curtain air bags", "Enhanced accident response system unlocks the doors, shuts off the fuel pump and turns on interior lights after airbag deploys", "3-point rear center seat belts", "Child seat upper tether anchorages", "LATCH-ready child seat anchor system", "Child safety rear door locks", "Dual note horn", "Tire pressure monitoring display"]
doors: [1, 2, 3, 4]
doors: ['1', '2', '3', '4']
engine_sizes: [4, 6, 8]
license_plate: '???-####'
license_plate_by_state:
Expand Down Expand Up @@ -77,4 +77,7 @@ en:
WV: ['#?-####', '#??-###', '##?-###', '??-####', '???-###', '?#?-###']
WI: ['???-####', '#####K', '#####T']
WY: ['#-#####', '1#-#####', '2[0-3]-#####', '99-#####', 'DV-####', '####', 'GS###', 'PHS-####', 'WYO-####', 'AF###', 'AR###', 'CG###', 'MC###', 'MM###', 'NA###']
models: ['Camry', 'Accord', 'Civic', 'Corolla', 'F-150', 'Silverado', 'RAV4', 'CR-V', 'Mustang', 'Camaro', '3 Series', '5 Series', 'C-Class', 'E-Class', 'A4', 'Q5', 'Golf', 'Jetta', 'Altima', 'Rogue', 'Elantra', 'Tucson', 'Sportage', 'Outback', 'CX-5', 'RX', 'Wrangler', 'Grand Cherokee', 'Model 3', 'Model Y', 'Model S', 'Model X']
vehicle_types: ['Sedan', 'SUV', 'Truck', 'Coupe', 'Convertible', 'Hatchback', 'Wagon', 'Van', 'Minivan', 'Crossover', 'Sports Car', 'Luxury', 'Electric']
license_plate_patterns: ['???-####', '### ???', '?##-???#', '##?-?##?']
cylinder_engine: 'Cylinder Engine'
Loading