Search in sources :

Example 31 with JobResult

use of com.microsoft.azure.sdk.iot.service.jobs.JobResult in project azure-iot-sdk-java by Azure.

the class JobClientTests method scheduleUpdateTwinSucceed.

@Test(timeout = TEST_TIMEOUT_MILLISECONDS)
@Ignore
public void scheduleUpdateTwinSucceed() throws InterruptedException {
    // Arrange
    ExecutorService executor = Executors.newFixedThreadPool(MAX_NUMBER_JOBS);
    DeviceTestManager deviceTestManger = devices.get(0);
    final String deviceId = testDevice.getDeviceId();
    final String queryCondition = "DeviceId IN ['" + deviceId + "']";
    final ConcurrentMap<String, Exception> jobExceptions = new ConcurrentHashMap<>();
    final ConcurrentMap<String, JobResult> jobResults = new ConcurrentHashMap<>();
    final ConcurrentMap<String, Integer> twinExpectedTemperature = new ConcurrentHashMap<>();
    final ArrayList<String> jobIdsPending = new ArrayList<>();
    // Act
    for (int i = 0; i < MAX_NUMBER_JOBS; i++) {
        final int jobTemperature = (newTemperature++);
        executor.submit(() -> {
            String jobId = JOB_ID_NAME + UUID.randomUUID();
            jobIdsPending.add(jobId);
            try {
                DeviceTwinDevice deviceTwinDevice = new DeviceTwinDevice(deviceId);
                Set<Pair> testDesProp = new HashSet<>();
                testDesProp.add(new Pair(STANDARD_PROPERTY_HOMETEMP, jobTemperature));
                deviceTwinDevice.setDesiredProperties(testDesProp);
                twinExpectedTemperature.put(jobId, jobTemperature);
                jobClient.scheduleUpdateTwin(jobId, queryCondition, deviceTwinDevice, new Date(), MAX_EXECUTION_TIME_IN_SECONDS);
                JobResult jobResult = jobClient.getJob(jobId);
                while (jobResult.getJobStatus() != JobStatus.completed) {
                    Thread.sleep(MAXIMUM_TIME_TO_WAIT_FOR_IOTHUB_MILLISECONDS);
                    jobResult = jobClient.getJob(jobId);
                }
                jobResult = queryJobResponseResult(jobId, JobType.scheduleUpdateTwin, JobStatus.completed);
                jobResults.put(jobId, jobResult);
            } catch (IotHubException | IOException | InterruptedException e) {
                jobExceptions.put(jobId, e);
            }
            jobIdsPending.remove(jobId);
        });
    }
    cleanupJobs(executor, jobIdsPending);
    // Assert
    // asserts for the client side.
    assertEquals(0, deviceTestManger.getStatusError());
    ConcurrentMap<String, ConcurrentLinkedQueue<Object>> changes = deviceTestManger.getTwinChanges();
    ConcurrentLinkedQueue<Object> receivedTemperatures = changes.get(STANDARD_PROPERTY_HOMETEMP);
    assertNotNull(receivedTemperatures);
    assertEquals(MAX_NUMBER_JOBS, receivedTemperatures.size());
    // asserts for the service side.
    if (jobExceptions.size() != 0) {
        for (Map.Entry<String, Exception> jobException : jobExceptions.entrySet()) {
            log.error("{} threw", jobException.getKey(), jobException.getValue());
        }
        fail("Service throw an exception enqueuing jobs");
    }
    assertEquals("Missing job result", MAX_NUMBER_JOBS, jobResults.size());
    for (Map.Entry<String, JobResult> job : jobResults.entrySet()) {
        String jobId = job.getKey();
        JobResult jobResult = job.getValue();
        assertNotNull(jobResult);
        assertEquals("JobResult reported incorrect jobId", jobId, jobResult.getJobId());
        String expectedTemperature = twinExpectedTemperature.get(jobId) + ".0";
        assertTrue("Device do not change " + STANDARD_PROPERTY_HOMETEMP + " to " + expectedTemperature, receivedTemperatures.contains(expectedTemperature));
    }
}
Also used : DeviceTwinDevice(com.microsoft.azure.sdk.iot.service.devicetwin.DeviceTwinDevice) ArrayList(java.util.ArrayList) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IotHubException(com.microsoft.azure.sdk.iot.service.exceptions.IotHubException) Pair(com.microsoft.azure.sdk.iot.service.devicetwin.Pair) HashSet(java.util.HashSet) JobResult(com.microsoft.azure.sdk.iot.service.jobs.JobResult) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) IotHubException(com.microsoft.azure.sdk.iot.service.exceptions.IotHubException) IotHubUnathorizedException(com.microsoft.azure.sdk.iot.service.exceptions.IotHubUnathorizedException) Date(java.util.Date) DeviceTestManager(tests.integration.com.microsoft.azure.sdk.iot.helpers.DeviceTestManager) ExecutorService(java.util.concurrent.ExecutorService) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Ignore(org.junit.Ignore) ContinuousIntegrationTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.ContinuousIntegrationTest) IotHubTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.IotHubTest) IntegrationTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.IntegrationTest) Test(org.junit.Test)

Example 32 with JobResult

use of com.microsoft.azure.sdk.iot.service.jobs.JobResult in project azure-iot-sdk-java by Azure.

the class JobClientTests method cancelScheduleDeviceMethodSucceed.

@Test(timeout = TEST_TIMEOUT_MILLISECONDS)
@ContinuousIntegrationTest
@Ignore
public void cancelScheduleDeviceMethodSucceed() throws InterruptedException {
    // Arrange
    ExecutorService executor = Executors.newFixedThreadPool(MAX_NUMBER_JOBS);
    DeviceTestManager deviceTestManger = devices.get(0);
    final String deviceId = testDevice.getDeviceId();
    final String queryCondition = "DeviceId IN ['" + deviceId + "']";
    // 3 minutes in the future.
    final Date future = new Date(new Date().getTime() + 180000L);
    final ConcurrentMap<String, Exception> jobExceptions = new ConcurrentHashMap<>();
    final ArrayList<String> jobIdsPending = new ArrayList<>();
    // Act
    for (int i = 0; i < MAX_NUMBER_JOBS; i++) {
        final int index = i;
        executor.submit(() -> {
            String jobId = JOB_ID_NAME + UUID.randomUUID();
            jobIdsPending.add(jobId);
            try {
                jobClient.scheduleDeviceMethod(jobId, queryCondition, DeviceEmulator.METHOD_LOOPBACK, RESPONSE_TIMEOUT, CONNECTION_TIMEOUT, PAYLOAD_STRING, (index % 2 == 0) ? future : new Date(), MAX_EXECUTION_TIME_IN_SECONDS);
                JobStatus expectedJobStatus = JobStatus.completed;
                if (index % 2 == 0) {
                    expectedJobStatus = JobStatus.cancelled;
                    // wait 1 seconds and cancel.
                    Thread.sleep(1000);
                    jobClient.cancelJob(jobId);
                }
                JobResult jobResult = jobClient.getJob(jobId);
                while (jobResult.getJobStatus() != expectedJobStatus) {
                    Thread.sleep(MAXIMUM_TIME_TO_WAIT_FOR_IOTHUB_MILLISECONDS);
                    jobResult = jobClient.getJob(jobId);
                }
                log.info("Iothub confirmed {} {} for type {}", jobId, expectedJobStatus, JobType.scheduleDeviceMethod);
            } catch (IotHubException | IOException | InterruptedException e) {
                jobExceptions.put(jobId, e);
            }
            jobIdsPending.remove(jobId);
        });
    }
    cleanupJobs(executor, jobIdsPending);
    // asserts for the service side.
    if (jobExceptions.size() != 0) {
        for (Map.Entry<String, Exception> jobException : jobExceptions.entrySet()) {
            log.error("{} threw", jobException.getKey(), jobException.getValue());
        }
        fail("Service throw an exception enqueuing jobs");
    }
    // asserts for the client side.
    assertEquals(0, deviceTestManger.getStatusError());
}
Also used : JobResult(com.microsoft.azure.sdk.iot.service.jobs.JobResult) ArrayList(java.util.ArrayList) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) IOException(java.io.IOException) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) IotHubException(com.microsoft.azure.sdk.iot.service.exceptions.IotHubException) IotHubUnathorizedException(com.microsoft.azure.sdk.iot.service.exceptions.IotHubUnathorizedException) JobStatus(com.microsoft.azure.sdk.iot.service.jobs.JobStatus) DeviceTestManager(tests.integration.com.microsoft.azure.sdk.iot.helpers.DeviceTestManager) ExecutorService(java.util.concurrent.ExecutorService) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) IotHubException(com.microsoft.azure.sdk.iot.service.exceptions.IotHubException) Ignore(org.junit.Ignore) ContinuousIntegrationTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.ContinuousIntegrationTest) IotHubTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.IotHubTest) IntegrationTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.IntegrationTest) Test(org.junit.Test) ContinuousIntegrationTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.ContinuousIntegrationTest)

Example 33 with JobResult

use of com.microsoft.azure.sdk.iot.service.jobs.JobResult in project azure-iot-sdk-java by Azure.

the class JobClientTests method queryJobResponseResult.

// Since this is a helper method, the params can be passed any value.
@SuppressWarnings("SameParameterValue")
private JobResult queryJobResponseResult(String jobId, JobType jobType, JobStatus jobStatus) throws IOException, IotHubException {
    Query query = jobClient.queryJobResponse(jobType, jobStatus);
    JobResult jobResult;
    while (jobClient.hasNextJob(query)) {
        jobResult = jobClient.getNextJob(query);
        if (jobResult.getJobId().equals(jobId) && (jobResult.getJobType() == jobType) && (jobResult.getJobStatus() == jobStatus)) {
            log.info("Iothub confirmed {} {} for type {}", jobId, jobStatus, jobType);
            return jobResult;
        }
    }
    throw new AssertionError("queryDeviceJob did not find the job");
}
Also used : SqlQuery(com.microsoft.azure.sdk.iot.service.devicetwin.SqlQuery) Query(com.microsoft.azure.sdk.iot.service.devicetwin.Query) JobResult(com.microsoft.azure.sdk.iot.service.jobs.JobResult)

Example 34 with JobResult

use of com.microsoft.azure.sdk.iot.service.jobs.JobResult in project azure-iot-sdk-java by Azure.

the class JobClientTests method queryDeviceJobResult.

// Since this is a helper method, the params can be passed any value.
@SuppressWarnings("SameParameterValue")
private static JobResult queryDeviceJobResult(String jobId, JobType jobType, JobStatus jobStatus) throws IOException, IotHubException {
    String queryContent = SqlQuery.createSqlQuery("*", SqlQuery.FromType.JOBS, "devices.jobs.jobId = '" + jobId + "' and devices.jobs.jobType = '" + jobType.toString() + "'", null).getQuery();
    Query query = jobClient.queryDeviceJob(queryContent);
    JobResult jobResult;
    while (jobClient.hasNextJob(query)) {
        jobResult = jobClient.getNextJob(query);
        if (jobResult.getJobId().equals(jobId)) {
            if (jobResult.getJobType() == jobType) {
                if (jobResult.getJobStatus() == jobStatus) {
                    // query confirmed that the specified job has the correct type, and status
                    return jobResult;
                } else {
                    throw new AssertionError("queryDeviceJob received job unexpected status. Expected " + jobStatus + " but job ended with status " + jobResult.getJobStatus());
                }
            } else {
                throw new AssertionError("queryDeviceJob received job with the wrong job type. Expected " + jobType + " but found " + jobResult.getJobType());
            }
        }
    }
    throw new AssertionError("queryDeviceJob did not find the job");
}
Also used : SqlQuery(com.microsoft.azure.sdk.iot.service.devicetwin.SqlQuery) Query(com.microsoft.azure.sdk.iot.service.devicetwin.Query) JobResult(com.microsoft.azure.sdk.iot.service.jobs.JobResult) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString)

Example 35 with JobResult

use of com.microsoft.azure.sdk.iot.service.jobs.JobResult in project azure-iot-sdk-java by Azure.

the class AzureSasCredentialSample method runJobClientSample.

private static void runJobClientSample(String iotHubHostName, AzureSasCredential credential) {
    // JobClient has some configurable options for HTTP read and connect timeouts, as well as for setting proxies.
    // For this sample, the default options will be used though.
    JobClientOptions options = JobClientOptions.builder().build();
    // This constructor takes in your implementation of AzureSasCredential which allows you to use symmetric key based
    // authentication without giving the client your connection string.
    JobClient jobClient = new JobClient(iotHubHostName, credential, options);
    try {
        System.out.println("Querying all active jobs for your IoT Hub");
        Query deviceJobQuery = jobClient.queryDeviceJob(SqlQuery.createSqlQuery("*", SqlQuery.FromType.JOBS, null, null).getQuery());
        int queriedJobCount = 0;
        while (jobClient.hasNextJob(deviceJobQuery)) {
            queriedJobCount++;
            JobResult job = jobClient.getNextJob(deviceJobQuery);
            System.out.println(String.format("Job %s of type %s has status %s", job.getJobId(), job.getJobType(), job.getJobStatus()));
        }
        if (queriedJobCount == 0) {
            System.out.println("No active jobs found for your IoT Hub");
        }
    } catch (IotHubException | IOException e) {
        System.err.println("Failed to query the jobs for your IoT Hub");
        e.printStackTrace();
        System.exit(-1);
    }
}
Also used : JobClientOptions(com.microsoft.azure.sdk.iot.service.jobs.JobClientOptions) SqlQuery(com.microsoft.azure.sdk.iot.service.devicetwin.SqlQuery) Query(com.microsoft.azure.sdk.iot.service.devicetwin.Query) JobResult(com.microsoft.azure.sdk.iot.service.jobs.JobResult) IOException(java.io.IOException) JobClient(com.microsoft.azure.sdk.iot.service.jobs.JobClient) IotHubException(com.microsoft.azure.sdk.iot.service.exceptions.IotHubException)

Aggregations

JobResult (com.microsoft.azure.sdk.iot.service.jobs.JobResult)40 Test (org.junit.Test)27 Date (java.util.Date)25 IotHubConnectionString (com.microsoft.azure.sdk.iot.service.IotHubConnectionString)17 JobClient (com.microsoft.azure.sdk.iot.service.jobs.JobClient)14 TwinState (com.microsoft.azure.sdk.iot.deps.twin.TwinState)13 HashSet (java.util.HashSet)11 NonStrictExpectations (mockit.NonStrictExpectations)11 JobsParser (com.microsoft.azure.sdk.iot.deps.serializer.JobsParser)9 TwinCollection (com.microsoft.azure.sdk.iot.deps.twin.TwinCollection)9 DeviceTwinDevice (com.microsoft.azure.sdk.iot.service.devicetwin.DeviceTwinDevice)9 Pair (com.microsoft.azure.sdk.iot.service.devicetwin.Pair)9 IOException (java.io.IOException)8 Expectations (mockit.Expectations)8 IotHubException (com.microsoft.azure.sdk.iot.service.exceptions.IotHubException)6 MethodParser (com.microsoft.azure.sdk.iot.deps.serializer.MethodParser)5 DeviceTestManager (tests.integration.com.microsoft.azure.sdk.iot.helpers.DeviceTestManager)5 Job (com.microsoft.azure.sdk.iot.service.devicetwin.Job)4 MethodResult (com.microsoft.azure.sdk.iot.service.devicetwin.MethodResult)4 Query (com.microsoft.azure.sdk.iot.service.devicetwin.Query)4