text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.engine.rest;

import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.core.Response.Status;

import org.camunda.bpm.engine.AuthorizationException;
import org.camunda.bpm.engine.BadUserRequestException;
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.batch.Batch;
import org.camunda.bpm.engine.exception.NotFoundException;
import org.camunda.bpm.engine.exception.NullValueException;
import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery;
import org.camunda.bpm.engine.management.UpdateJobSuspensionStateSelectBuilder;
import org.camunda.bpm.engine.management.UpdateJobSuspensionStateTenantBuilder;
import org.camunda.bpm.engine.rest.dto.batch.BatchDto;
import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto;
import org.camunda.bpm.engine.rest.dto.runtime.JobQueryDto;
import org.camunda.bpm.engine.rest.dto.runtime.JobSuspensionStateDto;
import org.camunda.bpm.engine.rest.exception.InvalidRequestException;
import org.camunda.bpm.engine.rest.exception.RestException;
import org.camunda.bpm.engine.rest.helper.MockJobBuilder;
import org.camunda.bpm.engine.rest.helper.MockProvider;
import org.camunda.bpm.engine.rest.util.JsonPathUtil;
import org.camunda.bpm.engine.rest.util.container.TestContainerRule;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.runtime.JobQuery;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.mockito.InOrder;

import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;
import org.mockito.Mockito;

public class JobRestServiceInteractionTest extends AbstractRestServiceTest {

  private static final String RETRIES = "retries";
  @ClassRule
  public static TestContainerRule rule = new TestContainerRule();

  protected static final String JOB_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/job";
  protected static final String SINGLE_JOB_RESOURCE_URL = JOB_RESOURCE_URL + "/{id}";
  protected static final String JOB_RESOURCE_SET_RETRIES_URL = SINGLE_JOB_RESOURCE_URL + "/retries";
  protected static final String JOBS_SET_RETRIES_URL = JOB_RESOURCE_URL + "/retries";
  protected static final String JOB_RESOURCE_SET_PRIORITY_URL = SINGLE_JOB_RESOURCE_URL + "/priority";
  protected static final String JOB_RESOURCE_EXECUTE_JOB_URL = SINGLE_JOB_RESOURCE_URL + "/execute";
  protected static final String JOB_RESOURCE_GET_STACKTRACE_URL = SINGLE_JOB_RESOURCE_URL + "/stacktrace";
  protected static final String JOB_RESOURCE_SET_DUEDATE_URL = SINGLE_JOB_RESOURCE_URL + "/duedate";
  protected static final String SINGLE_JOB_SUSPENDED_URL = SINGLE_JOB_RESOURCE_URL + "/suspended";
  protected static final String JOB_SUSPENDED_URL = JOB_RESOURCE_URL + "/suspended";

  private ProcessEngine namedProcessEngine;
  private ManagementService mockManagementService;

  private UpdateJobSuspensionStateTenantBuilder mockSuspensionStateBuilder;
  private UpdateJobSuspensionStateSelectBuilder mockSuspensionStateSelectBuilder;

  private JobQuery mockQuery;

  @Before
  public void setUpRuntimeData() {

    mockQuery = mock(JobQuery.class);
    Job mockedJob = new MockJobBuilder()
      .id(MockProvider.EXAMPLE_JOB_ID)
      .processInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)
      .executionId(MockProvider.EXAMPLE_EXECUTION_ID)
      .retries(MockProvider.EXAMPLE_JOB_RETRIES)
      .exceptionMessage(MockProvider.EXAMPLE_JOB_NO_EXCEPTION_MESSAGE)
      .dueDate(new Date())
      .priority(MockProvider.EXAMPLE_JOB_PRIORITY)
      .jobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID)
      .tenantId(MockProvider.EXAMPLE_TENANT_ID)
      .build();

    when(mockQuery.singleResult()).thenReturn(mockedJob);
    when(mockQuery.jobId(MockProvider.EXAMPLE_JOB_ID)).thenReturn(mockQuery);

    mockManagementService = mock(ManagementService.class);
    when(mockManagementService.createJobQuery()).thenReturn(mockQuery);

    mockSuspensionStateSelectBuilder = mock(UpdateJobSuspensionStateSelectBuilder.class);
    when(mockManagementService.updateJobSuspensionState()).thenReturn(mockSuspensionStateSelectBuilder);

    mockSuspensionStateBuilder = mock(UpdateJobSuspensionStateTenantBuilder.class);
    when(mockSuspensionStateSelectBuilder.byJobId(anyString())).thenReturn(mockSuspensionStateBuilder);
    when(mockSuspensionStateSelectBuilder.byJobDefinitionId(anyString())).thenReturn(mockSuspensionStateBuilder);
    when(mockSuspensionStateSelectBuilder.byProcessInstanceId(anyString())).thenReturn(mockSuspensionStateBuilder);
    when(mockSuspensionStateSelectBuilder.byProcessDefinitionId(anyString())).thenReturn(mockSuspensionStateBuilder);
    when(mockSuspensionStateSelectBuilder.byProcessDefinitionKey(anyString())).thenReturn(mockSuspensionStateBuilder);

    namedProcessEngine = getProcessEngine(MockProvider.EXAMPLE_PROCESS_ENGINE_NAME);
    when(namedProcessEngine.getManagementService()).thenReturn(mockManagementService);
  }

  @Test
  public void testSetJobRetries() {
    Map<String, Object> retriesVariableJson = new HashMap<String, Object>();
    retriesVariableJson.put("retries", MockProvider.EXAMPLE_JOB_RETRIES);

    given().pathParam("id", MockProvider.EXAMPLE_JOB_ID).contentType(ContentType.JSON).body(retriesVariableJson).then().expect()
    .statusCode(Status.NO_CONTENT.getStatusCode())
    .when().put(JOB_RESOURCE_SET_RETRIES_URL);

    verify(mockManagementService).setJobRetries(MockProvider.EXAMPLE_JOB_ID, MockProvider.EXAMPLE_JOB_RETRIES);
  }

  @Test
  public void testSetJobRetriesNonExistentJob() {
    String expectedMessage = "No job found with id '" + MockProvider.NON_EXISTING_JOB_ID + "'.";

    doThrow(new ProcessEngineException(expectedMessage)).when(mockManagementService).setJobRetries(MockProvider.NON_EXISTING_JOB_ID,
        MockProvider.EXAMPLE_JOB_RETRIES);

    Map<String, Object> retriesVariableJson = new HashMap<String, Object>();
    retriesVariableJson.put("retries", MockProvider.EXAMPLE_JOB_RETRIES);

    given().pathParam("id", MockProvider.NON_EXISTING_JOB_ID).contentType(ContentType.JSON)
    .body(retriesVariableJson).then().expect()
    .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
    .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
    .body("message", equalTo(expectedMessage))
    .when().put(JOB_RESOURCE_SET_RETRIES_URL);

    verify(mockManagementService).setJobRetries(MockProvider.NON_EXISTING_JOB_ID, MockProvider.EXAMPLE_JOB_RETRIES);
  }

  @Test
  public void testSetJobRetriesNegativeRetries() {

    String expectedMessage = "The number of job retries must be a non-negative Integer, but '" + MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES
        + "' has been provided.";

    doThrow(new ProcessEngineException(expectedMessage)).when(mockManagementService).setJobRetries(MockProvider.EXAMPLE_JOB_ID,
        MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES);

    Map<String, Object> retriesVariableJson = new HashMap<String, Object>();
    retriesVariableJson.put("retries", MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES);

    given().pathParam("id", MockProvider.EXAMPLE_JOB_ID).contentType(ContentType.JSON).body(retriesVariableJson).then().then().expect()
    .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
    .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
    .body("message", equalTo(expectedMessage))
    .when().put(JOB_RESOURCE_SET_RETRIES_URL);

    verify(mockManagementService).setJobRetries(MockProvider.EXAMPLE_JOB_ID, MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES);
  }

  @Test
  public void testSetJobRetriesThrowsAuthorizationException() {
    String message = "expected exception";
    doThrow(new AuthorizationException(message)).when(mockManagementService).setJobRetries(anyString(), anyInt());

    Map<String, Object> retriesVariableJson = new HashMap<String, Object>();
    retriesVariableJson.put("retries", MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES);

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
      .contentType(ContentType.JSON).body(retriesVariableJson)
    .then().expect()
      .statusCode(Status.FORBIDDEN.getStatusCode())
      .body("type", equalTo(AuthorizationException.class.getSimpleName()))
      .body("message", equalTo(message))
    .when()
      .put(JOB_RESOURCE_SET_RETRIES_URL);
  }

  @Test
  public void testSimpleJobGet() {
    given().pathParam("id", MockProvider.EXAMPLE_JOB_ID).then().expect().statusCode(Status.OK.getStatusCode())
      .body("id", equalTo(MockProvider.EXAMPLE_JOB_ID))
      .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID))
      .body("executionId", equalTo(MockProvider.EXAMPLE_EXECUTION_ID))
      .body("exceptionMessage", equalTo(MockProvider.EXAMPLE_JOB_NO_EXCEPTION_MESSAGE))
      .body("priority", equalTo(MockProvider.EXAMPLE_JOB_PRIORITY))
      .body("jobDefinitionId", equalTo(MockProvider.EXAMPLE_JOB_DEFINITION_ID))
      .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID))
    .when().get(SINGLE_JOB_RESOURCE_URL);

    InOrder inOrder = inOrder(mockQuery);
    inOrder.verify(mockQuery).jobId(MockProvider.EXAMPLE_JOB_ID);
    inOrder.verify(mockQuery).singleResult();
  }

  @Test
  public void testJobGetIdDoesntExist() {
    JobQuery invalidQueryNonExistingJob;
    invalidQueryNonExistingJob = mock(JobQuery.class);
    when(mockManagementService.createJobQuery().jobId(MockProvider.NON_EXISTING_JOB_ID)).thenReturn(invalidQueryNonExistingJob);
    when(invalidQueryNonExistingJob.singleResult()).thenReturn(null);

    String jobId = MockProvider.NON_EXISTING_JOB_ID;

    given().pathParam("id", jobId).then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON)
    .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
    .body("message", equalTo("Job with id " + jobId + " does not exist")).when()
    .get(SINGLE_JOB_RESOURCE_URL);
  }

  @Test
  public void testExecuteJob() {
    given().pathParam("id", MockProvider.EXAMPLE_JOB_ID)
    .then().expect().statusCode(Status.NO_CONTENT.getStatusCode())
    .when().post(JOB_RESOURCE_EXECUTE_JOB_URL);

    verify(mockManagementService).executeJob(MockProvider.EXAMPLE_JOB_ID);
  }

  @Test
  public void testExecuteJobIdDoesntExist() {
    String jobId = MockProvider.NON_EXISTING_JOB_ID;

    String expectedMessage = "No job found with id '" + jobId + "'";

    doThrow(new ProcessEngineException(expectedMessage)).when(mockManagementService).executeJob(MockProvider.NON_EXISTING_JOB_ID);

    given().pathParam("id", jobId)
    .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON)
    .body("type", equalTo(InvalidRequestException.class.getSimpleName())).body("message", equalTo(expectedMessage))
    .when().post(JOB_RESOURCE_EXECUTE_JOB_URL);
  }

  @Test
  public void testExecuteJobRuntimeException() {
    String jobId = MockProvider.EXAMPLE_JOB_ID;

    doThrow(new RuntimeException("Runtime exception")).when(mockManagementService).executeJob(jobId);

    given().pathParam("id", jobId)
    .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON)
    .body("type", equalTo(RestException.class.getSimpleName())).body("message", equalTo("Runtime exception"))
    .when().post(JOB_RESOURCE_EXECUTE_JOB_URL);
  }

  @Test
  public void testExecuteJobThrowsAuthorizationException() {
    String message = "expected exception";
    doThrow(new AuthorizationException(message)).when(mockManagementService).executeJob(anyString());

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
    .then().expect()
      .statusCode(Status.FORBIDDEN.getStatusCode())
      .body("type", equalTo(AuthorizationException.class.getSimpleName()))
      .body("message", equalTo(message))
    .when()
      .post(JOB_RESOURCE_EXECUTE_JOB_URL);
  }

  @Test
  public void testGetStacktrace() {
    String stacktrace = "aStacktrace";
    when(mockManagementService.getJobExceptionStacktrace(MockProvider.EXAMPLE_JOB_ID)).thenReturn(stacktrace);

    Response response = given().pathParam("id", MockProvider.EXAMPLE_JOB_ID)
    .then().expect().statusCode(Status.OK.getStatusCode()).contentType(ContentType.TEXT)
    .when().get(JOB_RESOURCE_GET_STACKTRACE_URL);

    String content = response.asString();
    Assert.assertEquals(stacktrace, content);
  }

  @Test
  public void testGetStacktraceJobNotFound() {
    String exceptionMessage = "job not found";
    doThrow(new ProcessEngineException(exceptionMessage)).when(mockManagementService).getJobExceptionStacktrace(MockProvider.EXAMPLE_JOB_ID);

    given().pathParam("id", MockProvider.EXAMPLE_JOB_ID)
    .then().expect().statusCode(Status.NOT_FOUND.getStatusCode())
    .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
    .body("message", equalTo(exceptionMessage))
    .when().get(JOB_RESOURCE_GET_STACKTRACE_URL);
  }

  @Test
  public void testGetStacktraceJobThrowsAuthorizationException() {
    String message = "expected exception";
    doThrow(new AuthorizationException(message)).when(mockManagementService).getJobExceptionStacktrace(MockProvider.EXAMPLE_JOB_ID);

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
    .then().expect()
      .statusCode(Status.FORBIDDEN.getStatusCode())
      .body("type", equalTo(AuthorizationException.class.getSimpleName()))
      .body("message", equalTo(message))
    .when()
      .get(JOB_RESOURCE_GET_STACKTRACE_URL);
  }

  @Test
  public void testSetJobDuedate() {
    Date newDuedate = MockProvider.createMockDuedate();
    Map<String, Object> duedateVariableJson = new HashMap<String, Object>();
    duedateVariableJson.put("duedate", newDuedate);

    given().pathParam("id", MockProvider.EXAMPLE_JOB_ID).contentType(ContentType.JSON).body(duedateVariableJson).then().expect()
    .statusCode(Status.NO_CONTENT.getStatusCode())
    .when().put(JOB_RESOURCE_SET_DUEDATE_URL);

    verify(mockManagementService).setJobDuedate(MockProvider.EXAMPLE_JOB_ID, newDuedate);

  }

  @Test
  public void testSetJobDuedateNull() {
    Map<String, Object> duedateVariableJson = new HashMap<String, Object>();
    duedateVariableJson.put("duedate", null);

    given().pathParam("id", MockProvider.EXAMPLE_JOB_ID).contentType(ContentType.JSON).body(duedateVariableJson).then().expect()
    .statusCode(Status.NO_CONTENT.getStatusCode())
    .when().put(JOB_RESOURCE_SET_DUEDATE_URL);

    verify(mockManagementService).setJobDuedate(MockProvider.EXAMPLE_JOB_ID, null);

  }

  @Test
  public void testSetJobDuedateNonExistentJob() {
    Date newDuedate = MockProvider.createMockDuedate();
    String expectedMessage = "No job found with id '" + MockProvider.NON_EXISTING_JOB_ID + "'.";

    doThrow(new ProcessEngineException(expectedMessage)).when(mockManagementService).setJobDuedate(MockProvider.NON_EXISTING_JOB_ID,
        newDuedate);

    Map<String, Object> duedateVariableJson = new HashMap<String, Object>();
    duedateVariableJson.put("duedate", newDuedate);

    given().pathParam("id", MockProvider.NON_EXISTING_JOB_ID).contentType(ContentType.JSON)
    .body(duedateVariableJson).then().expect()
    .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
    .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
    .body("message", equalTo(expectedMessage))
    .when().put(JOB_RESOURCE_SET_DUEDATE_URL);

    verify(mockManagementService).setJobDuedate(MockProvider.NON_EXISTING_JOB_ID, newDuedate);
  }

  @Test
  public void testSetJobDuedateThrowsAuthorizationException() {
    String message = "expected exception";
    doThrow(new AuthorizationException(message)).when(mockManagementService).setJobDuedate(anyString(), any(Date.class));

    Date newDuedate = MockProvider.createMockDuedate();
    Map<String, Object> duedateVariableJson = new HashMap<String, Object>();
    duedateVariableJson.put("duedate", newDuedate);

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
      .contentType(ContentType.JSON)
      .body(duedateVariableJson)
    .then().expect()
      .statusCode(Status.FORBIDDEN.getStatusCode())
      .body("type", equalTo(AuthorizationException.class.getSimpleName()))
      .body("message", equalTo(message))
    .when()
      .put(JOB_RESOURCE_SET_DUEDATE_URL);
  }

  @Test
  public void testActivateJob() {
    JobSuspensionStateDto dto = new JobSuspensionStateDto();
    dto.setSuspended(false);

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
      .contentType(ContentType.JSON)
      .body(dto)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(SINGLE_JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byJobId(MockProvider.EXAMPLE_JOB_ID);
    verify(mockSuspensionStateBuilder).activate();
  }

  @Test
  public void testActivateThrowsProcessEngineException() {
    JobSuspensionStateDto dto = new JobSuspensionStateDto();
    dto.setSuspended(false);

    String expectedMessage = "expectedMessage";

    doThrow(new ProcessEngineException(expectedMessage))
      .when(mockSuspensionStateBuilder)
      .activate();

    given()
      .pathParam("id", MockProvider.NON_EXISTING_JOB_ID)
      .contentType(ContentType.JSON)
      .body(dto)
    .then()
      .expect()
        .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
        .body("type", is(ProcessEngineException.class.getSimpleName()))
        .body("message", is(expectedMessage))
      .when()
        .put(SINGLE_JOB_SUSPENDED_URL);
  }

  @Test
  public void testActivateThrowsAuthorizationException() {
    JobSuspensionStateDto dto = new JobSuspensionStateDto();
    dto.setSuspended(false);

    String expectedMessage = "expectedMessage";

    doThrow(new AuthorizationException(expectedMessage))
      .when(mockSuspensionStateBuilder)
      .activate();

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
      .contentType(ContentType.JSON)
      .body(dto)
    .then()
      .expect()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .body("type", is(AuthorizationException.class.getSimpleName()))
        .body("message", is(expectedMessage))
      .when()
        .put(SINGLE_JOB_SUSPENDED_URL);
  }

  @Test
  public void testSuspendJob() {
    JobSuspensionStateDto dto = new JobSuspensionStateDto();
    dto.setSuspended(true);

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
      .contentType(ContentType.JSON)
      .body(dto)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(SINGLE_JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byJobId(MockProvider.EXAMPLE_JOB_ID);
    verify(mockSuspensionStateBuilder).suspend();
  }

  @Test
  public void testSuspendedThrowsProcessEngineException() {
    JobSuspensionStateDto dto = new JobSuspensionStateDto();
    dto.setSuspended(true);

    String expectedMessage = "expectedMessage";

    doThrow(new ProcessEngineException(expectedMessage))
      .when(mockSuspensionStateBuilder)
      .suspend();

    given()
      .pathParam("id", MockProvider.NON_EXISTING_JOB_ID)
      .contentType(ContentType.JSON)
      .body(dto)
    .then()
      .expect()
        .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
        .body("type", is(ProcessEngineException.class.getSimpleName()))
        .body("message", is(expectedMessage))
      .when()
        .put(SINGLE_JOB_SUSPENDED_URL);
  }

  @Test
  public void testSuspendWithMultipleByParameters() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID);
    params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
    params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
    params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);

    String message = "Only one of jobId, jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey should be set to update the suspension state.";

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.BAD_REQUEST.getStatusCode())
        .body("type", is(InvalidRequestException.class.getSimpleName()))
        .body("message", is(message))
      .when()
        .put(SINGLE_JOB_SUSPENDED_URL);
  }

  @Test
  public void testSuspendThrowsAuthorizationException() {
    JobSuspensionStateDto dto = new JobSuspensionStateDto();
    dto.setSuspended(true);

    String expectedMessage = "expectedMessage";

    doThrow(new AuthorizationException(expectedMessage))
      .when(mockSuspensionStateBuilder)
      .suspend();

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
      .contentType(ContentType.JSON)
      .body(dto)
    .then()
      .expect()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .body("type", is(AuthorizationException.class.getSimpleName()))
        .body("message", is(expectedMessage))
      .when()
        .put(SINGLE_JOB_SUSPENDED_URL);
  }

  @Test
  public void testActivateJobByProcessDefinitionKey() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
    verify(mockSuspensionStateBuilder).activate();
  }

  @Test
  public void testActivateJobByProcessDefinitionKeyWithException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);

    String expectedException = "expectedException";
    doThrow(new ProcessEngineException(expectedException))
      .when(mockSuspensionStateBuilder)
      .activate();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
        .body("type", is(ProcessEngineException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testActivateJobByProcessDefinitionKeyThrowsAuthorizationException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);

    String expectedException = "expectedException";
    doThrow(new AuthorizationException(expectedException))
      .when(mockSuspensionStateBuilder)
      .activate();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .body("type", is(AuthorizationException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testSuspendJobByProcessDefinitionKey() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
    verify(mockSuspensionStateBuilder).suspend();
  }

  @Test
  public void testSuspendJobByProcessDefinitionKeyWithException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);

    String expectedException = "expectedException";
    doThrow(new ProcessEngineException(expectedException))
      .when(mockSuspensionStateBuilder)
      .suspend();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
        .body("type", is(ProcessEngineException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testSuspendJobByProcessDefinitionKeyThrowsAuthorizationException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);

    String expectedException = "expectedException";
    doThrow(new AuthorizationException(expectedException))
      .when(mockSuspensionStateBuilder)
      .suspend();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .body("type", is(AuthorizationException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testActivateJobByProcessDefinitionKeyAndTenantId() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
    params.put("processDefinitionTenantId", MockProvider.EXAMPLE_TENANT_ID);

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
    verify(mockSuspensionStateBuilder).processDefinitionTenantId(MockProvider.EXAMPLE_TENANT_ID);
    verify(mockSuspensionStateBuilder).activate();
  }

  @Test
  public void testActivateJobByProcessDefinitionKeyWithoutTenantId() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
    params.put("processDefinitionWithoutTenantId", true);

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
    verify(mockSuspensionStateBuilder).processDefinitionWithoutTenantId();
    verify(mockSuspensionStateBuilder).activate();
  }

  @Test
  public void testSuspendJobByProcessDefinitionKeyAndTenantId() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
    params.put("processDefinitionTenantId", MockProvider.EXAMPLE_TENANT_ID);

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
    verify(mockSuspensionStateBuilder).processDefinitionTenantId(MockProvider.EXAMPLE_TENANT_ID);
    verify(mockSuspensionStateBuilder).suspend();
  }

  @Test
  public void testSuspendJobByProcessDefinitionKeyWithoutTenantId() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
    params.put("processDefinitionWithoutTenantId", true);

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY);
    verify(mockSuspensionStateBuilder).processDefinitionWithoutTenantId();
    verify(mockSuspensionStateBuilder).suspend();
  }

  @Test
  public void testActivateJobByProcessDefinitionId() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
    verify(mockSuspensionStateBuilder).activate();
  }

  @Test
  public void testActivateJobByProcessDefinitionIdWithException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);

    String expectedException = "expectedException";
    doThrow(new ProcessEngineException(expectedException))
      .when(mockSuspensionStateBuilder)
      .activate();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
        .body("type", is(ProcessEngineException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testActivateJobByProcessDefinitionIdThrowsAuthorizationException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);

    String expectedException = "expectedException";
    doThrow(new AuthorizationException(expectedException))
      .when(mockSuspensionStateBuilder)
      .activate();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .body("type", is(AuthorizationException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testSuspendJobByProcessDefinitionId() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);
    verify(mockSuspensionStateBuilder).suspend();
  }

  @Test
  public void testSuspendJobByProcessDefinitionIdWithException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);

    String expectedException = "expectedException";
    doThrow(new ProcessEngineException(expectedException))
      .when(mockSuspensionStateBuilder)
      .suspend();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
        .body("type", is(ProcessEngineException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testSuspendJobByProcessDefinitionIdThrowsAuthorizationException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID);

    String expectedException = "expectedException";
    doThrow(new AuthorizationException(expectedException))
      .when(mockSuspensionStateBuilder)
      .suspend();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .body("type", is(AuthorizationException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testActivateJobByProcessInstanceId() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byProcessInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
    verify(mockSuspensionStateBuilder).activate();
  }

  @Test
  public void testActivateJobByProcessInstanceIdWithException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);

    String expectedException = "expectedException";
    doThrow(new ProcessEngineException(expectedException))
      .when(mockSuspensionStateBuilder)
      .activate();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
        .body("type", is(ProcessEngineException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testActivateJobByProcessInstanceIdThrowsAuthorizationException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);

    String expectedException = "expectedException";
    doThrow(new AuthorizationException(expectedException))
      .when(mockSuspensionStateBuilder)
      .activate();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .body("type", is(AuthorizationException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testSuspendJobByProcessInstanceId() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byProcessInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
    verify(mockSuspensionStateBuilder).suspend();
  }

  @Test
  public void testSuspendJobByProcessInstanceIdWithException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);

    String expectedException = "expectedException";
    doThrow(new ProcessEngineException(expectedException))
      .when(mockSuspensionStateBuilder)
      .suspend();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
        .body("type", is(ProcessEngineException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testSuspendJobByProcessInstanceIdThrowsAuthorizationException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);

    String expectedException = "expectedException";
    doThrow(new AuthorizationException(expectedException))
      .when(mockSuspensionStateBuilder)
      .suspend();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .body("type", is(AuthorizationException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testActivateJobByJobDefinitionId() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID);

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byJobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID);
    verify(mockSuspensionStateBuilder).activate();
  }

  @Test
  public void testActivateJobByJobDefinitionIdThrowsAuthorizationException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID);

    String expectedException = "expectedException";
    doThrow(new AuthorizationException(expectedException))
      .when(mockSuspensionStateBuilder)
      .activate();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .body("type", is(AuthorizationException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testSuspendJobByJobDefinitionId() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID);

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.NO_CONTENT.getStatusCode())
      .when()
        .put(JOB_SUSPENDED_URL);

    verify(mockSuspensionStateSelectBuilder).byJobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID);
    verify(mockSuspensionStateBuilder).suspend();
  }

  @Test
  public void testSuspendJobByJobDefinitionIdThrowsAuthorizationException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID);

    String expectedException = "expectedException";
    doThrow(new AuthorizationException(expectedException))
      .when(mockSuspensionStateBuilder)
      .suspend();

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.FORBIDDEN.getStatusCode())
        .body("type", is(AuthorizationException.class.getSimpleName()))
        .body("message", is(expectedException))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testActivateJobByIdShouldThrowException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", false);
    params.put("jobId", MockProvider.EXAMPLE_JOB_ID);

    String message = "Either jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey can be set to update the suspension state.";

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.BAD_REQUEST.getStatusCode())
        .body("type", is(InvalidRequestException.class.getSimpleName()))
        .body("message", is(message))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testSuspendJobByIdShouldThrowException() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);
    params.put("jobId", MockProvider.EXAMPLE_JOB_ID);

    String message = "Either jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey can be set to update the suspension state.";

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.BAD_REQUEST.getStatusCode())
        .body("type", is(InvalidRequestException.class.getSimpleName()))
        .body("message", is(message))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testSuspendJobByNothing() {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("suspended", true);

    String message = "Either jobId, jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey should be set to update the suspension state.";

    given()
      .contentType(ContentType.JSON)
      .body(params)
    .then()
      .expect()
        .statusCode(Status.BAD_REQUEST.getStatusCode())
        .body("type", is(InvalidRequestException.class.getSimpleName()))
        .body("message", is(message))
      .when()
        .put(JOB_SUSPENDED_URL);
  }

  @Test
  public void testSetJobPriority() {
    Map<String, Object> priorityJson = new HashMap<String, Object>();
    priorityJson.put("priority", MockProvider.EXAMPLE_JOB_PRIORITY);

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
      .contentType(ContentType.JSON)
      .body(priorityJson)
    .then().expect()
      .statusCode(Status.NO_CONTENT.getStatusCode())
    .when().put(JOB_RESOURCE_SET_PRIORITY_URL);

    verify(mockManagementService).setJobPriority(MockProvider.EXAMPLE_JOB_ID, MockProvider.EXAMPLE_JOB_PRIORITY);
  }

  @Test
  public void testSetJobPriorityToExtremeValue() {
    Map<String, Object> priorityJson = new HashMap<String, Object>();
    priorityJson.put("priority", Long.MAX_VALUE);

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
      .contentType(ContentType.JSON)
      .body(priorityJson)
    .then().expect()
      .statusCode(Status.NO_CONTENT.getStatusCode())
    .when().put(JOB_RESOURCE_SET_PRIORITY_URL);

    verify(mockManagementService).setJobPriority(MockProvider.EXAMPLE_JOB_ID, Long.MAX_VALUE);
  }

  @Test
  public void testSetJobPriorityNonExistentJob() {
    String expectedMessage = "No job found with id '" + MockProvider.NON_EXISTING_JOB_ID + "'.";

    doThrow(new NotFoundException(expectedMessage))
      .when(mockManagementService).setJobPriority(MockProvider.NON_EXISTING_JOB_ID, MockProvider.EXAMPLE_JOB_PRIORITY);

    Map<String, Object> priorityJson = new HashMap<String, Object>();
    priorityJson.put("priority", MockProvider.EXAMPLE_JOB_PRIORITY);

    given()
      .pathParam("id", MockProvider.NON_EXISTING_JOB_ID)
      .contentType(ContentType.JSON)
      .body(priorityJson)
    .then().expect()
      .statusCode(Status.NOT_FOUND.getStatusCode())
      .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
      .body("message", equalTo(expectedMessage))
    .when().put(JOB_RESOURCE_SET_PRIORITY_URL);

    verify(mockManagementService).setJobPriority(MockProvider.NON_EXISTING_JOB_ID, MockProvider.EXAMPLE_JOB_PRIORITY);
  }

  @Test
  public void testSetJobPriorityFailure() {
    String expectedMessage = "No job found with id '" + MockProvider.EXAMPLE_JOB_ID + "'.";

    doThrow(new ProcessEngineException(expectedMessage))
      .when(mockManagementService).setJobPriority(MockProvider.EXAMPLE_JOB_ID, MockProvider.EXAMPLE_JOB_PRIORITY);

    Map<String, Object> priorityJson = new HashMap<String, Object>();
    priorityJson.put("priority", MockProvider.EXAMPLE_JOB_PRIORITY);

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
      .contentType(ContentType.JSON)
      .body(priorityJson)
    .then().expect()
      .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
      .body("type", equalTo(RestException.class.getSimpleName()))
      .body("message", equalTo(expectedMessage))
    .when().put(JOB_RESOURCE_SET_PRIORITY_URL);

    verify(mockManagementService).setJobPriority(MockProvider.EXAMPLE_JOB_ID, MockProvider.EXAMPLE_JOB_PRIORITY);
  }

  @Test
  public void testSetNullJobPriorityFailure() {
    String expectedMessage = "Priority for job '" +  MockProvider.EXAMPLE_JOB_ID + "' cannot be null.";

    Map<String, Object> priorityJson = new HashMap<String, Object>();
    priorityJson.put("priority", null);

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
      .contentType(ContentType.JSON)
      .body(priorityJson)
    .then().expect()
      .statusCode(Status.BAD_REQUEST.getStatusCode())
      .body("type", equalTo(RestException.class.getSimpleName()))
      .body("message", equalTo(expectedMessage))
    .when().put(JOB_RESOURCE_SET_PRIORITY_URL);

    verifyNoMoreInteractions(mockManagementService);
  }

  @Test
  public void testSetJobPriorityThrowsAuthorizationException() {
    String message = "expected exception";
    doThrow(new AuthorizationException(message))
      .when(mockManagementService).setJobPriority(anyString(), anyInt());

    Map<String, Object> priorityJson = new HashMap<String, Object>();
    priorityJson.put("priority", MockProvider.EXAMPLE_JOB_PRIORITY);

    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
      .contentType(ContentType.JSON)
      .body(priorityJson)
    .then().expect()
      .statusCode(Status.FORBIDDEN.getStatusCode())
      .body("type", equalTo(AuthorizationException.class.getSimpleName()))
      .body("message", equalTo(message))
    .when()
      .put(JOB_RESOURCE_SET_PRIORITY_URL);
  }

  @Test
  public void deleteJob() {
    given()
      .pathParam("id", MockProvider.EXAMPLE_JOB_ID)
    .then().expect()
      .statusCode(Status.NO_CONTENT.getStatusCode())
    .when()
      .delete(SINGLE_JOB_RESOURCE_URL);

    verify(mockManagementService).deleteJob(MockProvider.EXAMPLE_JOB_ID);
    verifyNoMoreInteractions(mockManagementService);
  }

  @Test
  public void deleteNotExistingJob() {
    String jobId = MockProvider.NON_EXISTING_JOB_ID;

    String expectedMessage = "No job found with id '" + jobId + "'.";

    doThrow(new NullValueException(expectedMessage))
      .when(mockManagementService).deleteJob(jobId);

    given()
      .pathParam("id", jobId)
    .then().expect()
      .statusCode(Status.NOT_FOUND.getStatusCode())
      .body("type", equalTo(InvalidRequestException.class.getSimpleName()))
      .body("message", equalTo(expectedMessage))
    .when()
      .delete(SINGLE_JOB_RESOURCE_URL);

    verify(mockManagementService).deleteJob(jobId);
    verifyNoMoreInteractions(mockManagementService);
  }

  @Test
  public void deleteLockedJob() {
    String jobId = MockProvider.EXAMPLE_JOB_ID;

    String expectedMessage = "Cannot delete job when the job is being executed. Try again later.";

    doThrow(new ProcessEngineException(expectedMessage))
      .when(mockManagementService).deleteJob(jobId);

    given()
      .pathParam("id", jobId)
      .then().expect()
      .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode())
      .body("type", equalTo(RestException.class.getSimpleName()))
      .body("message", equalTo(expectedMessage))
      .when()
      .delete(SINGLE_JOB_RESOURCE_URL);

    verify(mockManagementService).deleteJob(jobId);
    verifyNoMoreInteractions(mockManagementService);
  }

  @Test
  public void deleteJobThrowAuthorizationException() {
    String jobId = MockProvider.EXAMPLE_JOB_ID;

    String expectedMessage = "Missing permissions";

    doThrow(new AuthorizationException(expectedMessage))
      .when(mockManagementService).deleteJob(jobId);

    given()
      .pathParam("id", jobId)
    .then().expect()
      .statusCode(Status.FORBIDDEN.getStatusCode())
      .body("type", is(AuthorizationException.class.getSimpleName()))
      .body("message", is(expectedMessage))
    .when()
      .delete(SINGLE_JOB_RESOURCE_URL);

    verify(mockManagementService).deleteJob(jobId);
    verifyNoMoreInteractions(mockManagementService);
  }

  @Test
  public void testSetRetriesAsync() {
    List<String> ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID);
    Batch batchEntity = MockProvider.createMockBatch();
    when(mockManagementService.setJobRetriesAsync(
        anyListOf(String.class),
        any(JobQuery.class),
        anyInt())
    ).thenReturn(batchEntity);

    Map<String, Object> messageBodyJson = new HashMap<String, Object>();
    messageBodyJson.put("jobIds", ids);
    messageBodyJson.put(RETRIES, 5);

    Response response = given()
        .contentType(ContentType.JSON).body(messageBodyJson)
        .then().expect()
        .statusCode(Status.OK.getStatusCode())
        .when().post(JOBS_SET_RETRIES_URL);

    verifyBatchJson(response.asString());

    verify(mockManagementService, times(1)).setJobRetriesAsync(
        eq(ids), eq((JobQuery) null), eq(5));
  }

  @Test
  public void testSetRetriesAsyncWithQuery() {
    Batch batchEntity = MockProvider.createMockBatch();
    when(mockManagementService.setJobRetriesAsync(
        anyListOf(String.class),
        any(JobQuery.class),
        anyInt())
    ).thenReturn(batchEntity);

    Map<String, Object> messageBodyJson = new HashMap<String, Object>();
    messageBodyJson.put(RETRIES, 5);
    HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto();
    messageBodyJson.put("jobQuery", query);

    Response response = given()
        .contentType(ContentType.JSON).body(messageBodyJson)
        .then().expect()
        .statusCode(Status.OK.getStatusCode())
        .when().post(JOBS_SET_RETRIES_URL);

    verifyBatchJson(response.asString());

    verify(mockManagementService, times(1)).setJobRetriesAsync(
        eq((List<String>) null), any(JobQuery.class), Mockito.eq(5));
  }

  @Test
  public void testSetRetriesWithBadRequestQuery() {
    doThrow(new BadUserRequestException("job ids are empty"))
        .when(mockManagementService).setJobRetriesAsync(eq((List<String>) null), eq((JobQuery) null), anyInt());

    Map<String, Object> messageBodyJson = new HashMap<String, Object>();
    messageBodyJson.put(RETRIES, 5);

    given()
        .contentType(ContentType.JSON).body(messageBodyJson)
        .then().expect()
        .statusCode(Status.BAD_REQUEST.getStatusCode())
        .when().post(JOBS_SET_RETRIES_URL);
  }

  @Test
  public void testSetRetriesWithoutBody() {
    given()
        .contentType(ContentType.JSON)
        .then().expect()
        .statusCode(Status.BAD_REQUEST.getStatusCode())
        .when().post(JOBS_SET_RETRIES_URL);
  }

  @Test
  public void testSetRetriesWithNegativeRetries() {
    doThrow(new BadUserRequestException("retries are negative"))
        .when(mockManagementService).setJobRetriesAsync(
        anyListOf(String.class),
        any(JobQuery.class),
        eq(-1));

    Map<String, Object> messageBodyJson = new HashMap<String, Object>();
    messageBodyJson.put(RETRIES, -1);
    HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto();
    messageBodyJson.put("jobQuery", query);

    given()
        .contentType(ContentType.JSON).body(messageBodyJson)
        .then().expect()
        .statusCode(Status.BAD_REQUEST.getStatusCode())
        .when().post(JOBS_SET_RETRIES_URL);
  }

  @Test
  public void testSetRetriesWithoutRetries() {
    Map<String, Object> messageBodyJson = new HashMap<String, Object>();
    messageBodyJson.put("jobIds", null);

    given()
        .contentType(ContentType.JSON)
        .body(messageBodyJson)
        .then().expect()
        .statusCode(Status.BAD_REQUEST.getStatusCode())
        .when().post(JOBS_SET_RETRIES_URL);
  }

  protected void verifyBatchJson(String batchJson) {
    BatchDto batch = JsonPathUtil.from(batchJson).getObject("", BatchDto.class);
    assertNotNull("The returned batch should not be null.", batch);
    assertEquals(MockProvider.EXAMPLE_BATCH_ID, batch.getId());
    assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, batch.getType());
    assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, batch.getTotalJobs());
    assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, batch.getBatchJobsPerSeed());
    assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, batch.getInvocationsPerBatchJob());
    assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, batch.getSeedJobDefinitionId());
    assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, batch.getMonitorJobDefinitionId());
    assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, batch.getBatchJobDefinitionId());
    assertEquals(MockProvider.EXAMPLE_TENANT_ID, batch.getTenantId());
  }

}


text: Welcome to the AP World Studying Website

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="ru.stqa.pft.addressbook.tests.GroupDeletionTests" tests="1" skipped="0" failures="0" errors="0" timestamp="2017-07-20T13:25:27" hostname="gpodmorina" time="1.409">
  <properties/>
  <testcase name="testGroupDeletion" classname="ru.stqa.pft.addressbook.tests.GroupDeletionTests" time="1.409"/>
  <system-out><![CDATA[]]></system-out>
  <system-err><![CDATA[]]></system-err>
</testsuite>


text:
<?php
/**
 * ComposerTest.php
 *
 * Creation date: 2014-09-24
 * Creation time: 21:13
 *
 * @author Arkadiusz Moskwa <a.moskwa@gmail.com>
 */

namespace Nakard\MusicFormats\Tests\Media\Id3v2\Frame\TextInformation\InvolvedPersons;

use Nakard\MusicFormats\Media\Id3v2\Frame\TextInformation\InvolvedPersons\Composer;
use Nakard\MusicFormats\Tests\Media\Id3v2\Frame\TextInformation\AbstractFrameTestCase;

/**
 * Class ComposerTest
 *
 * @package Nakard\MusicFormats\Tests\Media\Id3v2\Frame\TextInformation\InvolvedPersons
 */
class ComposerTest extends AbstractFrameTestCase
{
    /**
     * @var Composer
     */
    protected $frame;

    protected function setUp()
    {
        parent::setUp();
        $this->frame = new Composer();
    }

    public function testGetIdentifier()
    {
        $this->assertSame('TCOM', $this->frame->getIdentifier());
    }
}


text:
package org.graphwalker.core.algorithm;

import org.graphwalker.core.machine.Context;
import org.graphwalker.core.model.Element;
import org.graphwalker.core.model.Path;

import java.util.HashMap;
import java.util.Map;

import static org.graphwalker.core.model.Edge.RuntimeEdge;
import static org.graphwalker.core.model.Vertex.RuntimeVertex;

/**
 * @author Nils Olsson
 */
public class Eulerian implements Algorithm {

  private final Context context;
  private final Map<RuntimeVertex, PolarityCounter> polarities;

  public Eulerian(Context context) {
    this.context = context;
    this.polarities = new HashMap<>(context.getModel().getVertices().size());
    polarize();
  }

  public enum EulerianType {
    EULERIAN, SEMI_EULERIAN, NOT_EULERIAN
  }

  private void polarize() {
    for (RuntimeEdge edge : context.getModel().getEdges()) {
      getPolarityCounter(edge.getSourceVertex()).decrease();
      getPolarityCounter(edge.getTargetVertex()).increase();
    }
    for (RuntimeVertex vertex : context.getModel().getVertices()) {
      if (!polarities.get(vertex).hasPolarity()) {
        polarities.remove(vertex);
      }
    }
  }

  private PolarityCounter getPolarityCounter(RuntimeVertex vertex) {
    if (!polarities.containsKey(vertex)) {
      polarities.put(vertex, new PolarityCounter());
    }
    return polarities.get(vertex);
  }

  public EulerianType getEulerianType() {
    if (polarities.isEmpty()) {
      return EulerianType.EULERIAN;
    }
    if (2 == polarities.size()) {
      return EulerianType.SEMI_EULERIAN;
    }
    return EulerianType.NOT_EULERIAN;
  }

  public Path<Element> getEulerPath(Element element) {
    if (EulerianType.NOT_EULERIAN.equals(getEulerianType())) {
      throw new AlgorithmException("The model is not eulerian or semi eulerian, no single path can cover the entire graph");
    }
    return context.getAlgorithm(Fleury.class).getTrail(element);
  }

  class PolarityCounter {

    private int polarity = 0;

    public void increase() {
      polarity += 1;
    }

    public void decrease() {
      polarity -= 1;
    }

    public boolean hasPolarity() {
      return 0 != getPolarity();
    }

    public int getPolarity() {
      return polarity;
    }
  }
}


text:
package com.mentor.nucleus.bp.debug.engine;

import java.io.File;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.debug.internal.ui.DebugUIPlugin;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;

import com.mentor.nucleus.bp.core.ComponentInstance_c;
import com.mentor.nucleus.bp.core.ComponentPackageInPackage_c;
import com.mentor.nucleus.bp.core.ComponentPackage_c;
import com.mentor.nucleus.bp.core.ComponentReference_c;
import com.mentor.nucleus.bp.core.Component_c;
import com.mentor.nucleus.bp.core.CorePlugin;
import com.mentor.nucleus.bp.core.DomainAsComponent_c;
import com.mentor.nucleus.bp.core.Domain_c;
import com.mentor.nucleus.bp.core.Function_c;
import com.mentor.nucleus.bp.core.Ooaofooa;
import com.mentor.nucleus.bp.core.SystemModel_c;
import com.mentor.nucleus.bp.core.common.ClassQueryInterface_c;
import com.mentor.nucleus.bp.core.common.PersistableModelComponent;
import com.mentor.nucleus.bp.core.ui.perspective.BridgePointPerspective;
import com.mentor.nucleus.bp.debug.ui.launch.BPDebugUtils;
import com.mentor.nucleus.bp.debug.ui.test.DebugUITestUtilities;
import com.mentor.nucleus.bp.test.TestUtil;
import com.mentor.nucleus.bp.test.common.BaseTest;
import com.mentor.nucleus.bp.test.common.TestingUtilities;

//========================================================================
//
//File:      $RCSfile: VerifierMessageTest.java,v $
//Version:   $Revision: 1.5 $
//Modified:  $Date: 2013/05/10 04:28:38 $
//
//(c) Copyright 2011-2014 by Mentor Graphics Corp. All rights reserved.
//
//========================================================================
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   See the
// License for the specific language governing permissions and limitations under
// the License.
//========================================================================

public class VerifierMessageTest extends BaseTest {

	private static String projectName = "VerifierMessageTest";

	private boolean initialized = false;

	public VerifierMessageTest(String testName) throws Exception {
		super(projectName, testName);
	}

	@Override
	protected void setUp() throws Exception {
		super.setUp();

		if (!initialized) {
			CorePlugin.disableParseAllOnResourceChange();

			// set perspective switch dialog on launch
			DebugUIPlugin.getDefault().getPluginPreferences().setValue(
					IDebugUIConstants.PLUGIN_ID + ".switch_to_perspective",
					"always");

			// initialize test model
			final IProject project = ResourcesPlugin.getWorkspace().getRoot()
					.getProject(projectName);

			loadProject(projectName);

			m_sys = SystemModel_c.SystemModelInstance(Ooaofooa
					.getDefaultInstance(), new ClassQueryInterface_c() {

				public boolean evaluate(Object candidate) {
					return ((SystemModel_c) candidate).getName().equals(
							project.getName());
				}

			});

			PersistableModelComponent sys_comp = m_sys
					.getPersistableComponent();
			sys_comp.loadComponentAndChildren(new NullProgressMonitor());

			TestingUtilities.allowJobCompletion();
			while (!ResourcesPlugin.getWorkspace().getRoot().isSynchronized(
					IProject.DEPTH_INFINITE)) {
				ResourcesPlugin.getWorkspace().getRoot().refreshLocal(
						IProject.DEPTH_INFINITE, new NullProgressMonitor());
				while (PlatformUI.getWorkbench().getDisplay().readAndDispatch())
					;
			}

			Ooaofooa.setPersistEnabled(true);

			initialized = true;
		}
	}

	public void tearDown() throws Exception {
		// terminate all launches
		DebugUITestUtilities.terminateAllProcesses(m_sys);
		// remove all launch configurations
		DebugUITestUtilities.removeAllConfigurations();
		// clear the any console output
		DebugUITestUtilities.clearConsoleOutput();
		DebugUITestUtilities.clearDebugView();
		// remove all breakpoints
		DebugUITestUtilities.removeAllBreakpoints();
		// wait for display events to complete
		TestingUtilities.processDisplayEvents();
	}

	public void testDeclaredToDeclaredRootToRoot() throws InterruptedException {
		performMessageTestFromComponent("Declared to Declared", "Root to Root",
				"Test Requirer");
	}

	public void testDeclaredToReferencedRootToRoot()
			throws InterruptedException {
		performMessageTestFromComponent("Declared to Referenced",
				"Root to Root", "Test Requirer");
	}

	public void testReferencedToDeclaredRootToRoot()
			throws InterruptedException {
		performMessageTestFromReference(
				"Referenced to Declared",
				"Root to Root",
				"VerifierMessageTest::MessageTest::Test Library::Component Execution Test Requirer");
	}

	public void testReferencedToReferencedRootToRoot()
			throws InterruptedException {
		performMessageTestFromReference(
				"Referenced to Referenced",
				"Root to Root",
				"VerifierMessageTest::MessageTest::Test Library::Component Execution Test Requirer");
	}

	private void performMessageTestFromReference(final String mainName, final String subName,
			final String componentName) {
		ComponentPackage_c componentPkg = ComponentPackage_c
				.getOneCP_CPOnR4606(m_sys, new ClassQueryInterface_c() {

					public boolean evaluate(Object candidate) {
						return ((ComponentPackage_c) candidate).getName()
								.equals(mainName);
					}

				});
		assertNotNull(componentPkg);

		ComponentPackage_c testPkg = ComponentPackage_c.getOneCP_CPOnR4601(
				ComponentPackageInPackage_c
						.getManyCP_CPINPsOnR4600(componentPkg),
				new ClassQueryInterface_c() {

					public boolean evaluate(Object candidate) {
						return ((ComponentPackage_c) candidate).getName()
								.equals(subName);
					}

				});
		assertNotNull(testPkg);
		// launch the components
		DebugUITestUtilities.setLogActivityAndLaunchForElement(testPkg,
				m_bp_tree.getControl().getMenu(), m_sys.getName());

		ComponentReference_c compRef = ComponentReference_c.getOneCL_ICOnR4605(testPkg,
				new ClassQueryInterface_c() {

					public boolean evaluate(Object candidate) {
						return ((ComponentReference_c) candidate).getName().equals(
								componentName);
					}

				});
		assertNotNull(compRef);

		Domain_c dom = Domain_c.getOneS_DOMOnR4204(DomainAsComponent_c
				.getOneCN_DCOnR4204(Component_c.getManyC_CsOnR4201(compRef)));
		assertNotNull(dom);

		Function_c testLaunch = Function_c.getOneS_SYNCOnR23(dom,
				new ClassQueryInterface_c() {

					public boolean evaluate(Object candidate) {
						return ((Function_c) candidate).getName()
								.equals("test");
					}

				});
		assertNotNull(testLaunch);

		openPerspectiveAndView(
				"com.mentor.nucleus.bp.debug.ui.DebugPerspective",
				BridgePointPerspective.ID_MGC_BP_EXPLORER);
		BPDebugUtils.openSessionExplorerView(true);

		BPDebugUtils.executeElement(testLaunch);

		DebugUITestUtilities.waitForExecution();
		ComponentInstance_c engine = ComponentInstance_c
				.getOneI_EXEOnR2963(compRef);
		assertNotNull(engine);
		// wait for the execution to complete
		DebugUITestUtilities.waitForBPThreads(m_sys);

		// compare the trace
		File expectedResults = new File(m_workspace_path
				+ "expected_results/verifier/" + mainName + " " + subName
				+ ".result");
		String expected_results = TestUtil.getTextFileContents(expectedResults);
		// get the text representation of the debug tree
		String actual_results = DebugUITestUtilities
				.getConsoleText(expected_results);
		assertEquals(expected_results, actual_results);

	}

	private void performMessageTestFromComponent(final String mainName,
			final String subName, final String componentName) {
		ComponentPackage_c componentPkg = ComponentPackage_c
				.getOneCP_CPOnR4606(m_sys, new ClassQueryInterface_c() {

					public boolean evaluate(Object candidate) {
						return ((ComponentPackage_c) candidate).getName()
								.equals(mainName);
					}

				});
		assertNotNull(componentPkg);

		ComponentPackage_c testPkg = ComponentPackage_c.getOneCP_CPOnR4601(
				ComponentPackageInPackage_c
						.getManyCP_CPINPsOnR4600(componentPkg),
				new ClassQueryInterface_c() {

					public boolean evaluate(Object candidate) {
						return ((ComponentPackage_c) candidate).getName()
								.equals(subName);
					}

				});
		assertNotNull(testPkg);
		// launch the components
		DebugUITestUtilities.setLogActivityAndLaunchForElement(testPkg,
				m_bp_tree.getControl().getMenu(), m_sys.getName());

		Component_c component = Component_c.getOneC_COnR4608(testPkg,
				new ClassQueryInterface_c() {

					public boolean evaluate(Object candidate) {
						return ((Component_c) candidate).getName().equals(
								componentName);
					}

				});
		while (component == null) {
			Display.getDefault().readAndDispatch();
		}
		assertNotNull(component);

		Domain_c dom = Domain_c.getOneS_DOMOnR4204(DomainAsComponent_c
				.getOneCN_DCOnR4204(component));
		assertNotNull(dom);

		Function_c testLaunch = Function_c.getOneS_SYNCOnR23(dom,
				new ClassQueryInterface_c() {

					public boolean evaluate(Object candidate) {
						return ((Function_c) candidate).getName()
								.equals("test");
					}

				});
		assertNotNull(testLaunch);

		openPerspectiveAndView(
				"com.mentor.nucleus.bp.debug.ui.DebugPerspective",
				BridgePointPerspective.ID_MGC_BP_EXPLORER);

		BPDebugUtils.executeElement(testLaunch);

		DebugUITestUtilities.waitForExecution();
		ComponentInstance_c engine = ComponentInstance_c
				.getOneI_EXEOnR2955(component);
		assertNotNull(engine);

		// wait for the execution to complete
		DebugUITestUtilities.waitForBPThreads(m_sys);

		// compare the trace
		File expectedResults = new File(m_workspace_path
				+ "expected_results/verifier/" + mainName + " " + subName
				+ ".result");
		String expected_results = TestUtil.getTextFileContents(expectedResults);
		// get the text representation of the debug tree
		String actual_results = DebugUITestUtilities
				.getConsoleText(expected_results);
		assertEquals(expected_results, actual_results);

	}

}


text:
import Card from './card';
import Utils from './../utils';

/**
 * Represents a round of a game. Most of the player interactions happen in this class.
 */
export default class Round {
  /**
   * Gets the players in the round.
   * @type {Player[]}
   */
  get players() {
    return this._players;
  }

  /**
   * Gets the seed used for initially shuffling the deck.
   * @type {(string|number|number[])}
   */
  get deckSeed() {
    return this._deckSeed;
  }

  /**
   * Gets the cards in the deck, by order.
   * @type {Card[]}
   */
  get cardsInDeck() {
    return this._cardsInDeck;
  }

  /**
   * Gets the cards shown on the table. These cards can be seen by every player in the round.
   * @type {Card[]}
   */
  get cardsOnTable() {
    return this._cardsOnTable;
  }

  /**
   * @private
   * @param {Game} ownerGame
   * @param {Player[]} players
   * @param {(string|number|number[])} deckSeed
   */
  constructor(ownerGame, players, deckSeed) {
    this._ownerGame = ownerGame;
    this._players = players;
    this._cardsInDeck = [];
    this._cardsOnTable = [];

    // TODO: Add support for custom starting decks
    // Generate the starting deck
    let ownerDeck = ownerGame.deck;
    for (let i = ownerDeck.cardTypes - 1; i >= 0; i--) {
      this._cardsInDeck.push(new Card(i, ownerDeck, this));
    }

    // Shuffle the deck based on the deck seed
    this._deckSeed = Utils.shuffleArray(this._cardsInDeck, deckSeed);
  }

  /**
   * Deals a specific amount of cards to a single or multiple players. Once the deck becomes empty, no more cards are dealt.
   * @param {number} amount The amount of cards which should be dealt to each of the players.
   * @param {...Player} players Players to whom cards should be dealt. If empty, everyone in the round gets cards.
   */
  deal(amount = 1, ...players) {
    if (players.length === 0) {
      // Deal for every player in the round
      players = this._players;
    }

    players.forEach((player) => {
      for (let i = Math.min(amount, this._cardsInDeck.length); i > 0; i--) {
        // Remove the drawn card from the deck, and then give it to the player
        player.cards.push(this._cardsInDeck.shift());
      }
    });
  }

  /**
   * Draws a specific amount of cards to the table, so every player in the round can see them. Once the deck becomes empty, no more cards are dealt.
   * @param {number} amount The amount of cards which should be drawn.
   */
  drawToTable(amount = 1) {
    for (let i = Math.min(amount, this._cardsInDeck.length); i > 0; i--) {
      // Remove the drawn card from the deck, and then put it on the table
      this._cardsOnTable.push(this._cardsInDeck.shift());
    }
  }

  /**
   * Gets a player in the round by ID.
   * @param {(number|string)} id
   * @returns {Player?} Returns a player object or null if the player could not be found.
   */
  getPlayerById(id) {
    return Utils.getObjectById(this._players, id);
  }
}


text:
package com.amazonaws.services.elasticsearch.model;

import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;

/**
 *

 * Container for the parameters to the
 * DescribeElasticsearchDomains operation. By default, the
 * API returns the status of all Elasticsearch domains.
 *

 */
public class DescribeElasticsearchDomainsRequest extends
        AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The Elasticsearch domains for which you want information.
     *

     */
    private java.util.List<String> domainNames;

    /**
     *

     * The Elasticsearch domains for which you want information.
     *

     *
     * @return The Elasticsearch domains for which you want information.
     */
    public java.util.List<String> getDomainNames() {
        return domainNames;
    }

    /**
     *

     * The Elasticsearch domains for which you want information.
     *

     *
     * @param domainNames
     *        The Elasticsearch domains for which you want information.
     */
    public void setDomainNames(java.util.Collection<String> domainNames) {
        if (domainNames == null) {
            this.domainNames = null;
            return;
        }

        this.domainNames = new java.util.ArrayList<String>(domainNames);
    }

    /**
     *

     * The Elasticsearch domains for which you want information.
     *

     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setDomainNames(java.util.Collection)} or
     * {@link #withDomainNames(java.util.Collection)} if you want to override
     * the existing values.
     *

     *
     * @param domainNames
     *        The Elasticsearch domains for which you want information.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DescribeElasticsearchDomainsRequest withDomainNames(
            String... domainNames) {
        if (this.domainNames == null) {
            setDomainNames(new java.util.ArrayList<String>(domainNames.length));
        }
        for (String ele : domainNames) {
            this.domainNames.add(ele);
        }
        return this;
    }

    /**
     *

     * The Elasticsearch domains for which you want information.
     *

     *
     * @param domainNames
     *        The Elasticsearch domains for which you want information.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DescribeElasticsearchDomainsRequest withDomainNames(
            java.util.Collection<String> domainNames) {
        setDomainNames(domainNames);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDomainNames() != null)
            sb.append("DomainNames: " + getDomainNames());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeElasticsearchDomainsRequest == false)
            return false;
        DescribeElasticsearchDomainsRequest other = (DescribeElasticsearchDomainsRequest) obj;
        if (other.getDomainNames() == null ^ this.getDomainNames() == null)
            return false;
        if (other.getDomainNames() != null
                && other.getDomainNames().equals(this.getDomainNames()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime
                * hashCode
                + ((getDomainNames() == null) ? 0 : getDomainNames().hashCode());
        return hashCode;
    }

    @Override
    public DescribeElasticsearchDomainsRequest clone() {
        return (DescribeElasticsearchDomainsRequest) super.clone();
    }
}


text:
'use strict';

describe('Data.Queue Tests', function() {
  it('queue', function() {
    var queue = new Prime.Data.Queue();

    assert.isTrue(queue.isEmpty());

    var object = "string";
    queue.add(object);

    assert.isFalse(queue.isEmpty());
    assert.equal(queue.size(), 1);
    var headObject = queue.peek();

    assert.equal(object, headObject);
    assert.equal(queue.size(), 1);

    headObject = queue.poll();
    assert.equal(object, headObject);
    assert.equal(queue.size(), 0);
    assert.isTrue(queue.isEmpty());

    queue.add("foo").add("bar").add("baz");
    assert.equal(queue.size(), 3);

    assert.equal(queue.peek(), "foo");
    assert.equal(queue.poll(), "foo");
    assert.equal(queue.peek(), "bar");
    assert.equal(queue.poll(), "bar");
    assert.equal(queue.poll(), "baz");
    assert.isTrue(queue.isEmpty());

    queue.add("foo").add("bar").add("baz");
    assert.equal(queue.size(), 3);
  });
});


text:
require "livingsocial/version"
require "livingsocial/daily_deal"
require "livingsocial/daily_deal_builder"
require "livingsocial/national_deal_builder"
require "livingsocial/national_deal"


text:
/**
 * \file
 * \brief Base capability/cnode handling functions.
 */

/*
 * Copyright (c) 2007, 2008, 2009, 2010, 2012, ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
 */

#ifndef INCLUDEBARRELFISH_CAPABILITIES_ARCH_H
#define INCLUDEBARRELFISH_CAPABILITIES_ARCH_H

#include <stdint.h>
#include <sys/cdefs.h>

#include <barrelfish_kpi/types.h>
#include <barrelfish_kpi/capabilities.h>
#include <barrelfish_kpi/dispatcher_shared.h>
#include <barrelfish_kpi/distcaps.h>
#include <barrelfish/invocations.h>
#include <barrelfish/slot_alloc.h>

__BEGIN_DECLS

/*
 * MVAS extension: arch specific flags to vnode_inherit.
 */
static inline errval_t vnode_inherit_attr(struct capref dest, struct capref src,
                                          cslot_t start, cslot_t end,
                                          paging_x86_64_flags_t newflags,
                                          struct capref *src_mapping_cn,
                                          struct capref *dst_mapping_cn)
{
    enum cnode_type slevel = get_cap_level(src);
    capaddr_t saddr = get_cap_addr(src);

    capaddr_t mcn[2*MCN_COUNT];
    for (size_t i = 0; i < MCN_COUNT; i++) {
        mcn[i] = get_cap_addr(src_mapping_cn[i]);
        assert(get_cap_level(src_mapping_cn[i]) == CNODE_TYPE_OTHER);
    }
    for (size_t i = 0; i < MCN_COUNT; i++) {
        mcn[MCN_COUNT+i] = get_cap_addr(dst_mapping_cn[i]);
        assert(get_cap_level(dst_mapping_cn[i]) == CNODE_TYPE_OTHER);
    }

    return invoke_vnode_inherit(dest, saddr, slevel, start, end, newflags, mcn);
}

__END_DECLS

#endif //INCLUDEBARRELFISH_CAPABILITIES_ARCH_H


text:
#include "qdbusargument_p.h"
#include "qdbusconnection.h"
#include <stdlib.h>

QT_BEGIN_NAMESPACE

template <typename T>
static inline T qIterGet(DBusMessageIter *it)
{
    // Use a union of expected and largest type q_dbus_message_iter_get_basic
    // will return to ensure reading the wrong basic type does not result in
    // stack overwrite
    union {
        // The value to be extracted
        T t;
        // Largest type that q_dbus_message_iter_get_basic will return
        // according to dbus_message_iter_get_basic API documentation
        dbus_uint64_t maxValue;
        // A pointer to ensure no stack overwrite in case there is a platform
        // where sizeof(void*) > sizeof(dbus_uint64_t)
        void* ptr;
    } value;

    // Initialize the value in case a narrower type is extracted to it.
    // Note that the result of extracting a narrower type in place of a wider
    // one and vice-versa will be platform-dependent.
    value.t = T();

    q_dbus_message_iter_get_basic(it, &value);
    q_dbus_message_iter_next(it);
    return value.t;
}

QDBusDemarshaller::~QDBusDemarshaller()
{
}

inline QString QDBusDemarshaller::currentSignature()
{
    char *sig = q_dbus_message_iter_get_signature(&iterator);
    QString retval = QString::fromUtf8(sig);
    q_dbus_free(sig);

    return retval;
}

inline uchar QDBusDemarshaller::toByte()
{
    return qIterGet<uchar>(&iterator);
}

inline bool QDBusDemarshaller::toBool()
{
    return bool(qIterGet<dbus_bool_t>(&iterator));
}

inline ushort QDBusDemarshaller::toUShort()
{
    return qIterGet<dbus_uint16_t>(&iterator);
}

inline short QDBusDemarshaller::toShort()
{
    return qIterGet<dbus_int16_t>(&iterator);
}

inline int QDBusDemarshaller::toInt()
{
    return qIterGet<dbus_int32_t>(&iterator);
}

inline uint QDBusDemarshaller::toUInt()
{
    return qIterGet<dbus_uint32_t>(&iterator);
}

inline qlonglong QDBusDemarshaller::toLongLong()
{
    return qIterGet<qlonglong>(&iterator);
}

inline qulonglong QDBusDemarshaller::toULongLong()
{
    return qIterGet<qulonglong>(&iterator);
}

inline double QDBusDemarshaller::toDouble()
{
    return qIterGet<double>(&iterator);
}

inline QString QDBusDemarshaller::toStringUnchecked()
{
    return QString::fromUtf8(qIterGet<char *>(&iterator));
}

inline QString QDBusDemarshaller::toString()
{
    if (isCurrentTypeStringLike())
        return toStringUnchecked();
    else
        return QString();
}

inline QDBusObjectPath QDBusDemarshaller::toObjectPathUnchecked()
 {
     return QDBusObjectPath(QString::fromUtf8(qIterGet<char *>(&iterator)));
 }

inline QDBusObjectPath QDBusDemarshaller::toObjectPath()
{
    if (isCurrentTypeStringLike())
        return toObjectPathUnchecked();
    else
        return QDBusObjectPath();
}

inline QDBusSignature QDBusDemarshaller::toSignatureUnchecked()
 {
     return QDBusSignature(QString::fromUtf8(qIterGet<char *>(&iterator)));
 }

inline QDBusSignature QDBusDemarshaller::toSignature()
{
    if (isCurrentTypeStringLike())
        return toSignatureUnchecked();
    else
        return QDBusSignature();
}

inline QDBusUnixFileDescriptor QDBusDemarshaller::toUnixFileDescriptor()
{
    QDBusUnixFileDescriptor fd;
    fd.giveFileDescriptor(qIterGet<dbus_int32_t>(&iterator));
    return fd;
}

inline QDBusVariant QDBusDemarshaller::toVariant()
{
    QDBusDemarshaller sub(capabilities);
    sub.message = q_dbus_message_ref(message);
    q_dbus_message_iter_recurse(&iterator, &sub.iterator);
    q_dbus_message_iter_next(&iterator);

    return QDBusVariant( sub.toVariantInternal() );
}

QDBusArgument::ElementType QDBusDemarshaller::currentType()
{
    switch (q_dbus_message_iter_get_arg_type(&iterator)) {
    case DBUS_TYPE_BYTE:
    case DBUS_TYPE_INT16:
    case DBUS_TYPE_UINT16:
    case DBUS_TYPE_INT32:
    case DBUS_TYPE_UINT32:
    case DBUS_TYPE_INT64:
    case DBUS_TYPE_UINT64:
    case DBUS_TYPE_BOOLEAN:
    case DBUS_TYPE_DOUBLE:
    case DBUS_TYPE_STRING:
    case DBUS_TYPE_OBJECT_PATH:
    case DBUS_TYPE_SIGNATURE:
        return QDBusArgument::BasicType;

    case DBUS_TYPE_VARIANT:
        return QDBusArgument::VariantType;

    case DBUS_TYPE_ARRAY:
        switch (q_dbus_message_iter_get_element_type(&iterator)) {
        case DBUS_TYPE_BYTE:
        case DBUS_TYPE_STRING:
            // QByteArray and QStringList
            return QDBusArgument::BasicType;
        case DBUS_TYPE_DICT_ENTRY:
            return QDBusArgument::MapType;
        default:
            return QDBusArgument::ArrayType;
        }

    case DBUS_TYPE_STRUCT:
        return QDBusArgument::StructureType;
    case DBUS_TYPE_DICT_ENTRY:
        return QDBusArgument::MapEntryType;

    case DBUS_TYPE_UNIX_FD:
        return capabilities & QDBusConnection::UnixFileDescriptorPassing ?
                    QDBusArgument::BasicType : QDBusArgument::UnknownType;

    case DBUS_TYPE_INVALID:
        return QDBusArgument::UnknownType;

//    default:
//        qWarning("QDBusDemarshaller: Found unknown D-Bus type %d '%c'",
//                 q_dbus_message_iter_get_arg_type(&iterator),
//                 q_dbus_message_iter_get_arg_type(&iterator));
    }
    return QDBusArgument::UnknownType;
}

QVariant QDBusDemarshaller::toVariantInternal()
{
    switch (q_dbus_message_iter_get_arg_type(&iterator)) {
    case DBUS_TYPE_BYTE:
        return QVariant::fromValue(toByte());
    case DBUS_TYPE_INT16:
	return QVariant::fromValue(toShort());
    case DBUS_TYPE_UINT16:
	return QVariant::fromValue(toUShort());
    case DBUS_TYPE_INT32:
        return toInt();
    case DBUS_TYPE_UINT32:
        return toUInt();
    case DBUS_TYPE_DOUBLE:
        return toDouble();
    case DBUS_TYPE_BOOLEAN:
        return toBool();
    case DBUS_TYPE_INT64:
        return toLongLong();
    case DBUS_TYPE_UINT64:
        return toULongLong();
    case DBUS_TYPE_STRING:
        return toStringUnchecked();
    case DBUS_TYPE_OBJECT_PATH:
        return QVariant::fromValue(toObjectPathUnchecked());
    case DBUS_TYPE_SIGNATURE:
        return QVariant::fromValue(toSignatureUnchecked());
    case DBUS_TYPE_VARIANT:
        return QVariant::fromValue(toVariant());

    case DBUS_TYPE_ARRAY:
        switch (q_dbus_message_iter_get_element_type(&iterator)) {
        case DBUS_TYPE_BYTE:
            // QByteArray
            return toByteArrayUnchecked();
        case DBUS_TYPE_STRING:
            return toStringListUnchecked();
        case DBUS_TYPE_DICT_ENTRY:
            return QVariant::fromValue(duplicate());

        default:
            return QVariant::fromValue(duplicate());
        }

    case DBUS_TYPE_STRUCT:
        return QVariant::fromValue(duplicate());

    case DBUS_TYPE_UNIX_FD:
        if (capabilities & QDBusConnection::UnixFileDescriptorPassing)
            return QVariant::fromValue(toUnixFileDescriptor());
        // fall through

    default:
//        qWarning("QDBusDemarshaller: Found unknown D-Bus type %d '%c'",
//                 q_dbus_message_iter_get_arg_type(&iterator),
//                 q_dbus_message_iter_get_arg_type(&iterator));
        char *ptr = 0;
        ptr += q_dbus_message_iter_get_arg_type(&iterator);
        q_dbus_message_iter_next(&iterator);

        // I hope you never dereference this pointer!
        return QVariant::fromValue<void *>(ptr);
    };
}

bool QDBusDemarshaller::isCurrentTypeStringLike()
{
    const int type = q_dbus_message_iter_get_arg_type(&iterator);
    switch (type) {
    case DBUS_TYPE_STRING:  //FALLTHROUGH
    case DBUS_TYPE_OBJECT_PATH:  //FALLTHROUGH
    case DBUS_TYPE_SIGNATURE:
        return true;
    default:
        return false;
    }
}

QStringList QDBusDemarshaller::toStringListUnchecked()
{
    QStringList list;

    QDBusDemarshaller sub(capabilities);
    q_dbus_message_iter_recurse(&iterator, &sub.iterator);
    q_dbus_message_iter_next(&iterator);
    while (!sub.atEnd())
        list.append(sub.toStringUnchecked());

    return list;
}

QStringList QDBusDemarshaller::toStringList()
{
    if (q_dbus_message_iter_get_arg_type(&iterator) == DBUS_TYPE_ARRAY
            && q_dbus_message_iter_get_element_type(&iterator) == DBUS_TYPE_STRING)
        return toStringListUnchecked();
    else
        return QStringList();
}

QByteArray QDBusDemarshaller::toByteArrayUnchecked()
{
    DBusMessageIter sub;
    q_dbus_message_iter_recurse(&iterator, &sub);
    q_dbus_message_iter_next(&iterator);
    int len;
    char* data;
    q_dbus_message_iter_get_fixed_array(&sub,&data,&len);
    return QByteArray(data,len);
}

QByteArray QDBusDemarshaller::toByteArray()
{
    if (q_dbus_message_iter_get_arg_type(&iterator) == DBUS_TYPE_ARRAY
            && q_dbus_message_iter_get_element_type(&iterator) == DBUS_TYPE_BYTE) {
        return toByteArrayUnchecked();
    }
    return QByteArray();
}

bool QDBusDemarshaller::atEnd()
{
    // dbus_message_iter_has_next is broken if the list has one single element
    return q_dbus_message_iter_get_arg_type(&iterator) == DBUS_TYPE_INVALID;
}

inline QDBusDemarshaller *QDBusDemarshaller::beginStructure()
{
    return beginCommon();
}

inline QDBusDemarshaller *QDBusDemarshaller::beginArray()
{
    return beginCommon();
}

inline QDBusDemarshaller *QDBusDemarshaller::beginMap()
{
    return beginCommon();
}

inline QDBusDemarshaller *QDBusDemarshaller::beginMapEntry()
{
    return beginCommon();
}

QDBusDemarshaller *QDBusDemarshaller::beginCommon()
{
    QDBusDemarshaller *d = new QDBusDemarshaller(capabilities);
    d->parent = this;
    d->message = q_dbus_message_ref(message);

    // recurse
    q_dbus_message_iter_recurse(&iterator, &d->iterator);
    q_dbus_message_iter_next(&iterator);
    return d;
}

inline QDBusDemarshaller *QDBusDemarshaller::endStructure()
{
    return endCommon();
}

inline QDBusDemarshaller *QDBusDemarshaller::endArray()
{
    return endCommon();
}

inline QDBusDemarshaller *QDBusDemarshaller::endMap()
{
    return endCommon();
}

inline QDBusDemarshaller *QDBusDemarshaller::endMapEntry()
{
    return endCommon();
}

QDBusDemarshaller *QDBusDemarshaller::endCommon()
{
    QDBusDemarshaller *retval = parent;
    delete this;
    return retval;
}

QDBusArgument QDBusDemarshaller::duplicate()
{
    QDBusDemarshaller *d = new QDBusDemarshaller(capabilities);
    d->iterator = iterator;
    d->message = q_dbus_message_ref(message);

    q_dbus_message_iter_next(&iterator);
    return QDBusArgumentPrivate::create(d);
}

QT_END_NAMESPACE


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using System.IO;

namespace RandomCodeOrg.ENetFramework {

    /// <summary>
    /// This class provides the logic that allows an ENetFramework application to be executed right out of the IDE.
    /// Let your main class inherit from this class and redirect the startup arguments to the protected instance method 'Start(string[])'.
    ///
    /// </summary>
    /// <example>
    /// <code>
    /// using RandomCodeOrg.ENetFramework;
    ///
    /// namespace Foo.Bar {
    ///
    /// class YourMainClass : ENetFrameworkApplication {
    ///
    ///     static void Main(string[] args) {
    ///         new Program().Start(args);
    ///     }
    ///
    /// }
    /// </code>
    /// </example>
    public abstract class ENetFrameworkApplication {

        /// <summary>
        /// This method starts the application server configured by the given command line arguments and deploys this application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        protected void Start(string[] args) {
            string containerName = null;
            string containerPath = null;

            ApplicationStartupConfig startupConfig = new ApplicationStartupConfig(args);
            if (!startupConfig.TryOption(StartupArgument.CONTAINER, out containerName) & !startupConfig.TryOption(StartupArgument.CONTAINER_PATH, out containerPath)) {
                Console.WriteLine("The container could not be found!");
                Console.WriteLine("You may use the command line arguments -Container and -ContainerPath to specify the application server to be used.");
                Console.WriteLine();
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
                return;
            }
            bool remoteLoading = startupConfig.HasFlag(StartupArgument.REMOTE_LOADING);

            Debug.WriteLine("Using container {0} at '{1}.'", containerName, containerPath);
            string filePath = Path.Combine(containerPath, containerName) + ".dll";
            if (!File.Exists(filePath))
                filePath = Path.Combine(containerPath, containerName) + ".exe";
            if (!File.Exists(filePath))
                filePath = containerPath;
            if (!File.Exists(filePath)) {
                Console.WriteLine("The container could not be found!");
                Console.WriteLine();
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
                return;
            }
            filePath = Path.GetFullPath(filePath);
            Debug.WriteLine("Using assembly at: {0}", args = new string[] { filePath });
            AssemblyLoader assemblyLoader = new AssemblyLoader(filePath);
            if (remoteLoading) {
                Debug.WriteLine("WARN: Usage of remote assemblies is enabled. For more details refer to: https://msdn.microsoft.com/en-us/library/dd409252(vs.100).aspx#Anchor_1");
            }
            assemblyLoader.AllowRemoteAssemblies = remoteLoading;
            assemblyLoader.Handle(AppDomain.CurrentDomain);

            var containerAssembly = assemblyLoader.LoadDirect(filePath);

            Debug.WriteLine("Loaded assembly: {0}", new string[] { containerAssembly.FullName });

            Assembly toDeploy = GetType().Assembly;

            Start(containerAssembly, toDeploy, startupConfig.HasFlag(StartupArgument.CRATE_PACKAGE));
        }

        private void Start(Assembly containerAssembly, Assembly toDeploy, bool createPackage) {
            containerAssembly.EntryPoint.Invoke(null, new object[] { new string[] { } });
            var container = ENetFrameworkContext.Instance.ApplicationContainer;
            if (container == null) {
                Debug.WriteLine("Startup failed.");
                return;
            }
            var package = new Deployment.DevelopmentDeploymentPackage(toDeploy);
            if (createPackage) {
                Deployment.CompressedApplicationPackage.Create("package.capp", package);
            }

            container.Deploy(package);
            Console.ReadKey();
            container.Shutdown();
            Environment.Exit(0);
        }

    }
}


text: Packet bare metal cloud driver for Docker Machine


text:
package edu.uci.ics.asterix.common.transactions;

import java.io.IOException;

import edu.uci.ics.asterix.common.exceptions.ACIDException;
import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;

/**
 * Provides API for failure recovery. Failure could be at application level and
 * require a roll back or could be at system level (crash) and require a more
 * sophisticated mechanism of replaying logs and bringing the system to a
 * consistent state ensuring durability.
 */
public interface IRecoveryManager {

    public enum SystemState {
        NEW_UNIVERSE,
        RECOVERING,
        HEALTHY,
        CORRUPTED
    }

    public class ResourceType {
        public static final byte LSM_BTREE = 0;
        public static final byte LSM_RTREE = 1;
        public static final byte LSM_INVERTED_INDEX = 2;
    }

    /**
     * Returns the state of the system.
     * Health state of the system could be any one of the following. RECOVERING:
     * The system is recovering HEALTHY: The system is in healthy state
     * CORRUPTEED: The system is in corrupted state. This happens when a
     * rollback or recovery task fails. In this state the system is unusable.
     *
     * @see SystemState
     * @return SystemState The state of the system
     * @throws ACIDException
     */
    SystemState getSystemState() throws ACIDException;

    /**
     * Initiates a crash recovery.
     *
     * @param synchronous
     *            indicates if the recovery is to be done in a synchronous
     *            manner. In asynchronous mode, the recovery will happen as part
     *            of a separate thread.
     * @return SystemState the state of the system (@see SystemState) post
     *         recovery.
     * @throws ACIDException
     */
    public void startRecovery(boolean synchronous) throws IOException, ACIDException;

    /**
     * Rolls back a transaction.
     *
     * @param txnContext
     *            the transaction context associated with the transaction
     * @throws ACIDException
     */
    public void rollbackTransaction(ITransactionContext txnContext) throws ACIDException;

    /**
     * Makes a system checkpoint.
     * @param isSharpCheckpoint a flag indicating whether to perform a sharp or non-sharp checkpoint.
     * @param nonSharpCheckpointTargetLSN if a non-sharp checkpoint to be performed, what is the minimum LSN it should target.
     * @return the LSN at which the checkpoint was performed.
     * @throws ACIDException
     * @throws HyracksDataException
     */
    public long checkpoint(boolean isSharpCheckpoint, long nonSharpCheckpointTargetLSN) throws ACIDException, HyracksDataException;

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<field name="trade">
  <research>
    <title>Handel</title>
    <text>Schaltet weiter Forschungsfelder für Handel frei</text>
    <levels>
      <level num="1" researchers="2" experience="1000" />
      <level num="2" researchers="4" experience="2500" />
      <level num="3" researchers="6" experience="5000" />
      <level num="4" researchers="8" experience="10000" />
      <level num="5" researchers="10" experience="16000" />
      <level num="6" researchers="12" experience="24000" />
    </levels>
  </research>
</field>


text:
define(
    [
        'dojo/_base/declare',
        'dojo/_base/array',
        'dojo/_base/lang',
        'dijit/TitlePane',
        'dijit/layout/ContentPane',
        'JBrowse/Util',
        'dojo/dom-construct',
        'JBrowse/View/TrackList/_TextFilterMixin'
    ],
    function (
        declare,
        array,
        lang,
        TitlePane,
        ContentPane,
        Util,
        dom,
        _TextFilterMixin
    ) {

var dojof = Util.dojof;
return declare(
        'WebApollo.View.InformationEditor',
        [ ContentPane, _TextFilterMixin ],
{
    region: 'left',
    splitter: true,
    style: 'width: 25%',

    id: 'informationEditor',
    baseClass: 'webapolloInformationEditor',

    /**
      * Track selector with facets and text searching.
      * @constructs
      */
    constructor: function() {
        console.log('Testing InformationEditor');
    },

    postCreate: function() {
        console.log('Testing InformationEditor postCreate');
        this.placeAt( this.browser.container );
    },
    buildRendering: function() {
        this.inherited(arguments);

        var topPane = new ContentPane({ className: 'header' });
        this.addChild( topPane );
        dom.create(
            'h2',
            { className: 'title',
              innerHTML: 'Annotation Information Editor'
            },
            topPane.containerNode );

        this._makeTextFilterNodes(
            dom.create('div',
                { className: 'textfilterContainer' },
            topPane.containerNode )
        );
        this._updateTextFilterControl();

        this.informationList =
        { pane: new ContentPane({ id: 'informationEditorList', className: 'information_list' }).placeAt( this.containerNode )
        };
    }
});

});


text: <!DOCTYPE HTML>