Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 95 additions & 99 deletions OCPP-J/src/main/java/eu/chargetime/ocpp/Draft_HttpHealthCheck.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
/*
* Based ON https://github.com/TooTallNate/Java-WebSocket/issues/1077
*/
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.drafts.Draft;
import org.java_websocket.enums.CloseHandshakeType;
Expand All @@ -12,105 +15,98 @@
import org.java_websocket.handshake.*;
import org.java_websocket.util.Charsetfunctions;

import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;

class Draft_HttpHealthCheck extends Draft {

static final int HTTP_HEALTH_CHECK_CLOSE_CODE = 10200;

static Boolean isHttp(ClientHandshake handshakedata) {
String upgradeField = handshakedata.getFieldValue("Upgrade");
return upgradeField == null || upgradeField.isEmpty();
}

@Override
public List<ByteBuffer> createHandshake(Handshakedata handshakedata, boolean withcontent) {
byte[] content = Charsetfunctions.asciiBytes("<h1>OCPP-J Websocket OK</h1>");
byte[] header = Charsetfunctions.asciiBytes(
"HTTP/1.0 200 OK\r\n" +
"Mime-Version: 1.0\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: " + content.length + " \r\n" +
"Connection: close\r\n" +
"\r\n"
);

ByteBuffer bytebuffer = ByteBuffer.allocate(content.length + header.length);
bytebuffer.put(header);
bytebuffer.put(content);
bytebuffer.flip();
return Collections.singletonList(bytebuffer);
}

@Override
public HandshakeState acceptHandshakeAsClient(
ClientHandshake request, ServerHandshake response
) throws InvalidHandshakeException {
throw new InvalidHandshakeException("This draft can't be used on a client");
}

@Override
public HandshakeState acceptHandshakeAsServer(
ClientHandshake handshakedata
) throws InvalidHandshakeException {
return (isHttp(handshakedata)) ? HandshakeState.MATCHED : HandshakeState.NOT_MATCHED;
}

@Override
public ByteBuffer createBinaryFrame(Framedata framedata) {
return null;
}

@Override
public List<Framedata> createFrames(ByteBuffer binary, boolean mask) {
return null;
}

@Override
public List<Framedata> createFrames(String text, boolean mask) {
return null;
}

@Override
public void processFrame(
WebSocketImpl webSocketImpl, Framedata frame
) throws InvalidDataException {
throw new InvalidDataException(0, "This draft can't be used on a client");
}

@Override
public void reset() {
// Nothing to Do
}

@Override
public ClientHandshakeBuilder postProcessHandshakeRequestAsClient(
ClientHandshakeBuilder request
) throws InvalidHandshakeException {
throw new InvalidHandshakeException("This draft can't be used on a client");
}

@Override
public HandshakeBuilder postProcessHandshakeResponseAsServer(
ClientHandshake request, ServerHandshakeBuilder response
) throws InvalidHandshakeException {
return response;
}

@Override
public List<Framedata> translateFrame(ByteBuffer buffer) throws InvalidDataException {
throw new InvalidHandshakeException("This draft doesn't work with frames");
}

@Override
public CloseHandshakeType getCloseHandshakeType() {
return CloseHandshakeType.NONE;
}

@Override
public Draft copyInstance() {
return this;
}
static final int HTTP_HEALTH_CHECK_CLOSE_CODE = 10200;

static Boolean isHttp(ClientHandshake handshakedata) {
String upgradeField = handshakedata.getFieldValue("Upgrade");
return upgradeField == null || upgradeField.isEmpty();
}

@Override
public List<ByteBuffer> createHandshake(Handshakedata handshakedata, boolean withcontent) {
byte[] content = Charsetfunctions.asciiBytes("<h1>OCPP-J Websocket OK</h1>");
byte[] header =
Charsetfunctions.asciiBytes(
"HTTP/1.0 200 OK\r\n"
+ "Mime-Version: 1.0\r\n"
+ "Content-Type: text/html\r\n"
+ "Content-Length: "
+ content.length
+ " \r\n"
+ "Connection: close\r\n"
+ "\r\n");

ByteBuffer bytebuffer = ByteBuffer.allocate(content.length + header.length);
bytebuffer.put(header);
bytebuffer.put(content);
bytebuffer.flip();
return Collections.singletonList(bytebuffer);
}

@Override
public HandshakeState acceptHandshakeAsClient(ClientHandshake request, ServerHandshake response)
throws InvalidHandshakeException {
throw new InvalidHandshakeException("This draft can't be used on a client");
}

@Override
public HandshakeState acceptHandshakeAsServer(ClientHandshake handshakedata)
throws InvalidHandshakeException {
return (isHttp(handshakedata)) ? HandshakeState.MATCHED : HandshakeState.NOT_MATCHED;
}

@Override
public ByteBuffer createBinaryFrame(Framedata framedata) {
return null;
}

@Override
public List<Framedata> createFrames(ByteBuffer binary, boolean mask) {
return null;
}

@Override
public List<Framedata> createFrames(String text, boolean mask) {
return null;
}

@Override
public void processFrame(WebSocketImpl webSocketImpl, Framedata frame)
throws InvalidDataException {
throw new InvalidDataException(0, "This draft can't be used on a client");
}

@Override
public void reset() {
// Nothing to Do
}

@Override
public ClientHandshakeBuilder postProcessHandshakeRequestAsClient(ClientHandshakeBuilder request)
throws InvalidHandshakeException {
throw new InvalidHandshakeException("This draft can't be used on a client");
}

@Override
public HandshakeBuilder postProcessHandshakeResponseAsServer(
ClientHandshake request, ServerHandshakeBuilder response) throws InvalidHandshakeException {
return response;
}

@Override
public List<Framedata> translateFrame(ByteBuffer buffer) throws InvalidDataException {
throw new InvalidHandshakeException("This draft doesn't work with frames");
}

@Override
public CloseHandshakeType getCloseHandshakeType() {
return CloseHandshakeType.NONE;
}

@Override
public Draft copyInstance() {
return this;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,8 @@ protected Message parse(Object json) {
message.setPayload(array.get(INDEX_CALLRESULT_PAYLOAD).toString());
} else if (array.get(INDEX_MESSAGEID).getAsInt() == TYPENUMBER_CALLERROR) {
message = new CallErrorMessage();
((CallErrorMessage) message).setErrorCode(array.get(INDEX_CALLERROR_ERRORCODE).getAsString());
((CallErrorMessage) message)
.setErrorCode(array.get(INDEX_CALLERROR_ERRORCODE).getAsString());
((CallErrorMessage) message)
.setErrorDescription(array.get(INDEX_CALLERROR_DESCRIPTION).getAsString());
((CallErrorMessage) message).setRawPayload(array.get(INDEX_CALLERROR_PAYLOAD).toString());
Expand Down
15 changes: 10 additions & 5 deletions OCPP-J/src/main/java/eu/chargetime/ocpp/WebSocketListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public void open(String hostname, int port, ListenerEvents handler) {
drafts) {
@Override
public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
if(Draft_HttpHealthCheck.isHttp(clientHandshake)){
if (Draft_HttpHealthCheck.isHttp(clientHandshake)) {
logger.debug("On HTTP Request, for heathcheck");
webSocket.close(Draft_HttpHealthCheck.HTTP_HEALTH_CHECK_CLOSE_CODE);
return;
Expand Down Expand Up @@ -166,8 +166,14 @@ public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(
}
}
if (password == null
|| password.length < configuration.getParameter(JSONConfiguration.OCPPJ_CP_MIN_PASSWORD_LENGTH, OCPPJ_CP_MIN_PASSWORD_LENGTH)
|| password.length > configuration.getParameter(JSONConfiguration.OCPPJ_CP_MAX_PASSWORD_LENGTH, OCPPJ_CP_MAX_PASSWORD_LENGTH))
|| password.length
< configuration.getParameter(
JSONConfiguration.OCPPJ_CP_MIN_PASSWORD_LENGTH,
OCPPJ_CP_MIN_PASSWORD_LENGTH)
|| password.length
> configuration.getParameter(
JSONConfiguration.OCPPJ_CP_MAX_PASSWORD_LENGTH,
OCPPJ_CP_MAX_PASSWORD_LENGTH))
throw new InvalidDataException(401, "Invalid password length");
}

Expand All @@ -190,8 +196,7 @@ public void onClose(WebSocket webSocket, int code, String reason, boolean remote
reason,
remote);

if(code == Draft_HttpHealthCheck.HTTP_HEALTH_CHECK_CLOSE_CODE)
return;
if (code == Draft_HttpHealthCheck.HTTP_HEALTH_CHECK_CLOSE_CODE) return;

WebSocketReceiver receiver = sockets.get(webSocket);
if (receiver != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ of this software and associated documentation files (the "Software"), to deal
SOFTWARE.
*/

/**
* Exception returned to an outgoing request if an error is reported from the other end.
*/
/** Exception returned to an outgoing request if an error is reported from the other end. */
public class CallErrorException extends Exception {

private String errorCode;
Expand All @@ -37,9 +35,9 @@ public class CallErrorException extends Exception {
/**
* Constructor.
*
* @param errorCode send from the other end.
* @param errorCode send from the other end.
* @param errorDescription describing the error.
* @param payload raw payload send from the other end.
* @param payload raw payload send from the other end.
*/
public CallErrorException(String errorCode, String errorDescription, Object payload) {
super(
Expand Down
25 changes: 14 additions & 11 deletions ocpp-common/src/main/java/eu/chargetime/ocpp/Client.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@ public class Client {
* @param promiseRepository Inject promise repository
* @see Session
*/
public Client(
ISession session,
IPromiseRepository promiseRepository) {
public Client(ISession session, IPromiseRepository promiseRepository) {
this.session = session;
this.promiseRepository = promiseRepository;
}
Expand Down Expand Up @@ -94,7 +92,8 @@ public Confirmation handleRequest(Request request) throws UnsupportedFeatureExce
}

@Override
public boolean asyncCompleteRequest(String uniqueId, Confirmation confirmation) throws UnsupportedFeatureException, OccurenceConstraintException {
public boolean asyncCompleteRequest(String uniqueId, Confirmation confirmation)
throws UnsupportedFeatureException, OccurenceConstraintException {
return session.completePendingPromise(uniqueId, confirmation);
}

Expand All @@ -104,7 +103,8 @@ public void handleError(
Optional<CompletableFuture<Confirmation>> promiseOptional =
promiseRepository.getPromise(uniqueId);
if (promiseOptional.isPresent()) {
promiseOptional.get()
promiseOptional
.get()
.completeExceptionally(
new CallErrorException(errorCode, errorDescription, payload));
} else {
Expand Down Expand Up @@ -158,11 +158,13 @@ public CompletableFuture<Confirmation> send(Request request)
String requestUuid = session.storeRequest(request);
CompletableFuture<Confirmation> promise = promiseRepository.createPromise(requestUuid);

// Clean up after the promise has completed, no matter if it was successful or had an error or a timeout.
promise.whenComplete((confirmation, throwable) -> {
session.removeRequest(requestUuid);
promiseRepository.removePromise(requestUuid);
});
// Clean up after the promise has completed, no matter if it was successful or had an error or a
// timeout.
promise.whenComplete(
(confirmation, throwable) -> {
session.removeRequest(requestUuid);
promiseRepository.removePromise(requestUuid);
});

session.sendRequest(featureOptional.get().getAction(), request, requestUuid);
return promise;
Expand All @@ -172,7 +174,8 @@ public UUID getSessionId() {
return this.session.getSessionId();
}

public boolean asyncCompleteRequest(String uniqueId, Confirmation confirmation) throws UnsupportedFeatureException, OccurenceConstraintException {
public boolean asyncCompleteRequest(String uniqueId, Confirmation confirmation)
throws UnsupportedFeatureException, OccurenceConstraintException {
return session.completePendingPromise(uniqueId, confirmation);
}
}
3 changes: 2 additions & 1 deletion ocpp-common/src/main/java/eu/chargetime/ocpp/ISession.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ public interface ISession {

void sendRequest(String action, Request payload, String uuid);

boolean completePendingPromise(String id, Confirmation confirmation) throws UnsupportedFeatureException, OccurenceConstraintException;
boolean completePendingPromise(String id, Confirmation confirmation)
throws UnsupportedFeatureException, OccurenceConstraintException;

void close();
}
4 changes: 2 additions & 2 deletions ocpp-common/src/main/java/eu/chargetime/ocpp/Queue.java
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ public Optional<Request> restoreRequest(String ticket) {
}

/**
* Remove a stored {@link Request} using a unique identifier.
* If no request is found for the identifier this method has no effect.
* Remove a stored {@link Request} using a unique identifier. If no request is found for the
* identifier this method has no effect.
*
* @param ticket unique identifier returned when {@link Request} was initially stored.
*/
Expand Down
Loading