Coder Social home page Coder Social logo

higebu / protovalidate-java Goto Github PK

View Code? Open in Web Editor NEW

This project forked from bufbuild/protovalidate-java

0.0 1.0 0.0 2.06 MB

Protocol Buffer Validation for Java.

Home Page: https://central.sonatype.com/artifact/build.buf/protovalidate

License: Apache License 2.0

Shell 0.05% Java 97.79% Makefile 2.16%

protovalidate-java's Introduction

The Buf logo protovalidate-java

CI Conformance BSR

protovalidate-java is the Java language implementation of protovalidate designed to validate Protobuf messages at runtime based on user-defined validation constraints. Powered by Google's Common Expression Language (CEL), it provides a flexible and efficient foundation for defining and evaluating custom validation rules. The primary goal of protovalidate is to help developers ensure data consistency and integrity across the network without requiring generated code.

The protovalidate project

Head over to the core protovalidate repository for:

Other protovalidate runtime implementations include:

And others coming soon:

  • TypeScript: protovalidate-ts

Installation

To include protovalidate-java in your project, add the following to your build file:

dependencies {
    implementation 'build.buf:protovalidate:<version>'
}

Remember to always check for the latest version of protovalidate-java on the project's GitHub releases page to ensure you're using the most up-to-date version.

Usage

Implementing validation constraints

Validation constraints are defined directly within .proto files. Documentation for adding constraints can be found in the protovalidate project README and its comprehensive docs.

syntax = "proto3";

package my.package;

import "google/protobuf/timestamp.proto";
import "buf/validate/validate.proto";

message Transaction {
  uint64 id = 1 [(buf.validate.field).uint64.gt = 999];
  google.protobuf.Timestamp purchase_date = 2;
  google.protobuf.Timestamp delivery_date = 3;
  
  string price = 4 [(buf.validate.field).cel = {
    id: "transaction.price",
    message: "price must be positive and include a valid currency symbol ($ or £)",
    expression: "(this.startsWith('$') || this.startsWith('£')) && double(this.substring(1)) > 0"
  }];
  
  option (buf.validate.message).cel = {
    id: "transaction.delivery_date",
    message: "delivery date must be after purchase date",
    expression: "this.delivery_date > this.purchase_date"
  };
}

Example

In your Java code, create an instance of the Validator class and use the validate method to validate your messages.

// Import the required packages
package build.buf;

import build.buf.protovalidate.results.ValidationException;
import build.buf.protovalidate.results.ValidationResult;
import com.my.package.Transaction;
import com.google.protobuf.Timestamp;

import build.buf.protovalidate.Validator;
import build.buf.protovalidate.Config;

public class Main {

    // Create timestamps for purchase and delivery date
    Timestamp purchaseDate = Timestamp.newBuilder().build();
    Timestamp deliveryDate = Timestamp.newBuilder().build();

    // Create a transaction object using the Builder pattern
    Transaction transaction =
            Transaction.newBuilder()
                    .setId(1234)
                    .setPrice("$5.67")
                    .setPurchaseDate(purchaseDate)
                    .setDeliveryDate(deliveryDate)
                    .build();

    // Create a validator object with the default Configuration
    Validator validator = new Validator();
    // Validate the transaction object using the validator
    try {
        ValidationResult result = validator.validate(transaction);

        // Check if there are any validation violations
        if (result.violations.isEmpty()) {
            // No violations, validation successful
            System.out.println("Validation succeeded");
        } else {
            // Print the violations if any found
            System.out.println(result.toString());
        }
    } catch (ValidationException e) {
        // Catch and print any ValidationExceptions thrown during the validation process
        System.out.println("Validation failed: " + e.getMessage());
    }
}

Ecosystem

Legal

Offered under the Apache 2 license.

protovalidate-java's People

Contributors

dependabot[bot] avatar buildbreaker avatar pkwarren avatar elliotmjackson avatar plobsing avatar wreulicke avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.