Giter Site home page Giter Site logo

kobee1203 / schema-org-java Goto Github PK

View Code? Open in Web Editor NEW
16.0 2.0 2.0 19.71 MB

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

License: Apache License 2.0

Java 99.99% Handlebars 0.01%
generator java json json-ld json-schema maven maven-plugin schema schema-org seo

schema-org-java's Introduction

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

schema-org-java's People

Contributors

dependabot[bot] avatar kobee1203 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

schema-org-java's Issues

[generator] Handle Enumeration Member defined for multiple Enumeration types

The following JSO fragment is an enumeration member defined for multiple Enumeration types:

    {
      "@id": "schema:Radiography",
      "@type": [
        "schema:MedicalImagingTechnique",
        "schema:MedicalSpecialty"
      ],
      "rdfs:comment": "Radiography is an imaging technique that uses electromagnetic radiation other than visible light, especially X-rays, to view the internal structure of a non-uniformly composed and opaque object such as the human body.",
      "rdfs:label": "Radiography",
      "schema:isPartOf": {
        "@id": "https://health-lifesci.schema.org"
      }
    },

Radiography must be added to MedicalImagingTechnique and MedicalSpecialty.

Currently EnumerationMemberModelHandlerImpl does not handle this case and Radiography is not added to enumeration types.

could you make JsonLdTypeName annotation in field level as well?

At the moment this annotation can be used type and annotation_type levels. could you also add the field level for this?
I want to change the name of the property on my use case.

I want to add this property into my dataset
prov:wasDerivedFrom

But in java, we cannot define the variable names using ":" character. So I need to have an annotation to override the variable name.

Thanks

Use with a custom JSON-LD

Hello, I'm interested in generating pojo for a customized schema.org.

It looks like it's not possible with the current version (0.2.2) of your maven plugin.

I'm thinking of something like this:

.
├── pom.xml
└── src
    └── main
        └── resources
            └── custom.jsonld

with this configuration:

    <build>
        <plugins>
            <plugin>
                <groupId>com.weedow</groupId>
                <artifactId>schema-org-generator-maven-plugin</artifactId>
                <version>${schema-org.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <configuration>
                            <schemaVersion>classpath:/custom.jsonld</schemaVersion>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

(not sure about re-using schemaVersion though 🤔 )

Are you interested in this functionality ? I think I can contribute it if you want

want to set array objects

Let's say I want to set multiple objects, for instance, Thing object has a setter for identifier object and I can't add multiple identifier object. It takes just one object, can it take a list of identifier objects? So I will be able to set array objects.

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.