How to create docs for spring-integration endpoint - swagger

I'm using a SpringBoot 2.2.6 WebApplication with Maven 3. I'm also using spring-integration-http for my endpoint, that's mean that my endpoint are similar to follow:
#Bean
public IntegrationFlow test(CommonTransformer<TestDTO, String, TestMapper> testTransformer, Jackson2JsonObjectMapper obj) {
return IntegrationFlows.from(Http.inboundGateway("/foo/{name}")
.requestMapping(m -> m.methods(HttpMethod.GET))
.payloadExpression("#pathVariables.name")
.replyChannel(Constants.REPLY)
.requestPayloadType(String.class))
.transform(testTransformer)
.transform(new ObjectToJsonTransformer(obj))
.channel(Constants.HTTP_REQUEST)
.get();
}
Now I would like to create a OpenApi docs for my endpoint and, if it's possible, a swagger GUI interface to test it.
I have read several official/unofficial docs and I find interesting docs here another much interesting example here.
My preoccupation is that many of this articles are dated before 2020 (for example one of these use deprecated annotation likes #EnableSwagger2Mvc) but I can't managed to find out something more updated.
Is anyone aware of a more up-to-date procedure?
-------------------------- UPDATE --------------------------
First of all Thanks #ArtemBilan for yor response.
Yes I read that article and I'm not new to documenting my REST API. With springdoc-openapi-ui I'm able to create a .json file that, if putted in some editor like http://swagger.io or if used with a specific maven plugin can create a client (in both spring java and Angular language) ready for use.
I have tried the springfox way (above) to documenting my spring-integration-http but it sucks! It generate some useless files to reproduce the call via CURL..
Is not what I'm looking for. I must (the STO asks) documenting my endpoint like the .yaml you can find for the example Swagger Pet Store.
And it seems there's no way with this spring-integration-http to do so..
Any help is appreciate.

Related

Swagger identifies rare endpoints in REST API

Some days ago I started a REST API in JavaEE 7, I implemented a single class with three methods and implemented succesfully Swagger and Swagger-UI in the project, which showed the three endpoints I implemented succesfully in the generated JSON.
However, I migrated to JavaEE 8, and after this change Swagger detects several unknown endpoints, like the "default" ones (this capture shows only part of all of them):
Investigating a bit I discovered that these endpoints may belong to a JPA REST API in Eclipselink implementation, as described here https://oracle-base.com/articles/misc/oracle-rest-data-services-ords-open-api-swagger-support and here https://www.eclipse.org/eclipselink/documentation/2.4/solutions/restful_jpa004.htm#CHDFCFFA
Despite they appear in the generated JSON, all of them contain variable paths, so I can't access them following the path given by Swagger, even inventing some parameters like "version" using the webs above examples.
The Swagger version I use is v3, aka OpenAPI version. I specify OpenAPI properties with #OpenAPIDefinition in the endpoint class, which also contains a #Tag annotation to group them and the three methods contain #Operation tag with their own #ApiResponse. There is no more Swagger/OpenAPI annotations/files/classes written by me.
The question is, how can I make Swagger ignoring these endpoints?
Thanks
Finally I have found a solution. The case is that Swagger scanner engine scans the whole project, ignoring if the class and his methods have #Operation or not. If my hypothesis is true, some Eclipselink classes could have Swagger annotations (I'm not sure), so when Swagger scans, if finds them and add them to the JSON/YAML.
The solution is creating/adding to the existant openapi.yaml (it can have several names and can be in several locations, as enumerated here: https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X---Integration-and-configuration#known-locations) this:
resourceClasses:
- com.path.to.your.package.Resource
prettyPrint: true
cacheTTL: 0 
scannerClass: io.swagger.v3.jaxrs2.integration.JaxrsAnnotationScanner
readAllResources: false
Instead of resourceClasses it can be written resourcePackages, and then it should be specified the whole package and the class in the same style as used to specify the package. To be honest, this property does not affect to my problem.
The solution comes on setting readAllResources to false. The reason is here, in a note: https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X---Annotations#operation
Blockquote
Note: swagger-jaxrs2 reader engine includes by default also methods of scanned resources which are not annotated with #Operation, as long as a jax-rs #Path is defined at class and/or method level, together with the http method annotation (#GET, #POST, etc).
I hope this solution serves for anyone if he/she has to face the same problem.

Extracting CCD document values using MDHT via Mirth

I am trying to use MDHT tools to extract values from a CCD document via Mirth. I am doing this in the following way.
Downloaded Java runtime libraries and placed them in Mirth's custom-lib folder and wrote sample code to extract some patient values in Mirth's transformer & Deploy section.
Code in transformer.
// Load the CCD Document
var doc = org.openhealthtools.mdht.uml.cda.util.CDAUtil.load(new
java.io.ByteArrayInputStream(messageObject.getRawData().getBytes("UTF-8")));
// Get CCD Document Sections to be parsed
var docPatientRole = doc.getRecordTargets().get(0).getPatientRole();
var docPatient = docPatientRole.getPatient();
var docPatientName = docPatient.getNames().get(0);
// Map Patient Identity Fields to Mirth Channel Map Variables
channelMap.put('patientFirstName',
docPatientName.getGivens().get(0).getText());
channelMap.put('patientLastName',
docPatientName.getFamilies().get(0).getText());
channelMap.put('patientGenderCode',
docPatient.getAdministrativeGenderCode().getCode());
channelMap.put('patientDateOfBirth', docPatient.getBirthTime().getValue()); // YYYYMMDD
Can anyone help me with the code as I am new to JavaScript and also I am not aware of all the functions in the .jar files so as to access all the other components in a CCD.
I am currently stuck at this point. I need to access all the sections/Components in a CCD. Can anyone please redirect me to any examples/tutorials (via Mirth) related to each section. I have already looked at some links guide/developers guide but all links are Dead and not working.
Any help is appreciated.
"but all links are dead and not working"
I know that feel... it's frustrating.
For a start, you need to define a type and a version of the document that you want to consume. Check out this article What version of CCDA Document is this? Then you need to find an Implementation Guide (IG) for this type of documents so you know its structure (for example, HL7 C-CDA Release 1.1 IG is available here). If you know the document type, you know what data can be extracted from the document.
I'm not sure about a programming language that you use in your question. Is it Java or JavaScript? My examples are in Java:
CCDA REST API - package com.appliedinformatics.cdaapi.parser (RecordTarget, Medications, Problems, Results).
MDHT Developers Guide: Consume CDA Content using MDHT API (Allergies).
MDHT Consolidated CDA Validator - GitHub
A reference C-CDA Validator - GitHub
MDHT CDA Maven example - GitHub

Dropwizard: customize health check address and format

Is it possible to customize Dropwizrd's healthcheck output so that, e.g.: /health for healthchecks instead of /healthcheck and some output like {“status”: 200}.
I realise I could simply write a new resource that does what ever I need, I was just wondering if there is a more standard way to do this.
From what I have read on the 0.7.1 source code it's not possible to change the resource URI for healthchecks unfortunately, I highly doubt you can change the healthcheck format. I also remember people complaining about not being able to add REST resources to admin page, only servlets. Maybe on 0.8.0?
Here are the details of what I've tracked so far on the source code. Maybe I have misread or misunderstood something, so somebody could fix it.
Metrics has actually written AdminServlet to add healtcheck servlet in a way that it checks the servlet config whether the URI is defined or not.
this.healthcheckUri = getParam(config.getInitParameter(HEALTHCHECK_URI_PARAM_KEY), DEFAULT_HEALTHCHECK_URI);
But dropwizard doesn't provide a way to inject this configuration in any way on AbstractServerFactory.
handler.addServlet(new NonblockingServletHolder(new AdminServlet()), "/*");
NonblockingServletHolder is the one which is providing the config to AdminServlet but is created by AbstractServerFactory with empty constructor and provides no way to change the config.
I've thought of and tried to access the ServletHolder from the Environment object on Application.run method but the admin servlets are not created until after run method is run.
environment.getAdminContext().getServletHandler().getServlets()[0].setInitParameter("healthcheck-uri", "/health");
Something like this in your run() function will help you control the URI of your healthchecks:
environment.servlets().addServlet(
"HealthCheckServlet",
new HealthCheckServlet(environment.healthChecks())
).addMapping("/health");
If you want to actually control what's returned you need to write your own resource file. Fetch all the healthchecks from the registery, run them and return whatever aggregated value you want based on their results.

How can I automate my tests for Java application without using UI?

I have access to the Code base (checked out to my local machine from SVN). It is written using Java and Groovy using Grails framework (MVC architecture). I am a tester and as part of automating my tests, I want to write code that will make calls to the controllers and in return i can check the result in terms of looking at response or entries in data base. I basically want to skip the UI part.
How can I start? I probably cannot write my code inside the dev project (i am not allowed to i suppose). Do i need to create a separate framework for it? Or can I take all the jar files and include then in a project and write code on top of it?
The answer in this post is actually what I am looking for but for a Java application. Is there any API i can use?
Please let me know if you need additional information.
If the application does not provide Json, XML or similar APIs, you can use a test library like HtmlUnit within jUnit test methods.
A example from "Getting Started" section:
#Test
public void homePage_Firefox() throws Exception {
final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_17);
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
Assert.assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
webClient.closeAllWindows();
}
Note that HtmlUnit tries to work like a virtual browser (written 100% in Java), but it is a bit limited in executing Javascript, for example.
Then, use another library like jsoup or Jericho HTML Parese to inspect the code and get the values you want to check in the database.
In the other hand, if the application does provide methods to obtain the data, you can use Jersey Client API to make REST requests and get the values. It is very simple. Look at this example:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9998").path("resource");
Form form = new Form();
form.param("x", "foo");
form.param("y", "bar");
MyJAXBBean bean =
target.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
MyJAXBBean.class);

Scaffolding Web Services in Grails

I need to implement a web app, but instead of using relational database I need to use different SOAP Web Services as a back-end. An important part of application only calls web services and displays the result. Since Web Services are clearly defined in form of Operation: In parameters and Return Type it seems to me that basic GUI could be easily constructed just like in the case of scaffolding based on Domain Entities.
For example in case of SearchProducts web service operation I need to enter search parameters as input, so the search page can be constructed. Operation will return a list of products, so I need a page that will display this list in some kind of table.
Is there already some library in grails that let you achieve this. If not, how would you go about creating one?
Probably the easiest approach is to use wsimport on the WSDL files to generate the client-side stubs. Then you can call methods in the stubs from Groovy just as you would have called them from Java.
For example, consider the WSDL file for Microsoft's TerraServer, located at http://terraservice.net/TerraService.asmx?wsdl . Then you run something like
wsimport -d src -keep http://terraservice.net/TerraService.asmx?WSDL
which puts all the compiled stubs in the src directory. Then you can write Groovy code like
import com.terraserver_usa.terraserver.*;
TerraServiceSoap sei = new TerraService().getTerraServiceSoap()
Place home = new Place(city:'Boston',state:'MA',country:'US')
def pt = sei.convertPlaceToLonLatPt(home)
println "$pt.lat, $pt.lon"
assert Math.abs(pt.lat - 42.360000) < 0.001
assert Math.abs(pt.lon - -71.05000) < 0.001
If you want to access a lot of web services, generate the stubs for all of them. Or you can use dynamic proxies instead.
The bottom line, though, is to let Java do what it already does well, and use Groovy where it makes your life easier.
You should be able to use XFire or CXF Plugins. For automatic scaffolding, modify your Controller.groovy template in scaffolding templates so it auto-generates methods you need.

Resources