Saturday, April 8, 2023

Rest client using swagger codegen

 https://stackoverflow.com/questions/57545884/how-to-develop-a-simple-rest-client-using-swagger-codegen

Yes. You can use swagger-codegen-maven-plugin to generate a REST client. But before that , you need to describe the REST API in YAML or JSON in OpenAPI Specification mainly because swagger-codegen-maven-plugin only can generate a REST client from a file written in this specification.

Other answers assume that you need to write the specification manually while my solution take a step further to automatically generating the specification from the REST controller source codes.

The latest OpenAPI version is 3.0 .But based on the package of your imported swagger annotation , you are using version 2.0 (or before). So my solution assume you are using OpenAPI 2.0.

Generating Open API Specification

First, you can use swagger-maven-plugin to generate an OpenAPI spec from the RestController source codes. It basically analyses the Swagger annotations annotated in the @RestController classes that specified in <locations> and dump the OpenAPI spec to /src/main/resources/swagger.json :

<plugin>
    <groupId>com.github.kongchen</groupId>
    <artifactId>swagger-maven-plugin</artifactId>
    <version>3.1.5</version>
    <configuration>
        <apiSources>
            <apiSource>
                <springmvc>true</springmvc>
                <locations>
                    <location>com.dgs.spring.springbootswagger.controller.EmployeeController</location>
                    <location>com.dgs.spring.springbootswagger.controller.FooController</location>
                </locations>
                <schemes>
                    <scheme>http</scheme>
                </schemes>
                <host>127.0.0.1:8080</host>
                <basePath>/</basePath>
                <info>
                    <title>My API</title>
                    <version>1.1.1</version>
                </info>
                <swaggerDirectory>${basedir}/src/main/resources/</swaggerDirectory>
            </apiSource>
        </apiSources>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Execute the followings maven command to start generation:

mvn clean compile

Generating Rest Client

After swagger.json is generated, you can copy and paste it to your client project (e.g. /src/main/resources/swagger.json) . We can then use swagger-codegen-maven-plugin to generate a HTTP client .

By default , it will generate the whole maven project which includes test cases and other documentation stuff. But what I want is just the HttpClient 's source codes without other things. After several trial and error , I settle down to the following configuration :

<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.4.7</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${basedir}/src/main/resources/swagger.json</inputSpec>
                <language>java</language>
                <library>resttemplate</library>
                <output>${project.basedir}/target/generated-sources/</output>

                <apiPackage>com.example.demo.restclient.api</apiPackage>
                <modelPackage>com.example.demo.restclient.model</modelPackage>
                <invokerPackage>com.example.demo.restclient</invokerPackage>

                <generateApiTests>false</generateApiTests>
                <generateModelTests>false</generateModelTests>
                <generateApiDocumentation>false</generateApiDocumentation>
                <generateModelDocumentation>false</generateModelDocumentation>
                <configOptions>
                    <dateLibrary>java8</dateLibrary>
                    <sourceFolder>restclient</sourceFolder>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

The generated HTTP client is based on RestTemplate and will be generated to the folder target/generated-sources/restclient. You may have to configure your IDE to import the generated client in order to use it . (In case of Eclipse, you can configure in Project Properties ➡️ Java Build Path ➡️ Add the folder of the generated rest client)

To start generating the client , just execute the maven command :

mvn clean compile

To use the generated HTTP client :

ApiClient apiClient = new ApiClient();

//Override the default API base path configured in Maven
apiClient.setBasePath("http://api.example.com/api");

EmployeeManagementSystemApi api = new EmployeeManagementSystemApi(apiClient);
api.getEmployeeById(1l);

Note :

  • If you come across javax/xml/bind/annotation/XmlRootElement exception during generation when using java8+ , you may need to refer to this.

Saturday, December 31, 2022

Rename a project in android-studio - veryuseful

 https://stackoverflow.com/questions/57102684/how-to-copy-and-rename-a-project-in-android-studio-3-4

Saturday, October 30, 2021

dbutils... ORMS .. awesome

 https://testsortedset.wordpress.com/javasnippets/my-tiny-mini-orm-with-commons-dbutils-and-generics-2/

Thursday, October 28, 2021

SSL or no SSL ?

 https://mkyong.com/webservices/jax-ws/java-security-cert-certificateexception-no-name-matching-localhost-found/

Friday, October 22, 2021

Fat runnable jars with maven

 First read this for the different ways:

https://www.baeldung.com/executable-jar-with-maven


If you have external/local jars, understand the problem:

https://stackoverflow.com/questions/364114/can-i-add-jars-to-maven-2-build-classpath-without-installing-them


One possible dirty way:

https://github.com/stephenc/non-maven-jar-maven-plugin

Apache CXF and SOAP XML Logging

 Phew this one was tough..but managed to solve it eventually using the following:

https://newbedev.com/apache-cxf-loggingininterceptor-is-deprecated-what-to-use-instead

https://stackoverflow.com/questions/56356503/how-to-log-soap-request-response-using-log4j2-in-separate-log-files-dynamically

And this one did the most work

https://newbedev.com/how-to-modify-the-raw-xml-message-of-an-outbound-cxf-request


In between, had to mess with Streams.. it was crazy:

https://newbedev.com/convert-outputstream-to-bytearrayoutputstream

https://stackoverflow.com/questions/5923817/how-to-clone-an-inputstream/5924132#5924132

https://stackoverflow.com/questions/33014035/write-from-output-stream-to-output-stream


Finally .. learnt alot again.

Wednesday, July 7, 2021

Jar with dependencies using maven

 This works for me:

https://www.programmersought.com/article/82714095304/

Thursday, June 17, 2021

Using maven to package

 https://maven.apache.org/plugins/maven-assembly-plugin/examples/sharing-descriptors.html

Found the above and managed to use it in my project!

Wednesday, June 9, 2021

Getting started with Selenium on Eclipse

 https://www.guru99.com/installing-selenium-webdriver.html

Monday, May 24, 2021

Tomcat console access

 For Tomcat v8.5.4 and above, the file <tomcat>/webapps/manager/META-INF/context.xml has been adjusted:

<Context antiResourceLocking="false" privileged="true" >
    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
</Context>

Change this file to comment the Valve:

<Context antiResourceLocking="false" privileged="true" >
    <!--
    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
    -->
</Context>

After that, refresh your browser (not need to restart Tomcat), you can see the manager page.

Tuesday, May 18, 2021

Multiple Tomcat Instances


https://dzone.com/articles/run-configure-multiple-instance-in-a-single-tomcat

https://crunchify.com/how-to-run-multiple-tomcat-instances-on-one-server/


Thursday, March 25, 2021

Useful site for generating sample codes for post JSON

 https://reqbin.com/req/java/h4rnefmw/post-json-with-bearer-token-authorization-header

Wednesday, March 24, 2021

Java Client to do a HTTP post

 Had so much trouble to do this on a J2EE 6  using Jersey 1  and Apache HTTPClient.


Finally resolved using pure java.io classes:

https://gist.github.com/dnetix/db23658cb308a0f2ac1b09f2ddb726d3


Monday, March 22, 2021

Dependency management in Maven

 Interesting:

https://blogs.oracle.com/developers/mastering-maven-dependency-exclusions

Using Maven to generate "fat" jars or "uber" jars

 This one worked for me:

http://tutorials.jenkov.com/maven/maven-build-fat-jar.html


Here are other ways to do it:

https://mkyong.com/maven/how-to-create-a-jar-file-with-maven/


Remember to put the xml outside of pluginManagement

https://stackoverflow.com/questions/33261354/maven-copy-dependecies-not-working


If you have some jars referenced as external jars, you can try this: (didn't work for me)

https://programmersought.com/article/90075878511/


Some useful background info:

https://imagej.net/Uber-JAR


What works for me:

<build>

<finalName>icommogateway</finalName>

<pluginManagement>

<!-- lock down plugins versions to avoid using Maven defaults (may be 

moved to parent pom) -->

</pluginManagement>


<plugins>


<!-- download source code in Eclipse, best practice -->

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-eclipse-plugin</artifactId>

<version>2.9</version>

<configuration>

<downloadSources>true</downloadSources>

<downloadJavadocs>false</downloadJavadocs>

<dependencySets>

<dependencySet>

<excludes>

<exclude>log4j:log4j</exclude>

</excludes>

</dependencySet>

</dependencySets>

</configuration>

</plugin>


<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->

<plugin>

<artifactId>maven-clean-plugin</artifactId>

<version>3.1.0</version>

</plugin>


<plugin>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.8.0</version>

<configuration>

<source>1.7</source>

<target>1.7</target>

<compilerArgs>

<!-- The parameter name and the parameter value appear in pairs, that 

is, the first is the name, and the second is the value -->

<arg>-extdirs</arg>

<arg>M:/Development/Unica/Interact/912/interact.jar</arg>

</compilerArgs>

</configuration>

</plugin>


<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-assembly-plugin</artifactId>

<version>3.1.1</version>


<configuration>

<descriptorRefs>

<descriptorRef>jar-with-dependencies</descriptorRef>

</descriptorRefs>

</configuration>


<executions>

<execution>

<id>make-assembly</id>

<phase>package</phase>

<goals>

<goal>single</goal>

</goals>

</execution>

</executions>



</plugin>


</plugins>

</build>




To exclude some jars:

https://stackoverflow.com/questions/42412964/maven-depenency-plugin-copy-dependencies-exclude-single-artifact

https://github.com/albertattard/how-to-exclude-dependencies-from-maven-assembly-plugin/blob/master/pom.xml

https://blog.csdn.net/yh_zeng2/article/details/82859914

Tuesday, May 12, 2020

Using Github with Eclipse

I am using eGit to try this out.

In Eclipse-> Help -> Install New Software -> Work with:
http://download.eclipse.org/egit/updates

Useful video to get started:
https://www.youtube.com/watch?v=ptK9-CNms98

And how to configure projects to push to Github:
https://www.youtube.com/watch?v=LPT7v69guVY
1. How to create github repository 2. How to clone repository in eclipse 3. How to add eclipse project to github repository 4. How to commit, push and pull the changes

Basically:
Step 1 : Create GitHub account and SignIn Step 2 : Start a Project = Create a repository Step 3 : Start Eclipse Step 4 : Goto Perspective - Git Repositories and click on Add Git Repo Step 5 : Create a project in Eclipse Step 6 : Do a right click on Project - Team - Share - Add to git repo Step 7 : Commit and Push the project to the repo Step 8 : Commit and Push every change to the repo

Thursday, April 23, 2020

Remotely related to java :-)

How to run minecraft on your PC (Java version) - note, Java edition does not support cross platform:

https://www.h3xed.com/pc-gaming/start-a-minecraft-server-and-play-with-your-friends

To check your external ip:
https://www.whatismyip.com/

To check if your port is open:
https://www.yougetsignal.com/tools/open-ports/


Sunday, April 19, 2020

Very good reference on using Jersey:
https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-en/cn/part1/chapter8/building_and_invoking_requests.html


Do note: need to do a string:
Response resp = invocationBuilder.post(Entity.entity(jsonObjectBody.toString(), MediaType.APPLICATION_JSON)); 

or else json
{"method":"Logon","payload":{"strLogin":"aaa_offers","strPassword":"gL(8KKw3L)\\\"g)BKR","elemParameters":{}},"schema":"xtk:session","securityToken":"","sessionToken":""}


will be converted to like NVP:

{
               "method": {
      "chars": "Logon",
      "string": "Logon",
      "valueType": "STRING"
    },
    "payload": {    
      "strLogin": {
        "chars": "aaa_offers",
        "string": "aaa_offers",
        "valueType": "STRING"
      },
      "strPassword": {
        "chars": "**** password here ****",
        "string": "**** password here ****",
        "valueType": "STRING"
      },
                 "elemParameters": {}
    },
    "schema": {
      "chars": "xtk:session",
      "string": "xtk:session",
      "valueType": "STRING"
    },
    "securityToken": {
      "chars": "",
      "string": "",
      "valueType": "STRING"
    },
    "sessionToken": {
      "chars": "",
      "string": "",
      "valueType": "STRING"
    }
  }