Java WebSocket API Documentation Utilizing Good-Doc – DZone – Uplaza

Good-Doc is a robust documentation technology software that helps builders simply create clear and detailed API documentation for Java tasks. With the rising reputation of WebSocket expertise, Good-Doc has added assist for WebSocket interfaces ranging from model 3.0.7. This text will element how you can use Good-Doc to generate Java WebSocket interface documentation and supply a whole instance of a WebSocket server.

Overview of WebSocket Expertise

First, let’s briefly perceive WebSocket expertise. The WebSocket protocol gives a full-duplex communication channel, making information trade between the consumer and server easier and extra environment friendly. In Java, builders can simply implement WebSocket servers and purchasers utilizing JSR 356: Java API for WebSocket.

WebSocket Annotations Overview

In Java WebSocket, the @ServerEndpoint annotation is used to outline a POJO class as a WebSocket server endpoint. Strategies marked with this annotation might be robotically referred to as when WebSocket occasions (akin to connection institution, message reception, and many others.) happen. Apart from @ServerEndpoint, there are a number of different WebSocket-related annotations:

  1. @OnOpen: This methodology is triggered when a consumer establishes a WebSocket reference to the server. It’s normally used to initialize assets or ship a welcome message.
  2. @OnMessage: This methodology is triggered when the server receives a message from the consumer. It’s answerable for processing the acquired message and performing the corresponding operations.
  3. @OnClose: This methodology is triggered when the consumer closes the WebSocket connection. It’s normally used to launch assets or carry out cleanup work.
  4. @OnError: This methodology is triggered if an error happens throughout WebSocket communication. It handles error conditions, akin to logging or notifying the person.

Introduction to Good-Doc

Good-Doc is a light-weight API documentation technology software primarily based on Java. It helps extracting interface info from supply code and feedback, robotically producing documentation in Markdown format. For WebSocket tasks, this implies you’ll be able to immediately extract documentation out of your ServerEndpoint lessons with out manually writing tedious documentation descriptions.

Configuring Good-Doc to Generate WebSocket Interface Documentation

Making ready the Surroundings

Guarantee your improvement setting has the next parts put in:

  • Java 17 or greater
  • Maven or Gradle because the construct software
  • Newest model of Good-Doc plugin
  • WebSocket server implementation library, akin to jakarta.websocket

Making a WebSocket Server

Including Plugin Dependency

Add the Good-Doc dependency within the pom.xml file:

    
        com.ly.smart-doc
        smart-doc-maven-plugin
        [Latest version]
        
            
            ./src/foremost/assets/smart-doc.json
            
        
    

Making a WebSocket Server Endpoint

Outline the message sort (Message), a easy POJO representing the message acquired from the consumer.

public class Message {
    personal String content material;

    // getter and setter strategies
}

Outline the response sort (SampleResponse), a easy POJO representing the response message to be despatched again to the consumer.

public class SampleResponse {
    personal String responseContent;
    // getter and setter strategies
}

Implement the message decoder (MessageDecoder), answerable for changing the message despatched by the consumer from JSON format to a Message object.

public class MessageDecoder implements Decoder.Textual content {

    personal static last ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public Message decode(String s) throws DecodeException {
        strive {
            return objectMapper.readValue(s, Message.class);
        } catch (Exception e) {
            throw new DecodeException(s, "Unable to decode text to Message", e);
        }
    }
    @Override
    public boolean willDecode(String s) {
        return (s != null);
    }

    @Override
    public void init(EndpointConfig endpointConfig) {
    }
    @Override
    public void destroy() {
    }
}

Implement the response encoder (MessageResponseEncoder).

public class MessageResponseEncoder implements Encoder.Textual content {

    personal static last ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String encode(SampleResponse response) {
        strive {
            return objectMapper.writeValueAsString(response);
        } catch (Exception e) {
            throw new RuntimeException("Unable to encode SampleResponse", e);
        }
    }

    @Override
    public void init(EndpointConfig endpointConfig) {
    }

    @Override
    public void destroy() {
    }
}

Use the ServerEndpoint annotation to create a easy WebSocket server.

/**
 * WebSocket server endpoint instance.
 */
@Element
@ServerEndpoint(worth = "/ws/chat/{userId}",
        decoders = {MessageDecoder.class},
        encoders = {MessageResponseEncoder.class})
public class ChatEndpoint {

    /**
     * Known as when a brand new connection is established.
     *
     * @param session the consumer session
     * @param userId  the person ID
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        System.out.println("Connected: " + session.getId() + ", User ID: " + userId);
    }

    /**
     * Known as when a message is acquired from the consumer.
     *
     * @param message the message despatched by the consumer
     * @param session the consumer session
     * @return the response message
     */
    @OnMessage
    public SampleResponse receiveMessage(Message message, Session session) {
        System.out.println("Received message: " + message);
        return new SampleResponse(message.getContent());
    }

    /**
     * Known as when the connection is closed.
     *
     * @param session the consumer session
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println("Disconnected: " + session.getId());
    }

    /**
     * Known as when an error happens.
     *
     * @param session   the consumer session
     * @param throwable the error
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }
}

Configuring Good-Doc

Create a smart-doc.json configuration file to let Good-Doc know how you can generate documentation.

{
  "serverUrl": "http://smart-doc-demo:8080", // Set the server handle, not required
  "outPath": "src/main/resources/static/doc" // Specify the output path of the doc
}

Producing Documentation

Run the next command within the command line to generate documentation:

mvn smart-doc:websocket-html

Viewing the Documentation

After the documentation is generated, you could find it within the src/foremost/assets/static/doc/websocket listing. Open the websocket-index.html file in a browser to view the WebSocket API documentation.

Conclusion

Routinely producing Java WebSocket interface documentation with Good-Doc not solely saves numerous guide documentation writing time but additionally ensures the accuracy and well timed updates of the documentation. It has been confirmed {that a} good documentation administration technique can considerably enhance improvement effectivity and code high quality. With instruments like Good-Doc, you’ll be able to focus extra on the event of WebSocket purposes with out worrying about documentation upkeep points.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version