Search in sources :

Example 16 with JobResult

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

the class JobClientTests method mixScheduleInFutureSucceed.

@Test(timeout = TEST_TIMEOUT_MILLISECONDS)
@ContinuousIntegrationTest
@Ignore
public void mixScheduleInFutureSucceed() 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 + "']";
    // 10 seconds in the future.
    final Date future = new Date(new Date().getTime() + 10000L);
    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 index = i;
        final int jobTemperature = (newTemperature++);
        executor.submit(() -> {
            String jobId = JOB_ID_NAME + UUID.randomUUID();
            jobIdsPending.add(jobId);
            try {
                if (index % 2 == 0) {
                    jobClient.scheduleDeviceMethod(jobId, queryCondition, DeviceEmulator.METHOD_LOOPBACK, RESPONSE_TIMEOUT, CONNECTION_TIMEOUT, PAYLOAD_STRING, future, MAX_EXECUTION_TIME_IN_SECONDS);
                } else {
                    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 = queryDeviceJobResult(jobId, ((index % 2 == 0) ? JobType.scheduleDeviceMethod : JobType.scheduleUpdateTwin), JobStatus.completed);
                jobResults.put(jobId, jobResult);
            } catch (IotHubException | IOException | InterruptedException e) {
                jobExceptions.put(jobId, e);
            }
            jobIdsPending.remove(jobId);
        });
    }
    cleanupJobs(executor, jobIdsPending);
    // wait until identity receive the twin change
    ConcurrentMap<String, ConcurrentLinkedQueue<Object>> changes = deviceTestManger.getTwinChanges();
    int timeout = 0;
    while (changes.size() == 0) {
        if ((timeout += MAXIMUM_TIME_TO_WAIT_FOR_IOTHUB_MILLISECONDS) >= TEST_TIMEOUT_MILLISECONDS) {
            fail("Device didn't receive the twin change");
        }
        Thread.sleep(MAXIMUM_TIME_TO_WAIT_FOR_IOTHUB_MILLISECONDS);
        changes = deviceTestManger.getTwinChanges();
    }
    // 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());
    ConcurrentLinkedQueue<Object> temperatures = changes.get(STANDARD_PROPERTY_HOMETEMP);
    assertNotNull("There is no " + STANDARD_PROPERTY_HOMETEMP + " in the device changes", temperatures);
    for (Map.Entry<String, JobResult> job : jobResults.entrySet()) {
        JobResult jobResult = job.getValue();
        String jobId = jobResult.getJobId();
        assertNotNull(jobResult);
        if (jobResult.getJobType() == JobType.scheduleDeviceMethod) {
            MethodResult methodResult = jobResult.getOutcomeResult();
            assertNotNull("Device method didn't return any outcome", methodResult);
            assertEquals(200L, (long) methodResult.getStatus());
            assertEquals(DeviceEmulator.METHOD_LOOPBACK + ":" + PAYLOAD_STRING, methodResult.getPayload());
        } else {
            String temperature = twinExpectedTemperature.get(jobId) + ".0";
            assertTrue("Device do not change " + STANDARD_PROPERTY_HOMETEMP + " to " + temperature, temperatures.contains(temperature));
        }
    }
    // asserts for the client side.
    assertEquals(0, deviceTestManger.getStatusError());
}
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) 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) 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) MethodResult(com.microsoft.azure.sdk.iot.service.devicetwin.MethodResult) 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 17 with JobResult

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

the class JobTest method getInvokeJobClient.

/* Tests_SRS_JOB_21_018: [The get shall invoke getJob on JobClient with the current jobId and return its result.] */
@Test
public void getInvokeJobClient() throws IOException, IotHubException {
    // arrange
    final String connectionString = "validConnectionString";
    // assert
    new NonStrictExpectations() {

        {
            JobClient.createFromConnectionString(connectionString);
            result = mockedJobClient;
            mockedJobClient.getJob((String) any);
            result = mockedJobResult;
            times = 1;
        }
    };
    Job job = Deencapsulation.newInstance(Job.class, new Class[] { String.class }, connectionString);
    // act
    JobResult jobResult = job.get();
    // assert
    assertNotNull(jobResult);
}
Also used : JobResult(com.microsoft.azure.sdk.iot.service.jobs.JobResult) Job(com.microsoft.azure.sdk.iot.service.devicetwin.Job) Test(org.junit.Test)

Example 18 with JobResult

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

the class JobTest method cancelInvokeJobClient.

/* Tests_SRS_JOB_21_020: [The cancel shall invoke cancelJob on JobClient with the current jobId and return its result.] */
@Test
public void cancelInvokeJobClient() throws IOException, IotHubException {
    // arrange
    final String connectionString = "validConnectionString";
    // assert
    new NonStrictExpectations() {

        {
            JobClient.createFromConnectionString(connectionString);
            result = mockedJobClient;
            mockedJobClient.cancelJob((String) any);
            result = mockedJobResult;
            times = 1;
        }
    };
    Job job = Deencapsulation.newInstance(Job.class, new Class[] { String.class }, connectionString);
    // act
    JobResult jobResult = job.cancel();
    // assert
    assertNotNull(jobResult);
}
Also used : JobResult(com.microsoft.azure.sdk.iot.service.jobs.JobResult) Job(com.microsoft.azure.sdk.iot.service.devicetwin.Job) Test(org.junit.Test)

Example 19 with JobResult

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

the class JobResultTest method toStringReturnJobTypeUnknown.

/* Tests_SRS_JOBRESULT_21_020: [The toString shall return a String with a pretty print json that represents this class.] */
@Test
public void toStringReturnJobTypeUnknown() throws IOException {
    // arrange
    final String json = "validJson";
    final Date now = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT_JSON);
    String nowString = dateFormat.format(now);
    final String expectedPrettyPrint = "{\n" + "  \"jobId\": \"validJobId\",\n" + "  \"queryCondition\": \"DeviceId IN ['validDevice']\",\n" + "  \"createdTime\": \"" + nowString + "\",\n" + "  \"startTime\": \"" + nowString + "\",\n" + "  \"lastUpdatedDateTime\": \"" + nowString + "\",\n" + "  \"endTime\": \"" + nowString + "\",\n" + "  \"maxExecutionTimeInSeconds\": 100,\n" + "  \"jobType\": \"unknown\",\n" + "  \"jobStatus\": \"enqueued\",\n" + "  \"updateTwin\": {\n" + "    \"deviceId\": \"validDeviceId\",\n" + "    \"eTag\": \"validETag\",\n" + "    \"tag\": {\n" + "      \"tag1\": \"val1\"\n" + "    },\n" + "    \"desiredProperties\": {\n" + "      \"key1\": \"val1\"\n" + "    },\n" + "    \"parentScopes\": []\n" + "  },\n" + "  \"failureReason\": \"This is a valid failure reason\",\n" + "  \"statusMessage\": \"This is a valid status message\",\n" + "  \"jobStatistics\": {\n" + "    \"deviceCount\": 0,\n" + "    \"failedCount\": 0,\n" + "    \"succeededCount\": 0,\n" + "    \"runningCount\": 0,\n" + "    \"pendingCount\": 0\n" + "  },\n" + "  \"deviceId\": \"validDeviceId\",\n" + "  \"parentJobId\": \"validParentJobId\"\n" + "}";
    TwinCollection tags = new TwinCollection();
    tags.putFinal("tag1", "val1");
    TwinCollection desired = new TwinCollection();
    desired.putFinal("key1", "val1");
    TwinState twinState = new TwinState(tags, desired, null);
    twinState.setDeviceId(DEVICE_ID);
    twinState.setETag(ETAG);
    JobsResponseParserExpectations(json, twinState, null, now, null, "unknown");
    JobResult jobResult = Deencapsulation.newInstance(JobResult.class, new Class[] { byte[].class }, json.getBytes(StandardCharsets.UTF_8));
    // act
    String prettyPrint = jobResult.toString();
    // assert
    assertThat(prettyPrint, is(expectedPrettyPrint));
}
Also used : TwinCollection(com.microsoft.azure.sdk.iot.deps.twin.TwinCollection) TwinState(com.microsoft.azure.sdk.iot.deps.twin.TwinState) JobResult(com.microsoft.azure.sdk.iot.service.jobs.JobResult) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) Test(org.junit.Test)

Example 20 with JobResult

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

the class JobResultTest method gettersTwinContent.

/* Tests_SRS_JOBRESULT_21_005: [The getJobId shall return the stored jobId.] */
/* Tests_SRS_JOBRESULT_21_006: [The getQueryCondition shall return the stored queryCondition.] */
/* Tests_SRS_JOBRESULT_21_007: [The getCreatedTime shall return the stored createdTime.] */
/* Tests_SRS_JOBRESULT_21_008: [The getStartTime shall return the stored startTime.] */
/* Tests_SRS_JOBRESULT_21_009: [The getEndTime shall return the stored endTime.] */
/* Tests_SRS_JOBRESULT_21_010: [The getMaxExecutionTimeInSeconds shall return the stored maxExecutionTimeInSeconds.] */
/* Tests_SRS_JOBRESULT_21_011: [The getType shall return the stored jobType.] */
/* Tests_SRS_JOBRESULT_21_012: [The getJobStatus shall return the stored jobStatus.] */
/* Tests_SRS_JOBRESULT_21_014: [The getUpdateTwin shall return the stored updateTwin.] */
/* Tests_SRS_JOBRESULT_21_015: [The getFailureReason shall return the stored failureReason.] */
/* Tests_SRS_JOBRESULT_21_016: [The getStatusMessage shall return the stored statusMessage.] */
/* Tests_SRS_JOBRESULT_21_017: [The getJobStatistics shall return the stored jobStatistics.] */
/* Tests_SRS_JOBRESULT_21_018: [The getDeviceId shall return the stored deviceId.] */
/* Tests_SRS_JOBRESULT_21_019: [The getParentJobId shall return the stored parentJobId.] */
@Test
public void gettersTwinContent() throws IOException {
    // arrange
    final String json = "validJson";
    final Date now = new Date();
    TwinCollection tags = new TwinCollection();
    tags.putFinal("tag1", "val1");
    TwinState twinState = new TwinState(tags, null, null);
    twinState.setDeviceId(DEVICE_ID);
    twinState.setETag(ETAG);
    JobsResponseParserExpectations(json, twinState, null, now, null, "scheduleUpdateTwin");
    // act
    JobResult jobResult = Deencapsulation.newInstance(JobResult.class, new Class[] { byte[].class }, json.getBytes(StandardCharsets.UTF_8));
    // assert
    assertEquals(JOB_ID, jobResult.getJobId());
    assertEquals(QUERY_CONDITION, jobResult.getQueryCondition());
    assertEquals(now, jobResult.getCreatedTime());
    assertEquals(now, jobResult.getStartTime());
    assertEquals(now, jobResult.getEndTime());
    assertEquals(MAX_EXECUTION_TIME_IN_SECONDS, (long) jobResult.getMaxExecutionTimeInSeconds());
    assertEquals(JobType.scheduleUpdateTwin, jobResult.getJobType());
    assertEquals(JobStatus.enqueued, jobResult.getJobStatus());
    assertNull(jobResult.getCloudToDeviceMethod());
    assertNotNull(jobResult.getUpdateTwin());
    assertEquals(FAILURE_REASON, jobResult.getFailureReason());
    assertEquals(STATUS_MESSAGE, jobResult.getStatusMessage());
    assertNotNull(jobResult.getJobStatistics());
    assertEquals(DEVICE_ID, jobResult.getDeviceId());
    assertEquals(PARENT_JOB_ID, jobResult.getParentJobId());
}
Also used : TwinCollection(com.microsoft.azure.sdk.iot.deps.twin.TwinCollection) TwinState(com.microsoft.azure.sdk.iot.deps.twin.TwinState) JobResult(com.microsoft.azure.sdk.iot.service.jobs.JobResult) Date(java.util.Date) Test(org.junit.Test)

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