Swagger schema validation fails to read swagger spec from custom folder - java

I am using attlasian library for schema validation of swagger.
com.atlassian.oai.validator.restassured.OpenApiValidationFilter
private static final OpenApiValidationFilter SWAGGER_FILTER_ = new OpenApiValidationFilter( OpenApiInteractionValidator.createFor("swagger.yml") .withBasePathOverride("ApiBasePath") .build());
The above code works only when the swagger specs are available in src/main/api folder.
I am trying to read specs from src/main/swagger or src/main/api/swaggers folder.
" java.lang.RuntimeException: Could not find /api/swaggers/swagger.yml
on the classpath"
What am I missing here ?

You can use real path, instead of Object
OpenApiValidationFilter validationFilter = new OpenApiValidationFilter(
OpenApiInteractionValidator.createFor(Paths.get(System.getProperty("user.dir"), "src", "main", "swagger", "swagger.yml").toString()
).build());

Related

Spring WebClient does not decode application/octet-stream into File object

Hi I am using OpenAPI Generator Maven Plugin to generate some Java Client code (using Spring WebClient library). One of the endpoints of my spec. returns binary content, like:
"schema": {
"type": "string",
"format": "binary"
}
The generated code uses java.io.File as the return type for that, like:
public Mono<ResponseEntity<File>> downloadWithHttpInfo(String filename) throws WebClientResponseException {
ParameterizedTypeReference<File> localVarReturnType = new ParameterizedTypeReference<File>() {};
return downloadRequestCreation(filename).toEntity(localVarReturnType);
}
When calling this generated method, the response code was 200 (i.e. OK from the server side), but I got the following error in my client code:
org.springframework.web.reactive.function.UnsupportedMediaTypeException:
Content type 'application/octet-stream' not supported for bodyType=java.io.File
This came from the toEntity() method, which is part of the Spring WebClient code instead of my code.
Is there a way to workaround this? A: Instruct OpenAPI Generator Maven Plugin not to use java.io.File type but use Resource type? B: Somehow make WebClient able to decode application/octet-stream into java.io.File?
Found a solution: add the following options to the OpenAPI Generator Maven Plugin then generate the code again, which would replace File to Resource
<generatorName>java</generatorName>
<library>webclient</library>
<typeMappings>string+binary=Resource</typeMappings>
<importMappings>Resource=org.springframework.core.io.Resource</importMappings>
The above is saying when the return type is string and the format is binary, map it to Resource and for Resource import it as org.springframework.core.io.Resource. There you go.
I had the exact same issue, but using Gradle instead of Maven.
Here is the syntax for doing the same in Gradle:
task generateClientSources(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
generatorName = 'java'
// other configs ..
configOptions = [
// other configs ..
library : 'webclient'
]
typeMappings = [
File : 'Resource'
]
importMappings = [
File : 'org.springframework.core.io.Resource'
]
}

Resolve external $ref using swagger-parser API

I'm trying to create API resources containing External file reference in parameters and responses and try to get these references resolved using swagger. (Support importing OpenAPI definitions with external references).
For that, I am getting the YAML files as file archive and there will be a master main.YAML file and from that other files are referenced.
OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
ParseOptions options = new ParseOptions();
options.setResolve(true);
options.setFlatten(true);
OpenAPI openAPI = openAPIV3Parser.read(extractedLocation + "/main.yaml", null, options);
String openAPIContent = Yaml.mapper().writerWithDefaultPrettyPrinter().writeValueAsString(openAPI);
APIDefinitionValidationResponse apiDefinitionValidationResponse = new APIDefinitionValidationResponse ();
apiDefinitionValidationResponse = OASParserUtil.validateAPIDefinition(openAPIContent, returnContent);
I tried with this code snippet but the apiDefinitionValidationResponse is throwing an error when there is $ref in the YAML file. If there's no $ref then apiDefinitionValidationResponse is a success and api is created.
So i doubt there is a problem in giving the data to OASParserUtil.validateAPIDefinition method (validateAPIDefinition method has no issues and it has been validated and tested)
Could someone help me with this?
The generated YAML file has extensions{} lines all over it
Error messages in debug logs:
attribute info.license.extensions is unexpected
attribute info.extensions is unexpected
attribute components.schemas.ErrorListItem.extensions is unexpected
attribute components.schemas.MenuItem.extensions is unexpected
attribute components.schemas.Order.extensions is unexpected
What i can tell from the error message and your result yaml is, that the transformation step adds some extensions: {} lines into the final yaml.
Having an extensions attribute at those places it complains about is not allowed by the OpenAPI specification.
Looks like your yaml serialization is to simple. Looking at the SerializerUtils from the openapi-generator they have a bit more configuration.
The extra module takes care of serializing only the interesting part of the OpenAPI object.

How to add the Default data from Ldif file to the Ldap Server with the java api?

I need to add bulk data into the LDAP server from the ldif file. I researched of java APIs but can't find the suitable one
I already tried with LdapTestUtils but it requires a server restart. I need another way except this
You will need to use a separate library that has API supporting LDIF import. Once such library is Apache Directory LDAP API. The library is in general compatible with most of the LDAP servers.
Refer the documentation, The LdifFileLoader class has features to import LDIF, in tandem with DefaultDirectoryService class (unfortunately I am unable to locate my earlier code demonstrating the LDIF import). You could refer this post, which shows how to use the above, though it deals with a problem of a different type.
I am not sure of the LDAP server you are using, however, you could give the above a shot and check.
It can also be achieved via LdapTemplate. LdapParser will parse the record from ldif file in the form of LdapAttribute then bind this record via ldapTemplate.bind
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl("ldap://192.168.99.101:389/");
contextSource.setUserDn("uid=admin,dc=abc,dc=com");
contextSource.setPassword(********);
contextSource.setPooled(false);
contextSource.afterPropertiesSet();
LdapTemplate template = new LdapTemplate(contextSource);
LdifParser parser = new LdifParser(new ClassPathResource("schema.ldif"));
parser.open();
while (parser.hasMoreRecords()) {
LdapAttributes record = parser.getRecord();
LdapName dn = record.getName();
template.bind(dn, null, record);
}

Generate Java class (Pojo) for parameters using WSDL url

I have a wsdl url using which I have to create a template file which has the list of the parameters for a particular API and create a pojo file for that request. I tried using soapui-api but I was unable to do so because of unable to fulfill the dependencies (Followed all the stackoverflow help to resolve the jar issues but it did not work):
Code:
WsdlProject project = new WsdlProject();
WsdlInterface[] wsdls = WsdlImporter.importWsdl(project, "http://XXXXX?wsdl");
WsdlInterface wsdl = wsdls[0];
for (com.eviware.soapui.model.iface.Operation operation : wsdl.getOperationList()) {
WsdlOperation wsdlOperation = (WsdlOperation) operation;
System.out.println("OP:"+wsdlOperation.getName());
System.out.println("Request:");
System.out.println(wsdlOperation.createRequest(true));
System.out.println("Response:"); System.out.println(wsdlOperation.createResponse(true));
}
Another approach in which I tried to parse the wsdl url using parser and get the list of names of the possible requests. I was able to get the request list but not the parameters required to create that request.
WSDLParser parser = new WSDLParser();
Definitions wsdl = parser.parse("http://XXXX?wsdl");
String str = wsdl.getLocalBindings().toString();
for(Message msg : wsdl.getMessages()) {
for (Part part : msg.getParts()) {
System.out.println(part.getElement());
}
}
Please help me on how to get the list of parameters from a wsdl url by either of the one approach.
well there are various stranded approach available for this , try and search for WS-import tool which is one of tools to do this .
This is the simple and best example here
WS_Import_tool
one more way of doing this is -
Apache_CFX
If you want to generate them using eclipse - that is also possible .
Check it out -
How do you convert WSDLs to Java classes using Eclipse?
What errors you are facing for SOAP UI
You can reffer this link for trouble shooting
Generate_java_from_Wsdl

Google Drive api v3 (java): Deleting a resource property does not work

I'm using the Google Drive API for Java (v3-rev111-1.23). I'm trying to remove a property from a resource.
I followed this documentation:
https://developers.google.com/drive/v3/reference/files/update
https://developers.google.com/drive/v3/web/migration#methods
This is the code I wrote:
Drive service = getDriveService();
File file = new File();
Map<String,String> properties = new HashMap<>();
properties.put("propA", null);
file.setProperties(properties);
file = service.files().update(fileId, file).execute();
The problem is that the property is never cleared. Remains with the previous value.
If I write the generated json with:
System.out.println(service.files().update(fileId, file).getJsonContent());
I get:
{properties={propA=null}}
Using the same code to add a new property like:
properties.put("test", "yes");
I get:
{properties={test=yes}}
and it works properly.
Has someone faced and solved this problem?
I read this post Google Drive Java API V3 delete custom property from 2016, but no solution was given.
More details:
Using the try-its of the web (https://developers.google.com/drive/v3/reference/files/update) I could create properties, modify them and even delete them.
Thanks.
Here's what I can share that might help you, using the Try-its:
I created a file using Files.create and created a custom property
appProperties{
"supersaiyan": "yes"
}
Then I deleted it using Files.update:
appProperties{
"supersaiyan": null
}
When I tried to fetch the appProperties, I got {} which means successfully deleted.

Categories