Swagger example value not showing all attributes - swagger

TLDR Swagger isn't showing all attributes in the Example Value section of the UI, irrespective of whether they are annotated or not.
I'm probably doing something wrong, any help would be much appreciated!
import com.codahale.metrics.annotation.ResponseMetered
import com.codahale.metrics.annotation.Timed
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import javax.validation.Valid
import javax.ws.rs.POST
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
#Api(
tags = ["foobar"],
description = "foobar")
#Path("/v1/user")
class FooResource {
#POST
#Path("v1/user")
#Produces(MediaType.APPLICATION_JSON)
#Timed
#ResponseMetered
#ApiOperation("Foo bar")
fun lisApiUser(#Valid user: User): Response {
throw RuntimeException("foo")
}
}
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import io.swagger.annotations.ApiModel
import io.swagger.annotations.ApiModelProperty
#JsonIgnoreProperties(ignoreUnknown = true)
//#ApiModel makes no difference
data class User #JsonCreator constructor(
#JsonProperty("name")
// #ApiModelProperty(name = "name", value = "John Smith", example = "John Smith") makes no difference
// #field:ApiModelProperty(name = "name", value = "John Smith", example = "John Smith") makes no difference
val name: String, //doesn't show in Swagger UI
#JsonProperty("details")
val details: Details //shows in Swagger UI
)
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import io.swagger.annotations.ApiModel
import io.swagger.annotations.ApiModelProperty
#JsonIgnoreProperties(ignoreUnknown = true)
//#ApiModel makes no difference
data class Details #JsonCreator constructor(
#JsonProperty("email")
// #ApiModelProperty(name = "email", value = "foo#example.com") makes no difference
// #field:ApiModelProperty(name = "email", value = "foo#example.com", example = "foo#example.com") makes no difference
val email: String //doesn't show in Swagger UI
)
https://imgur.com/a/JRgMVh4
In the Swagger UI, the Example Value section displays
{ "details":{} }
ie name and email attributes are not displayed. Oddly, clicking the Model section of the Swagger UI does display all attributes.

spring.main.lazy-initialization=false
In application.properties making false to lazy initialization works for me.

You need to add getters and setters, that was my case

Turns out both Jackson and Swagger "just work" by simply using the jackson-module-kotlin and removing all the annotations, constructors etc from the data classes
https://github.com/FasterXML/jackson-module-kotlin

Related

quarkus-smallrye-openapi - Could not resolve reference: Could not resolve pointer: /components/schemas

I have one rest endpoint which uses one class as the openapi schema:
import javax.ws.rs.Path;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
#Path("/orders")
#RequestScoped
public class OrdersRest {
#APIResponse(responseCode = "200", description = "Create a new order", content = {
#Content(mediaType = "application/json", schema = #Schema(implementation = OrderDto.class)) })
public Response create(OrderDto request) throws SessionNotFound {
The OrderDto class has one attribute that refers to another class, that exists on my project:
public class SessionDto {
private SessionSettingsProperties[] sessionSettingsProperties;
When I access the swagger-ui, I am receiving the error:
Errors
Resolver error at paths./session.get.responses.200.content.application/json.schema.properties.sessionSettingsProperties.items.$ref
Could not resolve reference: Could not resolve pointer: /components/schemas/SessionSettingsProperties does not exist in document
I'm using the Quarkus 1.13.1.Final version.
I've found this issue in Quarkus project that looks similar, but I believe is not exactly the same problem I have.
I was able to fix my problem including one org.eclipse.microprofile.openapi.annotations.media.Schema annotation in my field of the SessionDto class like this:
import org.eclipse.microprofile.openapi.annotations.media.Schema;
public class SessionDto {
#Schema(implementation = SessionSettingsProperties[].class)
private SessionSettingsProperties[] sessionSettingsProperties;

Xtext problem referencing grammar A from validator of grammar B

In Xtext, how do I follow a reference from grammar B to grammar A, within a validator of grammar B (which is in the ui-plugin)? Consider the following example.
Grammar A is org.xtext.people.People
grammar org.xtext.people.People with org.eclipse.xtext.common.Terminals
generate people "http://www.xtext.org/people/People"
People:
people+=Person*;
Person:
'person' name=ID ';';
and an instance
person Alice {citizenship "MN"; id "12345"; }
person Bob {citizenship "CH"; id "54321";}
person Malice {citizenship "XXX"; id "66666"; }
At an airport, entries of people are recorded.
enter Alice;
enter Bob;
enter Malice;
Entries are modelled with a second grammar B org.xtext.entries.Entries
grammar org.xtext.entries.Entries with org.eclipse.xtext.common.Terminals
generate entries "http://www.xtext.org/entries/Entries"
import "http://www.xtext.org/people/People"
Entries:
entries+=Entry*;
Entry:
'enter' person=[Person] ';';
After ensuring that the Eclipse project org.xtext.entries has the project org.xtext.people on it's classpath, and ensuring that the org.xtext.entries plugin has the org.xtext.people as a dependency, all works as expected.
There is a travel ban on people from country XXX, although certain deserving people are excluded. Only the CIA knows who is excluded from the ban. Entries must not be allowed for people from XXX unless excluded.
The updated grammar is
grammar org.xtext.entries.Entries with org.eclipse.xtext.common.Terminals
generate entries "http://www.xtext.org/entries/Entries"
import "http://www.xtext.org/people/People"
Entries:
entries+=Entry*;
Entry:
travelBanOverride=TravelBanOverride?
'enter' person=[Person] ';';
TravelBanOverride: '#TravelBanOverride' '(' code=STRING ')';
with validator
package org.xtext.entries.validation
import org.eclipse.xtext.validation.Check
import org.xtext.entries.entries.EntriesPackage
import org.xtext.entries.entries.Entry
import org.xtext.entries.CIA
class EntriesValidator extends AbstractEntriesValidator {
public static val BAN = 'BAN'
public static val ILLEGAL_OVERRIDE = 'ILLEGAL_OVERRIDE'
#Check
def checkBan(Entry entry) {
if (entry.person.citizenship == "XXX") {
if (entry.travelBanOverride === null) {
error('Violation of Travel Ban', EntriesPackage.Literals.ENTRY__PERSON, BAN)
}
else {
val overridecode = entry.travelBanOverride.code;
val valid = CIA.valid(entry.person.name, entry.person.id, overridecode)
if (!valid) {
error('Illegal override code', EntriesPackage.Literals.ENTRY__TRAVEL_BAN_OVERRIDE, ILLEGAL_OVERRIDE)
}
}
}
}
}
where the driver for the external CIA web-app is modelled for example by
package org.xtext.entries;
public class CIA {
public static boolean valid(String name, String id, String overrideCode) {
System.out.println("UNValid["+name+","+overrideCode+"]");
return name.equals("Malice") && id.equals("66666") && overrideCode.equals("123");
}
}
The validations work as expected.
I now wish to provided a quick-fix for BAN, that checks for an override code from the CIA.
package org.xtext.entries.ui.quickfix
import org.eclipse.xtext.ui.editor.quickfix.DefaultQuickfixProvider
import org.eclipse.xtext.ui.editor.quickfix.Fix
import org.xtext.entries.validation.EntriesValidator
import org.eclipse.xtext.validation.Issue
import org.eclipse.xtext.ui.editor.quickfix.IssueResolutionAcceptor
import org.xtext.entries.entries.Entry
import org.xtext.entries.Helper
class EntriesQuickfixProvider extends DefaultQuickfixProvider {
#Fix(EntriesValidator.BAN)
def tryOverride(Issue issue, IssueResolutionAcceptor acceptor) {
acceptor.accept(issue, 'Try override', 'Override if CIA says so.', 'override.png')
[element ,context |
val entry = element as Entry
// val person = entry.person // no such attribute
//val person = Helper.get(entry); // The method get(Entry) from the type Helper refers to the missing type Object
]
}
}
The first commented line does not compile: there is no attribute person. The second commented line is an attempt to solve the problem by getting a helper class in org.xtext.entries to get the person, but this does not compile either, giving a "The method get(Entry) from the type Helper refers to the missing type Object" error message.
For completeness, here is that helper.
package org.xtext.entries
import org.xtext.people.people.Person
import org.xtext.entries.entries.Entry
class Helper {
static def Person get(Entry entry) {
return entry.person;
}
}
Further, entry.travelBanOverride compiles fine, but entry.person does not. Clicking on Entry in Eclipse takes one to the expected code, which has both travelBanOverride and person.
The issue does not occur with a Java class in the same project and package.
package org.xtext.entries.ui.quickfix;
import org.xtext.entries.entries.Entry;
import org.xtext.people.people.Person;
public class Test {
public static void main(String[] args) {
Entry entry = null;
Person p = entry.getPerson();
}
}
Rewriting the quickfix in Java solves the problem.
package org.xtext.entries.ui.quickfix;
import org.eclipse.xtext.ui.editor.quickfix.DefaultQuickfixProvider;
import org.eclipse.xtext.ui.editor.quickfix.Fix;
import org.xtext.entries.validation.EntriesValidator;
import org.eclipse.xtext.validation.Issue;
import org.eclipse.xtext.ui.editor.quickfix.IssueResolutionAcceptor;
import org.xtext.entries.entries.Entry;
import org.xtext.entries.Helper;
import org.eclipse.xtext.ui.editor.model.edit.IModificationContext;
import org.eclipse.xtext.ui.editor.model.edit.ISemanticModification;
import org.eclipse.emf.ecore.EObject;
import org.xtext.entries.entries.Entry;
import org.xtext.people.people.Person;
public class EntriesQuickfixProvider extends DefaultQuickfixProvider {
#Fix(EntriesValidator.BAN)
public void tryOverride(final Issue issue, IssueResolutionAcceptor acceptor) {
acceptor.accept(issue,
"Try to override",
"Override",
"override.gif",
new ISemanticModification() {
public void apply(EObject element, IModificationContext context) {
Entry entry = (Entry) element;
System.out.println(entry.getPerson());
}
}
);
}
}
How do I follow a reference from grammar B (Entries) to grammar A (People), within a validator of grammar B?
My mistake is the following.
After ensuring that the Eclipse project org.xtext.entries has the
project org.xtext.people on it's classpath, and ensuring that the
org.xtext.entries plugin has the org.xtext.people as a dependency, all
works as expected.
The org.xtext.entries.ui ui-plugin must also have the org.xtext.people on its Java (Eclipse project) build path. Exporting and making a plugin-dependency it not enough.
Note that this setting should be made early, before crafting the quick-fix, because the Xtend editor has refreshing issues.

How to give kind name in DatastoreIO.v1.write

I am trying to read from a kind in google datastore and apply some transformations and write back to another kind. I am using google dataflow to achieve this. While reading from Datastore, we are able to give Kind. But not able to give Kind while writing. How to achieve this.
EDIT: Oops, I just noticed you were asking for Java. DatastoreIO.v1.write looks at the java equivalent of WriteToDatastore for me, in which case you have to set up your entity (including kind) in the previous step. Check out CreateEntityFn in this example. https://github.com/mbrukman/apache-beam/blob/master/examples/java/src/main/java/org/apache/beam/examples/cookbook/DatastoreWordCount.java#L197
ORIGINAL:
This is how I do it
import apache_beam
from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore
from google.cloud.proto.datastore.v1 import entity_pb2
from googledatastore import helper
class MakeEntity(object):
def __init__(self, project):
self._project = project
def make(self, element):
try:
entity = entity_pb2.Entity()
helper.add_key_path(entity.key, 'EntityKind', element['id'])
helper.add_properties(entity, {
"created": datetime.datetime.now(),
"email": unicode(element['email'],
"count": int(element['count'],
"amount": float(element['amount'],
})
return entity
except:
logging.error(traceback.format_exc())
raise
def build_pipeline(project, pipeline_options):
p = apache_beam.Pipeline(options=pipeline_options)
_ = \
(p
# other transforms
| 'create entity' >> apache_beam.Map(MakeEntity(project=project).make)
| 'write to datastore' >> WriteToDatastore(project=project))
return p
Edit #2: I adjusted your code to more closely follow the example I linked to. Hopefully this works
public class ModifyEntityKindFn extends DoFn<Entity, Entity> {
#ProcessElement
public void processElement(ProcessContext context) {
Key.Builder keyBuilder = makeKey(NEW_KIND, inputEntity.getKey());
keyBuilder.getPartitionIdBuilder().setNamespaceId(NEW_NAMESPACE);
Entity.Builder entityBuilder = Entity.newBuilder().setKey(keyBuilder.build());
entityBuilder.getMutableProperties().put("content", makeValue(context.element()).build());
context.output(entityBuilder.build());
}
}

Serializing a List[case class] in spray-json

I have a case class called Recording that I can serialize correctly using spray-json, but I can't serialize a List[Recording].
The answers I've seen about List serialization involve missing imports of DefaultJsonProtocol._ but that hasn't helped me here.
Here's the code:
import spray.json._
import scala.collection.immutable
object RecordingJsonProtocol extends DefaultJsonProtocol {
implicit val recordingFormat = jsonFormat2(Recording.apply)
}
case class Recording(name: String, hashOffsetIndex: immutable.Map[String, Int])
object RecordingLoader {
import RecordingJsonProtocol._
import DefaultJsonProtocol._
def recordingsToJson(filename: String, recordings : List[Recording]) = {
println(recordings.toJson.prettyPrint)
}
}
The error I receive is :
Error:(16, 24) Cannot find JsonWriter or JsonFormat type class for List[Recording]
println(recordings.toJson.prettyPrint)
^
Edit: problem solved
import DefaultJsonProtocol._
is redundant because RecordingJsonProtocol extends DefaultJsonProtocol -- but it's not merely redundant, it also prevents RecordingJsonProtocol from working.

How to set a label to a resource with jena

In my ontology I'm using SKOS concepts. In the documentation there are labels (like prefLabel, etc., mentioned): http://www.w3.org/TR/skos-reference/#labels.
How can I set such a label to a resource in Jena with defining the language?
My example to add a concept looks like this:
Resource skosConcept = infModel.createResource("http://www.w3.org/2004/02/skos/core#Concept");
Resource instance = infModel.createResource("http://eg.com#Instance");
infModel.add(instance, RDF.type, skosConcept);
But how can I define, for example, the skos:prefLabel? With a property to my instance resource? And how to set the language? The class OntResource seems to have such a property for adding a label with language . But I'm using an InfModel so I can't get the resource as an OntResource.
Just like you created the resource with createResource, you can create properties with createProperty, and then add the desired triple to the model in the same way that you already used. The literal with a language type can be created with createLiteral.
import com.hp.hpl.jena.rdf.model.InfModel;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.reasoner.Reasoner;
import com.hp.hpl.jena.reasoner.ReasonerRegistry;
import com.hp.hpl.jena.vocabulary.RDF;
public class SKOS {
public static void main(String[] args) {
Model model = ModelFactory.createDefaultModel();
Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
InfModel infModel = ModelFactory.createInfModel(reasoner, model);
String skos = "http://www.w3.org/2004/02/skos/core#";
Resource skosConcept = infModel.createResource( skos+"Concept" );
Resource instance = infModel.createResource("http://eg.com#Instance");
infModel.add(instance, RDF.type, skosConcept);
Property prefLabel = infModel.createProperty( skos+"prefLabel" );
Literal label = infModel.createLiteral( "a preferred label in English", "en" );
// either of these lines is fine
instance.addLiteral( prefLabel, label );
infModel.add( instance, prefLabel, label );
model.write( System.out, "N3" );
}
}
This code also shows the model, just so that we can see that the property is getting set as
<http://eg.com#Instance>
a <http://www.w3.org/2004/02/skos/core#Concept> ;
<http://www.w3.org/2004/02/skos/core#prefLabel>
"a preferred label in English"#en .

Resources