Skip to content

Java library for working with Schema.org data in JSON-LD format

License

Notifications You must be signed in to change notification settings

Kobee1203/schema-org-java

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Schema.org Java library

Schema-org-java is a library for creating schema.org entities.

The entities can be easily generated with the maven plugin, programmatically, or in command line.

The entities can be easily serialized and deserialized with JSON-LD format by using the JSON-LD serializer in the library.

The library has the following features:

  • Fully supports the vocabulary defined in the http://schema.org namespace.
  • Fully supports type multiple inheritance, multiple values per property in http://schema.org.
  • Every schema.org type has a corresponding Java interface which provides convenient getter/setter methods for getting/setting the values of the properties of that particular type.
  • Supports the generation of all Schema.org types at once, or specific ones.
  • Fully supports Schema.org documentation of types and properties by adding Javadoc on generated classes and methods.
  • Supports different versions of the Schema.org vocabulary.
  • Supports serializing and deserializing schema.org objects to and from JSON-LD formats.
schema-org-java.mp4

GitHub repo size GitHub code size in bytes

Build Libraries.io dependency status for GitHub repo

Code Coverage Sonar Quality Gate Sonar Tech Debt Sonar Violations

GitHub release (latest by date including pre-releases) Downloads Maven Central

The library allows to generate Schema.org types in several ways.

Add the plugin to your project->build->plugins section (default phase is generate-sources phase).

Generate all Schema.org entities:

<plugin>
  <groupId>com.weedow</groupId>
  <artifactId>schema-org-generator-maven-plugin</artifactId>
  <version>${schema-org-generator-maven-plugin.version}</version>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Generate specific Schema.org entities:

<plugin>
  <groupId>com.weedow</groupId>
  <artifactId>schema-org-generator-maven-plugin</artifactId>
  <version>${schema-org-generator-maven-plugin.version}</version>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <models>Hotel</models>
      </configuration>
    </execution>
  </executions>
</plugin>

Note: The previous example will generate all classes required by the Hotel type.

Plugin Configuration parameters

Option Description Default value
verbose Enable verbose mode. false
schemaVersion Schema version to be used for generation. eg. 13.0 (see Schema.org releases).
Specify the value latest to use the lastest version.
Local resource named schemaorg-current-https.jsonld present in the classpath
schemaResource Schema resource location to be used for generation. The value can be either a "classpath:" pseudo URL, a "file:" URL, or a plain file path. If not defined, uses the 'schemaVersion' parameter.
models A comma separated list of models to generate. All models
output Location of the output directory. ${project.build.directory}/generated-sources/schemaorg
modelPackage Package of the models org.schema.model
modelImplPackage Package of the model implementations org.schema.model.impl
dataTypePackage Package of the data type org.schema.model.datatype
skip Skip the execution.
Can also be set globally through the weedow.schemaorg.generator.maven.plugin.skip property.
false
addCompileSourceRoot Add the output directory to the project as a source root, so that the generated java types are compiled and included in the project artifact. true

Example with default configuration

import com.weedow.schemaorg.generator.SchemaModelGeneratorBuilder;
import com.weedow.schemaorg.generator.core.GeneratorOptions;
import com.weedow.schemaorg.generator.core.SchemaModelGenerator;
import com.weedow.schemaorg.generator.parser.ParserOptions;

final class GeneratorUtils {

  private GeneratorUtils() {
  }

  public static void generate() {
    ParserOptions parserOptions = new ParserOptions();

    GeneratorOptions generatorOptions = new GeneratorOptions();

    final SchemaModelGenerator generator = schemaModelGeneratorBuilder()
            .parserOptions(parserOptions)
            .generatorOptions(generatorOptions)
            .build();
    generator.generate();
  }
}

Example with custom configuration

import com.weedow.schemaorg.generator.SchemaModelGeneratorBuilder;
import com.weedow.schemaorg.generator.core.GeneratorOptions;
import com.weedow.schemaorg.generator.core.SchemaModelGenerator;
import com.weedow.schemaorg.generator.parser.ParserOptions;

final class GeneratorUtils {

  private GeneratorUtils() {
  }

  public static void generate(Path output, List<String> models, String schemaVersion, ...) {
    ParserOptions parserOptions = new ParserOptions();
    // Default is `null`: uses local resource named `schemaorg-current-https.jsonld` present in the classpath.
    // Pass 'latest' to use the latest Schema.org version. 
    parserOptions.setSchemaVersion(schemaVersion);

    GeneratorOptions generatorOptions = new GeneratorOptions()
            .setOutputFolder(output)
            .setModels(models)
            .setModelPackage(modelPackage)
            .setModelImplPackage(modelImplPackage)
            .setDataTypePackage(dataTypePackage);

    final SchemaModelGenerator generator = schemaModelGeneratorBuilder()
            .parserOptions(parserOptions)
            .generatorOptions(generatorOptions)
            .verbose(verbose)
            .build();
    generator.generate();
  }
}

Download the last version of the distribution zip, and extract the schema-org-generator-{version}-jar-with-dependencies.jar

$ java -jar schema-org-generator-{version}-jar-with-dependencies.jar --help

usage: java -jar schema-org-generator.jar SchemaModelGeneratorApp [-h] [-m
       <models>] [-V <version>] [-v]
 -h,--help                Show the help message
 -m,--models <models>     list of models to be generated. If not
                          specified, all models will be generated.
 -V,--version <version>   Schema version to be used: 'latest' to use the
                          latest version, or specific version (eg. 13.0).
                          If not specified, the generator uses the
                          resource in the JAR. see
                          https://github.com/schemaorg/schemaorg/tree/main
                          /data/releases
 -v,--verbose             Verbose

Example with default configuration

The default configuration generates all Schema.org entities.

$ java -jar schema-org-generator-{version}-jar-with-dependencies.jar

Example with custom configuration

$ java -jar schema-org-generator-{version}-jar-with-dependencies.jar -m Thing Hotel

The Serializer module supports serialization and deserialization of Schema.org objects in JSON-LD format.

Add the serializer module and the Maven Plugin to serialize/deserialize Schema.org objects generated by the Maven Plugin.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="..." xmlns:xsi="..." xsi:schemaLocation="...">

  <dependencies>
    <dependency>
      <groupId>com.weedow</groupId>
      <artifactId>schema-org-serializer</artifactId>
      <version>${schema-org-serializer.version}</version>
    </dependency>
  </dependencies>

  <build>
    <plugin>
      <groupId>com.weedow</groupId>
      <artifactId>schema-org-generator-maven-plugin</artifactId>
      <version>${schema-org-generator-maven-plugin.version}</version>
      <executions>
        <execution>
          <goals>
            <goal>generate</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </build>
</project>
import com.weedow.schemaorg.serializer.serialization.JsonLdSerializer;
import com.weedow.schemaorg.serializer.serialization.JsonLdSerializerImpl;
import org.schema.model.Thing;
import org.schema.model.impl.ThingImpl;

final class SerializerUtils {

  private SerializerUtils() {
  }

  public static String serialize() {
    final JsonLdSerializer jsonLdSerializer = new JsonLdSerializerImpl();

    Thing thing = new ThingImpl();
    thing.setId("my_id");
    thing.addName(Text.of("My Thing"));
    thing.addDescription(Text.of("This is my thing."));
    thing.addUrl(URL.of(new java.net.URL("https://github.com/Kobee1203/schema-org-java")));
    thing.addAlternateName(Text.of("My Part"));
    thing.addAlternateName(Text.of("My Object"));

    String result = null;
    try {
      result = jsonLdSerializer.serialize(thing);
    } catch (JsonLdException e) {
      // Errors related to JSON-LD serializer
    }
    return result;
  }
}

This example will give the following result:

{"@context":"https://schema.org","@id":"my_id","@type":"Thing","alternateName":["My Part","My Object"],"description":"This is my thing.","name":"My Thing","url":"https://github.com/Kobee1203/schema-org-java"}

There is another constructor that receives options as parameters.
Here is an example to serialize the Schema.org object with a pretty printed result:

import com.weedow.schemaorg.serializer.serialization.JsonLdSerializer;
import com.weedow.schemaorg.serializer.serialization.JsonLdSerializerImpl;
import org.schema.model.Thing;
import org.schema.model.impl.ThingImpl;

final class SerializerUtils {

  private SerializerUtils() {
  }

  public static String serialize() {
    JsonLdSerializerOptions options = JsonLdSerializerOptions.builder()
            .prettyPrint(true)
            .build();
    final JsonLdSerializer jsonLdSerializer = new JsonLdSerializerImpl(options);

    Thing thing = new ThingImpl();
    thing.setId("my_id");
    thing.addName(Text.of("My Thing"));
    thing.addDescription(Text.of("This is my thing."));
    thing.addUrl(URL.of(new java.net.URL("https://github.com/Kobee1203/schema-org-java")));
    thing.addAlternateName(Text.of("My Part"));
    thing.addAlternateName(Text.of("My Object"));

    String result = null;
    try {
      result = jsonLdSerializer.serialize(thing);
    } catch (JsonLdException e) {
      // Errors related to JSON-LD serializer
    }
    return result;
  }
}

This example will give the following result:

{
  "@context" : "https://schema.org",
  "@id" : "my_id",
  "@type" : "Thing",
  "alternateName" : [ "My Part", "My Object" ],
  "description" : "This is my thing.",
  "name" : "My Thing",
  "url" : "https://github.com/Kobee1203/schema-org-java"
}
import com.weedow.schemaorg.commons.model.JsonLdNode;
import com.weedow.schemaorg.serializer.deserialization.JsonLdDeserializer;
import com.weedow.schemaorg.serializer.deserialization.JsonLdDeserializerImpl;
import com.weedow.schemaorg.serializer.JsonLdException;

final class DeserializerUtils {

  private DeserializerUtils() {
  }

  /**
   * Deserializes the JSON-LD string into schema.org object.
   *
   * @param json JSON-LD String to deserialize
   * @return a JsonLdNode object resulting from the given deserialized String
   * @throws JsonLdException if the String cannot be deserialized
   */
  public static <T extends JsonLdNode> T deserialize(String json) throws JsonLdException {
    JsonLdDeserializer jsonLdDeserializer = new JsonLdDeserializerImpl();
    return jsonLdDeserializer.deserialize(json);
  }

  /**
   * Deserializes the JSON-LD string into schema.org objects.<br>
   * The method supports the deserialization of a JSON string representing a single object.
   *
   * @param json JSON-LD String to deserialize
   * @return a List of JsonLdNode objects resulting from the given deserialized String
   * @throws JsonLdException if the String cannot be deserialized
   */
  public static <T extends JsonLdNode> List<T> deserializeList(String json) throws JsonLdException {
    JsonLdDeserializer jsonLdDeserializer = new JsonLdDeserializerImpl();
    return jsonLdDeserializer.deserializeList(json);
  }
}

There is another constructor that receives a Map other types allowed by the deserializer.

  • Map key: @type value
  • Map value: Class

Here is an example to deserialize an object that is not generated by the Schema.org generation:

Let's imagine the following JSON-LD content:

{
  "@context" : "https://schema.org",
  "@type" : "Example",
  "aFloat" : 12345.67,
  "bool" : true,
  "cssSelectorType" : ".css-selector-type",
  "date" : "2022-03-12",
  "dateTime" : "2022-03-12T10:36:30",
  "integer" : 12345,
  "number" : 12345.67,
  "pronounceableText" : "This is my thing.",
  "text" : "My Thing",
  "time" : "10:36:30",
  "url" : "https://github.com/Kobee1203/schema-org-java",
  "xPathType" : "/xpath/example/title"
}

The previous content is passed to the deserialization method:

import com.weedow.schemaorg.serializer.deserialization.JsonLdDeserializer;
import com.weedow.schemaorg.serializer.deserialization.JsonLdDeserializerImpl;
import com.weedow.schemaorg.serializer.JsonLdException;
import org.myproject.data.Example;

final class DeserializerUtils {

  private DeserializerUtils() {
  }

  public static Example deserializeExample(String json) throws JsonLdException {
    JsonLdDeserializer jsonLdDeserializer = new JsonLdDeserializerImpl(Map.of("Example", Example.class));
    return jsonLdDeserializer.deserialize(json);
  }
}

If we want to add custom types, there is a constructor to get all classes from a package:

import com.weedow.schemaorg.commons.model.JsonLdNode;
import com.weedow.schemaorg.serializer.deserialization.JsonLdDeserializer;
import com.weedow.schemaorg.serializer.deserialization.JsonLdDeserializerImpl;
import com.weedow.schemaorg.serializer.JsonLdException;

final class DeserializerUtils {

  private DeserializerUtils() {
  }

  public static <T extends JsonLdNode> T deserializeExample(String json) throws JsonLdException {
    JsonLdDeserializer jsonLdDeserializer = new JsonLdDeserializerImpl("org.myproject.data");
    return jsonLdDeserializer.deserialize(json);
  }
}

Issues

Issues

Contributions are what make the open source community such an amazing place to be learned, inspire, and create. Any contributions you make are greatly appreciated.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Nicolas Dos Santos - @Kobee1203

Project Link: https://github.com/Kobee1203/schema-org-java

Tweets

GitHub forks GitHub stars GitHub watchers

MIT License
Copyright (c) 2022 Nicolas Dos Santos and other contributors