Sensible-Doc is a strong documentation era instrument that helps builders simply create clear and detailed API documentation for Java initiatives. With the rising reputation of WebSocket
know-how, Sensible-Doc has added help for WebSocket
interfaces ranging from model 3.0.7. This text will element use Sensible-Doc to generate Java WebSocket interface documentation and supply an entire instance of a WebSocket server.
Overview of WebSocket Know-how
First, let’s briefly perceive WebSocket know-how. The WebSocket protocol supplies a full-duplex communication channel, making information alternate between the consumer and server easier and extra environment friendly. In Java, builders can simply implement WebSocket servers and shoppers 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 will be robotically referred to as when WebSocket occasions (reminiscent of connection institution, message reception, and so on.) happen. In addition to @ServerEndpoint
, there are a number of different WebSocket-related annotations:
@OnOpen
: This technique is triggered when a consumer establishes a WebSocket reference to the server. It’s normally used to initialize sources or ship a welcome message.@OnMessage
: This technique is triggered when the server receives a message from the consumer. It’s accountable for processing the obtained message and performing the corresponding operations.@OnClose
: This technique is triggered when the consumer closes the WebSocket connection. It’s normally used to launch sources or carry out cleanup work.@OnError
: This technique is triggered if an error happens throughout WebSocket communication. It handles error conditions, reminiscent of logging or notifying the consumer.
Introduction to Sensible-Doc
Sensible-Doc is a light-weight API documentation era instrument based mostly on Java. It helps extracting interface info from supply code and feedback, robotically producing documentation in Markdown format. For WebSocket initiatives, this implies you’ll be able to immediately extract documentation out of your ServerEndpoint lessons with out manually writing tedious documentation descriptions.
Configuring Sensible-Doc to Generate WebSocket Interface Documentation
Making ready the Atmosphere
Guarantee your improvement surroundings has the next elements put in:
- Java 17 or increased
- Maven or Gradle because the construct instrument
- Newest model of Sensible-Doc plugin
- WebSocket server implementation library, reminiscent of
jakarta.websocket
Making a WebSocket Server
Including Plugin Dependency
Add the Sensible-Doc dependency within the pom.xml
file:
com.ly.smart-doc
smart-doc-maven-plugin
[Latest version]
./src/principal/sources/smart-doc.json
Making a WebSocket Server Endpoint
Outline the message sort (Message
), a easy POJO representing the message obtained from the consumer.
public class Message {
non-public 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 {
non-public String responseContent;
// getter and setter strategies
}
Implement the message decoder (MessageDecoder
), accountable for changing the message despatched by the consumer from JSON format to a Message object.
public class MessageDecoder implements Decoder.Textual content {
non-public static ultimate ObjectMapper objectMapper = new ObjectMapper();
@Override
public Message decode(String s) throws DecodeException {
attempt {
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 {
non-public static ultimate ObjectMapper objectMapper = new ObjectMapper();
@Override
public String encode(SampleResponse response) {
attempt {
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 {
/**
* Referred to as when a brand new connection is established.
*
* @param session the consumer session
* @param userId the consumer ID
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
System.out.println("Connected: " + session.getId() + ", User ID: " + userId);
}
/**
* Referred to as when a message is obtained 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());
}
/**
* Referred to as when the connection is closed.
*
* @param session the consumer session
*/
@OnClose
public void onClose(Session session) {
System.out.println("Disconnected: " + session.getId());
}
/**
* Referred to 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 Sensible-Doc
Create a smart-doc.json
configuration file to let Sensible-Doc know generate documentation.
{
"serverUrl": "http://smart-doc-demo:8080", // Set the server deal with, 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’ll find it within the src/principal/sources/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 Sensible-Doc
not solely saves lots of handbook documentation writing time but in addition 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 Sensible-Doc, you’ll be able to focus extra on the event of WebSocket functions with out worrying about documentation upkeep points.