use of com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse in project azure-iot-sdk-java by Azure.
the class IotHubExceptionManagerTest method httpResponseVerification_400_withErrorReason.
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBEXCEPTIONMANAGER_21_013: [If the httpresponse contains a reason message, the function must print this reason in the error message]
// Assert
@Test
public void httpResponseVerification_400_withErrorReason() throws IotHubException {
// Arrange
final int status = 400;
final byte[] body = { 1 };
final Map<String, List<String>> headerFields = new HashMap<>();
final byte[] errorReason = "{\"ExceptionMessage\":\"This is the error message\"}".getBytes();
HttpResponse response = new HttpResponse(status, body, headerFields, errorReason);
// Act
try {
IotHubExceptionManager.httpResponseVerification(response);
assert true;
} catch (IotHubBadFormatException expected) {
// Expected throw.
assertThat(expected.getMessage(), is("Bad message format! This is the error message"));
}
}
use of com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse in project azure-iot-sdk-java by Azure.
the class DeviceMethod method invoke.
/**
* Directly invokes a method on the device and return its result.
*
* @param deviceId is the device identification.
* @param methodName is the name of the method that shall be invoked on the device.
* @param responseTimeoutInSeconds is the maximum waiting time for a response from the device in seconds.
* @param connectTimeoutInSeconds is the maximum waiting time for a response from the connection in seconds.
* @param payload is the the method parameter
* @return the status and payload resulted from the method invoke
* @throws IotHubException This exception is thrown if the response verification failed
* @throws IOException This exception is thrown if the IO operation failed
*/
public synchronized MethodResult invoke(String deviceId, String methodName, Long responseTimeoutInSeconds, Long connectTimeoutInSeconds, Object payload) throws IotHubException, IOException {
/* Codes_SRS_DEVICEMETHOD_21_004: [The invoke shall throw IllegalArgumentException if the provided deviceId is null or empty.] */
if ((deviceId == null) || deviceId.isEmpty()) {
throw new IllegalArgumentException("deviceId is empty or null.");
}
/* Codes_SRS_DEVICEMETHOD_21_005: [The invoke shall throw IllegalArgumentException if the provided methodName is null, empty, or not valid.] */
if ((methodName == null) || methodName.isEmpty()) {
throw new IllegalArgumentException("methodName is empty or null.");
}
/* Codes_SRS_DEVICEMETHOD_21_006: [The invoke shall throw IllegalArgumentException if the provided responseTimeoutInSeconds is negative.] */
/* Codes_SRS_DEVICEMETHOD_21_007: [The invoke shall throw IllegalArgumentException if the provided connectTimeoutInSeconds is negative.] */
/* Codes_SRS_DEVICEMETHOD_21_014: [The invoke shall bypass the Exception if one of the functions called by invoke failed.] */
MethodParser methodParser = new MethodParser(methodName, responseTimeoutInSeconds, connectTimeoutInSeconds, payload);
/* Codes_SRS_DEVICEMETHOD_21_011: [The invoke shall add a HTTP body with Json created by the `serializer.MethodParser`.] */
String json = methodParser.toJson();
if (json == null) {
/* Codes_SRS_DEVICEMETHOD_21_012: [If `MethodParser` return a null Json, the invoke shall throw IllegalArgumentException.] */
throw new IllegalArgumentException("MethodParser return null Json");
}
/* Codes_SRS_DEVICEMETHOD_21_008: [The invoke shall build the Method URL `{iot hub}/twins/{device id}/methods/` by calling getUrlMethod.] */
URL url = this.iotHubConnectionString.getUrlMethod(deviceId);
long responseTimeout, connectTimeout;
if (responseTimeoutInSeconds == null) {
// If timeout is not set, it defaults to 30 seconds
responseTimeout = DEFAULT_RESPONSE_TIMEOUT;
} else {
responseTimeout = responseTimeoutInSeconds;
}
if (connectTimeoutInSeconds == null) {
connectTimeout = DEFAULT_CONNECT_TIMEOUT;
} else {
connectTimeout = connectTimeoutInSeconds;
}
// Calculate total timeout in milliseconds
long timeoutInMs = (responseTimeout + connectTimeout) * THOUSAND_MS;
/* Codes_SRS_DEVICEMETHOD_21_009: [The invoke shall send the created request and get the response using the HttpRequester.] */
/* Codes_SRS_DEVICEMETHOD_21_010: [The invoke shall create a new HttpRequest with http method as `POST`.] */
HttpResponse response = DeviceOperations.request(this.iotHubConnectionString, url, HttpMethod.POST, json.getBytes(StandardCharsets.UTF_8), String.valueOf(requestId++), timeoutInMs);
/* Codes_SRS_DEVICEMETHOD_21_013: [The invoke shall deserialize the payload using the `serializer.MethodParser`.] */
MethodParser methodParserResponse = new MethodParser();
methodParserResponse.fromJson(new String(response.getBody(), StandardCharsets.UTF_8));
/* Codes_SRS_DEVICEMETHOD_21_015: [If the HttpStatus represents success, the invoke shall return the status and payload using the `MethodResult` class.] */
return new MethodResult(methodParserResponse.getStatus(), methodParserResponse.getPayload());
}
use of com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse in project azure-iot-sdk-java by Azure.
the class DeviceOperations method request.
/**
* Send a http request to the IoTHub using the Twin/Method standard, and return its response.
*
* @param iotHubConnectionString is the connection string for the IoTHub
* @param url is the Twin URL for the device ID.
* @param method is the HTTP method (GET, POST, DELETE, PATCH, PUT).
* @param payload is the array of bytes that contains the payload.
* @param requestId is an unique number that identify the request.
* @param timeoutInMs is timeout in milliseconds.
* @return the result of the request.
* @throws IotHubException This exception is thrown if the response verification failed
* @throws IOException This exception is thrown if the IO operation failed
*/
public static HttpResponse request(IotHubConnectionString iotHubConnectionString, URL url, HttpMethod method, byte[] payload, String requestId, long timeoutInMs) throws IOException, IotHubException, IllegalArgumentException {
/* Codes_SRS_DEVICE_OPERATIONS_21_001: [The request shall throw IllegalArgumentException if the provided `iotHubConnectionString` is null.] */
if (iotHubConnectionString == null) {
throw new IllegalArgumentException("Null ConnectionString");
}
/* Codes_SRS_DEVICE_OPERATIONS_21_002: [The request shall throw IllegalArgumentException if the provided `url` is null.] */
if (url == null) {
throw new IllegalArgumentException("Null URL");
}
/* Codes_SRS_DEVICE_OPERATIONS_21_003: [The request shall throw IllegalArgumentException if the provided `method` is null.] */
if (method == null) {
throw new IllegalArgumentException("Null method");
}
/* Codes_SRS_DEVICE_OPERATIONS_21_004: [The request shall throw IllegalArgumentException if the provided `payload` is null.] */
if (payload == null) {
throw new IllegalArgumentException("Null payload");
}
/* Codes_SRS_DEVICE_OPERATIONS_21_005: [The request shall throw IllegalArgumentException if the provided `requestId` is null or empty.] */
if ((requestId == null) || requestId.isEmpty()) {
throw new IllegalArgumentException("requestId is null or empty");
}
/* Codes_SRS_DEVICE_OPERATIONS_99_018: [The request shall throw IllegalArgumentException if the provided `timeoutInMs` exceed Integer.MAX_VALUE.] */
if ((timeoutInMs + DEFAULT_HTTP_TIMEOUT_MS) > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP Request timeout shouldn't not exceed " + Integer.MAX_VALUE + " milliseconds");
}
/* Codes_SRS_DEVICE_OPERATIONS_21_006: [The request shall create a new SASToken with the ServiceConnect rights.] */
String sasTokenString = new IotHubServiceSasToken(iotHubConnectionString).toString();
/* Codes_SRS_DEVICE_OPERATIONS_21_007: [If the SASToken is null or empty, the request shall throw IOException.] */
if ((sasTokenString == null) || sasTokenString.isEmpty()) {
throw new IOException("Illegal sasToken null or empty");
}
/* Codes_SRS_DEVICE_OPERATIONS_21_008: [The request shall create a new HttpRequest with the provided `url`, http `method`, and `payload`.] */
HttpRequest request = new HttpRequest(url, method, payload);
/* Codes_SRS_DEVICE_OPERATIONS_21_009: [The request shall add to the HTTP header the sum of timeout and default timeout in milliseconds.] */
request.setReadTimeoutMillis((int) (timeoutInMs + DEFAULT_HTTP_TIMEOUT_MS));
/* Codes_SRS_DEVICE_OPERATIONS_21_010: [The request shall add to the HTTP header an `authorization` key with the SASToken.] */
request.setHeaderField(AUTHORIZATION, sasTokenString);
/* Codes_SRS_DEVICE_OPERATIONS_21_011: [The request shall add to the HTTP header a `Request-Id` key with a new unique string value for every request.] */
request.setHeaderField(REQUEST_ID, requestId);
/* Codes_SRS_DEVICE_OPERATIONS_21_012: [The request shall add to the HTTP header a `User-Agent` key with the client Id and service version.] */
request.setHeaderField(USER_AGENT, TransportUtils.getJavaServiceClientIdentifier() + TransportUtils.getServiceVersion());
/* Codes_SRS_DEVICE_OPERATIONS_21_013: [The request shall add to the HTTP header a `Accept` key with `application/json`.] */
request.setHeaderField(ACCEPT, ACCEPT_VALUE);
/* Codes_SRS_DEVICE_OPERATIONS_21_014: [The request shall add to the HTTP header a `Content-Type` key with `application/json; charset=utf-8`.] */
request.setHeaderField(CONTENT_TYPE, ACCEPT_VALUE + "; " + ACCEPT_CHARSET);
/* Codes_SRS_DEVICE_OPERATIONS_21_015: [The request shall send the created request and get the response.] */
HttpResponse response = request.send();
/* Codes_SRS_DEVICE_OPERATIONS_21_016: [If the resulted HttpResponseStatus represents fail, the request shall throw proper Exception by calling httpResponseVerification.] */
IotHubExceptionManager.httpResponseVerification(response);
/* Codes_SRS_DEVICE_OPERATIONS_21_017: [If the resulted status represents success, the request shall return the http response.] */
return response;
}
use of com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse in project azure-iot-sdk-java by Azure.
the class DeviceTwin method updateTwin.
/**
* This method updates device twin for the specified device.
*
* @param device The device with a valid id for which device twin is to be updated.
* @throws IOException This exception is thrown if the IO operation failed
* @throws IotHubException This exception is thrown if the response verification failed
*/
public synchronized void updateTwin(DeviceTwinDevice device) throws IotHubException, IOException {
if (device == null || device.getDeviceId() == null || device.getDeviceId().length() == 0) {
/*
**Codes_SRS_DEVICETWIN_25_013: [** The function shall throw IllegalArgumentException if the input device is null or if deviceId is null or empty **]**
*/
throw new IllegalArgumentException("Instantiate a device and set device id to be used");
}
if ((device.getDesiredMap() == null || device.getDesiredMap().isEmpty()) && (device.getTagsMap() == null || device.getTagsMap().isEmpty())) {
/*
**Codes_SRS_DEVICETWIN_25_045: [** The function shall throw IllegalArgumentException if the both desired and tags maps are either empty or null **]**
*/
throw new IllegalArgumentException("Set either desired properties or tags for the device to be updated with");
}
/*
**Codes_SRS_DEVICETWIN_25_014: [** The function shall build the URL for this operation by calling getUrlTwin **]**
*/
URL url = this.iotHubConnectionString.getUrlTwin(device.getDeviceId());
/*
**Codes_SRS_DEVICETWIN_25_015: [** The function shall serialize the twin map by calling updateTwin Api on the twin object for the device provided by the user**]**
*/
String twinJson = device.getTwinParser().updateTwin(device.getDesiredMap(), null, device.getTagsMap());
if (twinJson == null || twinJson.isEmpty()) {
/*
**Codes_SRS_DEVICETWIN_25_046: [** The function shall throw IOException if updateTwin Api call returned an empty or null json**]**
*/
throw new IOException("Serializer cannot return null json to update");
}
/*
**Codes_SRS_DEVICETWIN_25_016: [** The function shall create a new SAS token **]**
**Codes_SRS_DEVICETWIN_25_017: [** The function shall create a new HttpRequest with http method as Patch **]**
**Codes_SRS_DEVICETWIN_25_018: [** The function shall set the following HTTP headers specified in the IotHub DeviceTwin doc.
1. Key as authorization with value as sastoken
2. Key as request id with a new string value for every request
3. Key as User-Agent with value specified by the clientIdentifier and its version
4. Key as Accept with value as application/json
5. Key as Content-Type and value as application/json
6. Key as charset and value as utf-8
7. Key as If-Match and value as '*' **]**
**Codes_SRS_DEVICETWIN_25_019: [** The function shall send the created request and get the response **]**
**Codes_SRS_DEVICETWIN_25_020: [** The function shall verify the response status and throw proper Exception **]**
*/
HttpResponse response = DeviceOperations.request(this.iotHubConnectionString, url, HttpMethod.PATCH, twinJson.getBytes(StandardCharsets.UTF_8), String.valueOf(requestId++), 0);
}
use of com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse in project azure-iot-sdk-java by Azure.
the class RegistryManager method getDevices.
/**
* Get list of devices
*
* @param maxCount The requested count of devices
* @return The array of requested device objects
* @throws IOException This exception is thrown if the IO operation failed
* @throws IotHubException This exception is thrown if the response verification failed
*/
public ArrayList<Device> getDevices(Integer maxCount) throws IOException, IotHubException, JsonSyntaxException {
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_023: [The constructor shall throw IllegalArgumentException if the input count number is less than 1]
if (maxCount < 1) {
throw new IllegalArgumentException("maxCount cannot be less then 1");
}
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_024: [The function shall get the URL for the device]
URL url = iotHubConnectionString.getUrlDeviceList(maxCount);
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_025: [The function shall create a new SAS token for the device]
String sasTokenString = new IotHubServiceSasToken(this.iotHubConnectionString).toString();
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_026: [The function shall create a new HttpRequest for getting a device list from IotHub]
HttpRequest request = CreateRequest(url, HttpMethod.GET, new byte[0], sasTokenString);
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_027: [The function shall send the created request and get the response]
HttpResponse response = request.send();
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_028: [The function shall verify the response status and throw proper Exception]
IotHubExceptionManager.httpResponseVerification(response);
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_029: [The function shall create a new ArrayList<Device> object from the response and return with it]
String bodyStr = new String(response.getBody(), StandardCharsets.UTF_8);
try (JsonReader jsonReader = Json.createReader(new StringReader(bodyStr))) {
ArrayList<Device> deviceList = new ArrayList<>();
JsonArray deviceArray = jsonReader.readArray();
for (int i = 0; i < deviceArray.size(); i++) {
JsonObject jsonObject = deviceArray.getJsonObject(i);
Device iotHubDevice = gson.fromJson(jsonObject.toString(), Device.class);
deviceList.add(iotHubDevice);
}
return deviceList;
}
}
Aggregations