Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Features/fix profile initialization (nulls and cross-over in FirmwareManagementProfiles) #176

Merged
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
39 changes: 21 additions & 18 deletions OCPP-J/src/main/java/eu/chargetime/ocpp/WebSocketListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,10 @@ public WebSocketListener(ISessionFactory sessionFactory, Draft... drafts) {
public void open(String hostname, int port, ListenerEvents handler) {
server =
new WebSocketServer(
new InetSocketAddress(hostname, port),
configuration.getParameter(JSONConfiguration.WEBSOCKET_WORKER_COUNT, DEFAULT_WEBSOCKET_WORKER_COUNT),
drafts) {
new InetSocketAddress(hostname, port),
configuration.getParameter(
JSONConfiguration.WEBSOCKET_WORKER_COUNT, DEFAULT_WEBSOCKET_WORKER_COUNT),
drafts) {
@Override
public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
logger.debug(
Expand Down Expand Up @@ -115,9 +116,9 @@ public void relay(String message) {
String proxiedAddress = clientHandshake.getFieldValue(HTTP_HEADER_PROXIED_ADDRESS);

logger.debug(
"New web-socket connection opened from address: {} proxied for: {}",
webSocket.getRemoteSocketAddress(),
proxiedAddress);
"New web-socket connection opened from address: {} proxied for: {}",
webSocket.getRemoteSocketAddress(),
proxiedAddress);

SessionInformation information =
new SessionInformation.Builder()
Expand All @@ -131,13 +132,14 @@ public void relay(String message) {
}

@Override
public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket webSocket, Draft draft,
ClientHandshake clientHandshake) throws InvalidDataException {
public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(
WebSocket webSocket, Draft draft, ClientHandshake clientHandshake)
throws InvalidDataException {
SessionInformation information =
new SessionInformation.Builder()
.Identifier(clientHandshake.getResourceDescriptor())
.InternetAddress(webSocket.getRemoteSocketAddress())
.build();
new SessionInformation.Builder()
.Identifier(clientHandshake.getResourceDescriptor())
.InternetAddress(webSocket.getRemoteSocketAddress())
.build();

String username = null;
byte[] password = null;
Expand All @@ -150,25 +152,26 @@ public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket web
// split credentials on username and password
for (int i = 0; i < credDecoded.length; i++) {
if (credDecoded[i] == ':') {
username = new String(Arrays.copyOfRange(credDecoded, 0, i), StandardCharsets.UTF_8);
username =
new String(Arrays.copyOfRange(credDecoded, 0, i), StandardCharsets.UTF_8);
if (i + 1 < credDecoded.length) {
password = Arrays.copyOfRange(credDecoded, i + 1, credDecoded.length);
}
break;
}
}
}
if (password == null || password.length < OCPPJ_CP_MIN_PASSWORD_LENGTH || password.length > OCPPJ_CP_MAX_PASSWORD_LENGTH)
if (password == null
|| password.length < OCPPJ_CP_MIN_PASSWORD_LENGTH
|| password.length > OCPPJ_CP_MAX_PASSWORD_LENGTH)
throw new InvalidDataException(401, "Invalid password length");
}

try {
handler.authenticateSession(information, username, password);
}
catch (AuthenticationException e) {
} catch (AuthenticationException e) {
throw new InvalidDataException(e.getErrorCode(), e.getMessage());
}
catch (Exception e) {
} catch (Exception e) {
throw new InvalidDataException(401, e.getMessage());
}
return super.onWebsocketHandshakeReceivedAsServer(webSocket, draft, clientHandshake);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ of this software and associated documentation files (the "Software"), to deal
import eu.chargetime.ocpp.model.SessionInformation;

public interface ListenerEvents {
void authenticateSession(SessionInformation information, String username, byte[] password) throws AuthenticationException;
void authenticateSession(SessionInformation information, String username, byte[] password)
throws AuthenticationException;

void newSession(ISession session, SessionInformation information);
}
133 changes: 68 additions & 65 deletions ocpp-common/src/main/java/eu/chargetime/ocpp/Server.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,12 @@ of this software and associated documentation files (the "Software"), to deal
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.model.SessionInformation;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

import eu.chargetime.ocpp.model.SessionInformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -83,76 +82,80 @@ public void open(String hostname, int port, ServerEvents serverEvents) {
new ListenerEvents() {

@Override
public void authenticateSession(SessionInformation information, String username, byte[] password) throws AuthenticationException {
public void authenticateSession(
SessionInformation information, String username, byte[] password)
throws AuthenticationException {
serverEvents.authenticateSession(information, username, password);
}

@Override
public void newSession(ISession session, SessionInformation information) {
session.accept(
new SessionEvents() {
@Override
public void handleConfirmation(String uniqueId, Confirmation confirmation) {

Optional<CompletableFuture<Confirmation>> promiseOptional =
promiseRepository.getPromise(uniqueId);
if (promiseOptional.isPresent()) {
promiseOptional.get().complete(confirmation);
promiseRepository.removePromise(uniqueId);
} else {
logger.debug("Promise not found for confirmation {}", confirmation);
}
}

@Override
public Confirmation handleRequest(Request request)
throws UnsupportedFeatureException {
Optional<Feature> featureOptional = featureRepository.findFeature(request);
if (featureOptional.isPresent()) {
Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
return featureOptional.get().handleRequest(sessionIdOptional.get(), request);
} else {
logger.error(
"Unable to handle request ({}), the active session was not found.",
request);
throw new IllegalStateException("Active session not found");
}
} else {
throw new UnsupportedFeatureException();
}
new SessionEvents() {
@Override
public void handleConfirmation(String uniqueId, Confirmation confirmation) {

Optional<CompletableFuture<Confirmation>> promiseOptional =
promiseRepository.getPromise(uniqueId);
if (promiseOptional.isPresent()) {
promiseOptional.get().complete(confirmation);
promiseRepository.removePromise(uniqueId);
} else {
logger.debug("Promise not found for confirmation {}", confirmation);
}
}

@Override
public Confirmation handleRequest(Request request)
throws UnsupportedFeatureException {
Optional<Feature> featureOptional = featureRepository.findFeature(request);
if (featureOptional.isPresent()) {
Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
return featureOptional
.get()
.handleRequest(sessionIdOptional.get(), request);
} else {
logger.error(
"Unable to handle request ({}), the active session was not found.",
request);
throw new IllegalStateException("Active session not found");
}

@Override
public void handleError(
String uniqueId, String errorCode, String errorDescription, Object payload) {
Optional<CompletableFuture<Confirmation>> promiseOptional =
promiseRepository.getPromise(uniqueId);
if (promiseOptional.isPresent()) {
promiseOptional
.get()
.completeExceptionally(
new CallErrorException(errorCode, errorDescription, payload));
promiseRepository.removePromise(uniqueId);
} else {
logger.debug("Promise not found for error {}", errorDescription);
}
}

@Override
public void handleConnectionClosed() {
Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
serverEvents.lostSession(sessionIdOptional.get());
sessions.remove(sessionIdOptional.get());
} else {
logger.warn("Active session not found");
}
}

@Override
public void handleConnectionOpened() {}
});
} else {
throw new UnsupportedFeatureException();
}
}

@Override
public void handleError(
String uniqueId, String errorCode, String errorDescription, Object payload) {
Optional<CompletableFuture<Confirmation>> promiseOptional =
promiseRepository.getPromise(uniqueId);
if (promiseOptional.isPresent()) {
promiseOptional
.get()
.completeExceptionally(
new CallErrorException(errorCode, errorDescription, payload));
promiseRepository.removePromise(uniqueId);
} else {
logger.debug("Promise not found for error {}", errorDescription);
}
}

@Override
public void handleConnectionClosed() {
Optional<UUID> sessionIdOptional = getSessionID(session);
if (sessionIdOptional.isPresent()) {
serverEvents.lostSession(sessionIdOptional.get());
sessions.remove(sessionIdOptional.get());
} else {
logger.warn("Active session not found");
}
}

@Override
public void handleConnectionOpened() {}
});

sessions.put(session.getSessionId(), session);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ of this software and associated documentation files (the "Software"), to deal
import java.util.UUID;

public interface ServerEvents {
default void authenticateSession(SessionInformation information, String username, byte[] password) throws AuthenticationException {}
default void authenticateSession(SessionInformation information, String username, byte[] password)
throws AuthenticationException {}

void newSession(UUID sessionIndex, SessionInformation information);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ public abstract class ProfileFeature implements Feature {
* @param ownerProfile the {@link Profile} that owns the function.
*/
public ProfileFeature(Profile ownerProfile) {
if (ownerProfile == null) {
throw new IllegalArgumentException("need non-null profile");
}
profile = ownerProfile;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,21 @@ public ClientCoreProfile(ClientCoreEventHandler handler) {
features = new ArrayList<>();
eventHandler = handler;

features.add(new AuthorizeFeature(null));
features.add(new BootNotificationFeature(null));
features.add(new AuthorizeFeature(this));
features.add(new BootNotificationFeature(this));
features.add(new ChangeAvailabilityFeature(this));
features.add(new ChangeConfigurationFeature(this));
features.add(new ClearCacheFeature(this));
features.add(new DataTransferFeature(this));
features.add(new GetConfigurationFeature(this));
features.add(new HeartbeatFeature(null));
features.add(new MeterValuesFeature(null));
features.add(new HeartbeatFeature(this));
features.add(new MeterValuesFeature(this));
features.add(new RemoteStartTransactionFeature(this));
features.add(new RemoteStopTransactionFeature(this));
features.add(new ResetFeature(this));
features.add(new StartTransactionFeature(null));
features.add(new StatusNotificationFeature(null));
features.add(new StopTransactionFeature(null));
features.add(new StartTransactionFeature(this));
features.add(new StatusNotificationFeature(this));
features.add(new StopTransactionFeature(this));
features.add(new UnlockConnectorFeature(this));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@ public class ClientFirmwareManagementProfile implements Profile {
public ClientFirmwareManagementProfile(ClientFirmwareManagementEventHandler eventHandler) {
this.eventHandler = eventHandler;
features = new HashSet<>();
features.add(new DiagnosticsStatusNotificationFeature(null));
features.add(new FirmwareStatusNotificationFeature(null));
features.add(new GetDiagnosticsFeature(this));
features.add(new UpdateFirmwareFeature(this));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,20 @@ public ServerCoreProfile(ServerCoreEventHandler handler) {
features = new HashSet<>();
features.add(new AuthorizeFeature(this));
features.add(new BootNotificationFeature(this));
features.add(new ChangeAvailabilityFeature(null));
features.add(new ChangeConfigurationFeature(null));
features.add(new ClearCacheFeature(null));
features.add(new ChangeAvailabilityFeature(this));
features.add(new ChangeConfigurationFeature(this));
features.add(new ClearCacheFeature(this));
features.add(new DataTransferFeature(this));
features.add(new GetConfigurationFeature(null));
features.add(new GetConfigurationFeature(this));
features.add(new HeartbeatFeature(this));
features.add(new MeterValuesFeature(this));
features.add(new RemoteStartTransactionFeature(null));
features.add(new RemoteStopTransactionFeature(null));
features.add(new ResetFeature(null));
features.add(new RemoteStartTransactionFeature(this));
features.add(new RemoteStopTransactionFeature(this));
features.add(new ResetFeature(this));
features.add(new StartTransactionFeature(this));
features.add(new StatusNotificationFeature(this));
features.add(new StopTransactionFeature(this));
features.add(new UnlockConnectorFeature(null));
features.add(new UnlockConnectorFeature(this));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,8 @@ public class ServerFirmwareManagementProfile implements Profile {
public ServerFirmwareManagementProfile(ServerFirmwareManagementEventHandler eventHandler) {
this.eventHandler = eventHandler;
features = new HashSet<>();
features.add(new GetDiagnosticsFeature(null));
features.add(new DiagnosticsStatusNotificationFeature(this));
features.add(new FirmwareStatusNotificationFeature(this));
features.add(new UpdateFirmwareFeature(null));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ public class ServerLocalAuthListProfile implements Profile {

public ServerLocalAuthListProfile() {
featureList = new HashSet<>();
featureList.add(new GetLocalListVersionFeature(null));
featureList.add(new SendLocalListFeature(null));
featureList.add(new GetLocalListVersionFeature(this));
featureList.add(new SendLocalListFeature(this));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public class ServerRemoteTriggerProfile implements Profile {
public ServerRemoteTriggerProfile() {

features = new HashSet<>();
features.add(new TriggerMessageFeature(null));
features.add(new TriggerMessageFeature(this));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ public class ServerReservationProfile implements Profile {

public ServerReservationProfile() {
features = new HashSet<>();
features.add(new ReserveNowFeature(null));
features.add(new CancelReservationFeature(null));
features.add(new ReserveNowFeature(this));
features.add(new CancelReservationFeature(this));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ public class ServerSmartChargingProfile implements Profile {

public ServerSmartChargingProfile() {
features = new HashSet<>();
features.add(new ClearChargingProfileFeature(null));
features.add(new GetCompositeScheduleFeature(null));
features.add(new SetChargingProfileFeature(null));
features.add(new ClearChargingProfileFeature(this));
features.add(new GetCompositeScheduleFeature(this));
features.add(new SetChargingProfileFeature(this));
}

@Override
Expand Down
Loading