public void stop() { isStarted = false; if (!requestMap.isEmpty()) { logger.LogInfo("Pending %d responses from IotHub yet unsubscribed %s", requestMap.size(), logger.getMethodName()); } }
public void stop() { isStarted = false; if (!requestMap.isEmpty()) { logger.LogInfo("Pending %d responses to be sent to IotHub yet unsubscribed %s", requestMap.size(), logger.getMethodName()); } }
/** * Checks if any messages were received over HTTP and adds all of them to the received messages queue * @throws TransportException if an exception occurs while receiving messages over HTTP connection */ private void addReceivedMessagesOverHttpToReceivedQueue() throws TransportException { //since Http behaves synchronously, we need to check synchronously for any messages it may have received IotHubTransportMessage transportMessage = ((HttpsIotHubConnection)this.iotHubTransportConnection).receiveMessage(); if (transportMessage != null) { //Codes_SRS_IOTHUBTRANSPORT_34_056: [If the saved http transport connection can receive a message, add it to receivedMessagesQueue.] logger.LogInfo("Message with hashcode %s is received from IotHub on %s, method name is addReceivedMessagesOverHttpToReceivedQueue", transportMessage.hashCode(), new Date()); this.receivedMessagesQueue.add(transportMessage); } }
/** * Setter for the expiryTime property. This setter uses relative time, not absolute time. * @param timeOut The time out for the message, in milliseconds, from the current time. */ public void setExpiryTime(long timeOut) { // Codes_SRS_MESSAGE_34_047: [The function shall set the message's expiry time.] long currentTime = System.currentTimeMillis(); this.expiryTime = currentTime + timeOut; logger.LogInfo("The message with messageid %s has expiry time as %s milliseconds and the message will expire on %s, method name is %s ", this.getMessageId(), timeOut, new Date(this.expiryTime), logger.getMethodName()); }
/** * Setter for the expiryTime property using absolute time * @param absoluteTimeout The time out for the message, in milliseconds. */ public void setAbsoluteExpiryTime(long absoluteTimeout) { // Codes_SRS_MESSAGE_34_038: [If the provided absolute expiry time is negative, an IllegalArgumentException shall be thrown.] if (absoluteTimeout < 0) { throw new IllegalArgumentException("ExpiryTime may not be negative"); } // Codes_SRS_MESSAGE_34_037: [The function shall set the message's expiry time to be the number of milliseconds since the epoch provided in absoluteTimeout.] this.expiryTime = absoluteTimeout; logger.LogInfo("The message with messageid %s has expiry time as %s milliseconds and the message will expire on %s, method name is %s ", this.getMessageId(), absoluteTimeout, new Date(this.expiryTime), logger.getMethodName()); }
/** * Registers the given device into the transport client. * * @throws IllegalArgumentException if the deviceClient parameter is null. * @throws IllegalStateException if the connection is open. */ void registerDeviceClient(DeviceClient deviceClient) throws IllegalArgumentException, IllegalStateException { // Codes_SRS_TRANSPORTCLIENT_12_005: [The function shall throw IllegalArgumentException if the deviceClient parameter is null.] if (deviceClient == null) { throw new IllegalArgumentException("deviceClient parameter cannot be null."); } // Codes_SRS_TRANSPORTCLIENT_12_006: [The function shall throw IllegalStateException if the connection is already open.] if ((this.deviceIO != null) && (this.deviceIO.isOpen())) { throw new IllegalStateException("deviceClient cannot be registered if the connection is open."); } // Codes_SRS_TRANSPORTCLIENT_12_007: [The function shall add the given device client to the deviceClientList.] this.deviceClientList.add(deviceClient); logger.LogInfo("DeviceClient is added successfully to the transport client, method name is %s ", logger.getMethodName()); }
logger.LogInfo("Shutdown of executor service has started, method name is %s ", logger.getMethodName()); this.executorService.shutdown(); try logger.LogInfo("Pool did not terminate"); throw new TransportException("Waited too long for the connection to close.", e); logger.LogInfo("Shutdown of executor service completed, method name is %s ", logger.getMethodName());
/*** * Sets the given send interval on the underlying device IO * * @param newIntervalInMilliseconds the new interval in milliseconds * @throws IOException if the given number is less or equal to zero. */ public void setSendInterval(long newIntervalInMilliseconds) throws IOException { if (newIntervalInMilliseconds <= 0) { // Codes_SRS_TRANSPORTCLIENT_12_017: [The function shall throw IllegalArgumentException if the newIntervalInMilliseconds parameter is less or equql to zero.] throw new IllegalArgumentException("send interval can not be zero or negative"); } if ((this.transportClientState != TransportClientState.OPENED) || (deviceIO == null)) { // Codes_SRS_TRANSPORTCLIENT_12_023: [The function shall throw IllegalStateException if the connection is already open.] throw new IllegalStateException("TransportClient.setSendInterval only works when the transport client is opened"); } // Codes_SRS_TRANSPORTCLIENT_12_018: [The function shall set the new interval on the underlying device IO it the transport client is not open.] this.deviceIO.setSendPeriodInMilliseconds(newIntervalInMilliseconds); logger.LogInfo("Send interval updated successfully in the transport client, method name is %s ", logger.getMethodName()); }
@Override public void onConnectionEstablished(String connectionId) { if (connectionId.equals(this.iotHubTransportConnection.getConnectionId())) { logger.LogInfo("The connection to the IoT Hub has been established, method name is %s ", logger.getMethodName()); //Codes_SRS_IOTHUBTRANSPORT_34_014: [If the provided connectionId is associated with the current connection, This function shall invoke updateStatus with status CONNECTED, change // reason CONNECTION_OK and a null throwable.] this.updateStatus(IotHubConnectionStatus.CONNECTED, IotHubConnectionStatusChangeReason.CONNECTION_OK, null); } }
/** * Starts asynchronously sending and receiving messages from an IoT Hub. If * the client is already open, the function shall do nothing. * * @throws IOException if a connection to an IoT Hub cannot be established. */ public void open() throws IOException { if (this.ioTHubConnectionType == IoTHubConnectionType.USE_TRANSPORTCLIENT) { if (this.transportClient.getTransportClientState() == TransportClient.TransportClientState.CLOSED) { // Codes_SRS_DEVICECLIENT_12_007: [If the client has been initialized to use TransportClient and the TransportClient is not opened yet the function shall throw an IOException.] throw new IOException("Calling open() when using the TransportClient is not supported. Use TransportClient.open() instead."); } else { // Codes_SRS_DEVICECLIENT_12_019: [If the client has been initialized to use TransportClient and the TransportClient is already opened the function shall do nothing.] logger.LogInfo("Connection already opened by TransportClient."); } } else { // Codes_SRS_DEVICECLIENT_21_006: [The open shall invoke super.open().] super.open(); } logger.LogInfo("Connection opened with success, method name is %s ", logger.getMethodName()); }
/** * Sets the given retry policy on the underlying transport * Sets the given retry policy on the underlying transport * <a href="https://github.com/Azure/azure-iot-sdk-java/blob/master/device/iot-device-client/devdoc/requirement_docs/com/microsoft/azure/iothub/retryPolicy.md"> * See more details about the default retry policy and about using custom retry policies here</a> * @param retryPolicy the new interval in milliseconds * @throws UnsupportedOperationException if no device client has been registered yet. */ public void setRetryPolicy(RetryPolicy retryPolicy) { if (deviceClientList.size() == 0) { // Codes_SRS_TRANSPORTCLIENT_28_001: [The function shall throw UnsupportedOperationException if there is no registered device client] throw new UnsupportedOperationException("TransportClient.setRetryPolicy only works when there is at least one registered device client."); } for (int i = 0; i < this.deviceClientList.size(); i++) { // Codes_SRS_TRANSPORTCLIENT_28_002: [The function shall set the retry policies to all registered device clients.] deviceClientList.get(i).getConfig().setRetryPolicy(retryPolicy); } logger.LogInfo("Retry policy updated successfully in the transport client, method name is %s ", logger.getMethodName()); }
/** * Completes all current outstanding requests and closes the IoT Hub client. * Must be called to terminate the background thread that is sending data to * IoT Hub. After {@code closeNow()} is called, the IoT Hub client is no longer * usable. If the client is already closed, the function shall do nothing. * * @throws IOException if the connection to an IoT Hub cannot be closed. */ public void closeNow() throws IOException { // Codes_SRS_TRANSPORTCLIENT_12_015: [If the registered device list is not empty the function shall call closeFileUpload on all devices.] for (int i = 0; i < this.deviceClientList.size(); i++) { deviceClientList.get(i).closeFileUpload(); } // Codes_SRS_TRANSPORTCLIENT_12_014: [If the deviceIO not null the function shall call multiplexClose on the deviceIO and set the deviceIO to null.] if (this.deviceIO != null) { this.deviceIO.multiplexClose(); this.deviceIO = null; } logger.LogInfo("Connection closed with success, method name is %s ", logger.getMethodName()); }
public DeviceClientConfig(IotHubAuthenticationProvider authenticationProvider) throws IllegalArgumentException { if (!(authenticationProvider instanceof IotHubSasTokenAuthenticationProvider)) { throw new UnsupportedOperationException("This constructor only support sas token authentication currently"); } this.authenticationProvider = authenticationProvider; this.useWebsocket = false; this.productInfo = new ProductInfo(); this.logger = new CustomLogger(this.getClass()); logger.LogInfo("DeviceClientConfig object is created successfully with IotHubName=%s, deviceID=%s , method name is %s ", this.authenticationProvider.getHostname(), authenticationProvider.getDeviceId(), logger.getMethodName()); }
/** * Attempts to reconnect. By the end of this call, the state of this object shall be either CONNECTED or DISCONNECTED * @param transportException */ private void handleDisconnection(TransportException transportException) { logger.LogInfo("The messages in progress are buffered to be sent again due to a connection loss, " + "method name is %s ", logger.getMethodName()); synchronized (this.inProgressMessagesLock) { //Codes_SRS_IOTHUBTRANSPORT_34_057: [This function shall move all packets from inProgressQueue to waiting queue.] this.waitingPacketsQueue.addAll(inProgressPackets.values()); inProgressPackets.clear(); } //Codes_SRS_IOTHUBTRANSPORT_34_058: [This function shall invoke updateStatus with DISCONNECTED_RETRYING, and the provided transportException.] this.updateStatus(IotHubConnectionStatus.DISCONNECTED_RETRYING, exceptionToStatusChangeReason(transportException), transportException); //Codes_SRS_IOTHUBTRANSPORT_34_059: [This function shall invoke checkForUnauthorizedException with the provided exception.] checkForUnauthorizedException(transportException); //Codes_SRS_IOTHUBTRANSPORT_34_060: [This function shall invoke reconnect with the provided exception.] reconnect(transportException); }
public IotHubConnectionString(String hostName, String deviceId, String sharedAccessKey, String sharedAccessToken, String gatewayHostName) throws IllegalArgumentException, URISyntaxException { this.isUsingX509 = (sharedAccessKey == null && sharedAccessToken == null); /* Codes_SRS_IOTHUB_CONNECTIONSTRING_21_025: [If the parameters for the connection string is not valid, the constructor shall throw an IllegalArgumentException.] */ validateTerms(hostName, deviceId, sharedAccessKey, sharedAccessToken, this.isUsingX509); /* Codes_SRS_IOTHUB_CONNECTIONSTRING_21_020: [The constructor shall save the IoT Hub hostname as the value of `hostName` in the connection string.] */ this.hostName = hostName; /* Codes_SRS_IOTHUB_CONNECTIONSTRING_21_021: [The constructor shall save the first part of the IoT Hub hostname as the value of `hubName`, hostname split by `.`.] */ this.hubName = parseHubName(this.hostName); /* Codes_SRS_IOTHUB_CONNECTIONSTRING_21_022: [The constructor shall save the device ID as the UTF-8 URL-decoded value of `deviceId` in the connection string.] */ this.deviceId = deviceId; /* Codes_SRS_IOTHUB_CONNECTIONSTRING_21_023: [The constructor shall save the device key as the value of `sharedAccessKey` in the connection string.] */ this.sharedAccessKey = sharedAccessKey; /* Codes_SRS_IOTHUB_CONNECTIONSTRING_21_024: [The constructor shall save the shared access token as the value of `sharedAccessToken` in the connection string.] */ this.sharedAccessToken = sharedAccessToken; /* Codes_SRS_IOTHUB_CONNECTIONSTRING_34_036: [If the SAS Token has expired, throw a SecurityException.] */ if (this.sharedAccessToken != null && IotHubSasToken.isExpired(this.sharedAccessToken)) { throw new SecurityException("Your SAS Token has expired"); } this.gatewayHostName = gatewayHostName; if (this.gatewayHostName != null && !this.gatewayHostName.isEmpty()) { this.hostName = gatewayHostName; } this.logger = new CustomLogger(this.getClass()); logger.LogInfo("IotHubConnectionString object is created successfully, method name is %s ", logger.getMethodName()); }
@Override public void onMessageReceived(IotHubTransportMessage message, Throwable e) { if (message != null && e != null) { //Codes_SRS_IOTHUBTRANSPORT_34_008: [If this function is called with a non-null message and a non-null // throwable, this function shall log an IllegalArgumentException.] this.logger.LogError("IllegalArgumentException encountered, method name is %s", this.logger.getMethodName()); this.logger.LogError(new IllegalArgumentException("Cannot call onMessageReceived with non-null message and " + "non-null throwable")); } else if (message != null) { //Codes_SRS_IOTHUBTRANSPORT_34_009: [If this function is called with a non-null message and a null // exception, this function shall add that message to the receivedMessagesQueue.] logger.LogInfo("Message with hashcode %s is received from IotHub on %s, method name is onMessageReceived", message.hashCode(), new Date()); this.receivedMessagesQueue.add(message); } else if (e != null) { //Codes_SRS_IOTHUBTRANSPORT_34_010: [If this function is called with a null message and a non-null // throwable, this function shall log that exception.] this.logger.LogError("Exception encountered while receiving messages from service, " + "method name is %s", this.logger.getMethodName()); this.logger.LogError(e); } }
/** * Invokes the callbacks for all completed requests. */ public void invokeCallbacks() { IotHubTransportPacket packet = this.callbackPacketsQueue.poll(); while (packet != null) { IotHubStatusCode status = packet.getStatus(); IotHubEventCallback callback = packet.getCallback(); Object context = packet.getContext(); logger.LogInfo("Invoking the callback function for sent message, IoT Hub responded to message with " + "status %s, method name is %s ", status.name(), logger.getMethodName()); //Codes_SRS_IOTHUBTRANSPORT_34_045: [This function shall dequeue each packet in the callback queue and // execute their saved callback with their saved status and context] callback.execute(status, context); packet = this.callbackPacketsQueue.poll(); } }
/** * Private helper for open. * Starts the Proton reactor. */ private void openAsync() throws TransportException { logger.LogDebug("Entered in method %s", logger.getMethodName()); if (this.reactor == null) { // Codes_SRS_AMQPSIOTHUBCONNECTION_12_003: [The constructor shall throw TransportException if the Proton reactor creation failed.] this.reactor = createReactor(); } if (executorService == null) { executorService = Executors.newFixedThreadPool(1); } IotHubReactor iotHubReactor = new IotHubReactor(reactor); ReactorRunner reactorRunner = new ReactorRunner(iotHubReactor, this.listener, this.connectionId); executorService.submit(reactorRunner); logger.LogInfo("Reactor is assigned to executor service, method name is %s ", logger.getMethodName()); }
/** * Private helper for close. * Closes the AmqpsSessionManager, the connection and stops the Proton reactor. */ private void closeAsync() { logger.LogDebug("Entered in method %s", logger.getMethodName()); // Codes_SRS_AMQPSIOTHUBCONNECTION_15_012: [The function shall set the status of the AMQPS connection to DISCONNECTED.] this.state = IotHubConnectionStatus.DISCONNECTED; // Codes_SRS_AMQPSIOTHUBCONNECTION_15_013: [The function shall closeNow the AmqpsSessionManager and the AMQP connection.] this.amqpsSessionManager.closeNow(); if (this.connection != null) { this.connection.close(); } // Codes_SRS_AMQPSIOTHUBCONNECTION_34_014: [If this object's proton reactor is not null, this function shall stop the Proton reactor.] if (this.reactor != null) { this.reactor.stop(); } logger.LogInfo("Proton reactor has been stopped, method name is %s ", logger.getMethodName()); logger.LogDebug("Exited from method %s", logger.getMethodName()); }