@Test
  public void testResetOriginalValues() throws Exception {
    CalendarResource newCalendarResource = addCalendarResource();

    _persistence.clearCache();

    CalendarResource existingCalendarResource =
        _persistence.findByPrimaryKey(newCalendarResource.getPrimaryKey());

    Assert.assertTrue(
        Validator.equals(
            existingCalendarResource.getUuid(),
            ReflectionTestUtil.invoke(
                existingCalendarResource, "getOriginalUuid", new Class<?>[0])));
    Assert.assertEquals(
        Long.valueOf(existingCalendarResource.getGroupId()),
        ReflectionTestUtil.<Long>invoke(
            existingCalendarResource, "getOriginalGroupId", new Class<?>[0]));

    Assert.assertEquals(
        Long.valueOf(existingCalendarResource.getClassNameId()),
        ReflectionTestUtil.<Long>invoke(
            existingCalendarResource, "getOriginalClassNameId", new Class<?>[0]));
    Assert.assertEquals(
        Long.valueOf(existingCalendarResource.getClassPK()),
        ReflectionTestUtil.<Long>invoke(
            existingCalendarResource, "getOriginalClassPK", new Class<?>[0]));
  }
  @Test
  public void testTwoInclude() throws Exception {
    HttpGet httpGet =
        new HttpGet(
            "http://localhost:"
                + ourPort
                + "/Patient?name=Hello&_include=foo&_include=bar&_pretty=true");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info(responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent);
    assertEquals(1, bundle.size());

    Patient p = bundle.getResources(Patient.class).get(0);
    assertEquals(2, p.getName().size());
    assertEquals("Hello", p.getId().getIdPart());

    Set<String> values = new HashSet<String>();
    values.add(p.getName().get(0).getFamilyFirstRep().getValue());
    values.add(p.getName().get(1).getFamilyFirstRep().getValue());
    assertThat(values, containsInAnyOrder("foo", "bar"));
  }
  /**
   * Test the deployment operation. This will add and remove a given set of deployment using a
   * composite operation and attaching the streams necessary to the http post message.
   *
   * @param quantity the amount of deployments
   * @param encoded whether to send the operation in the dmr encoded format or not
   * @throws IOException
   */
  private void testDeploymentOperations(final int quantity, final boolean encoded)
      throws IOException {

    // Create the deployment
    final File temp = createTempDeploymentZip();
    try {
      final ModelNode deployment = createCompositeDeploymentOperation(quantity);
      final ContentBody operation = getOperationBody(deployment, encoded);
      final List<ContentBody> streams = new ArrayList<ContentBody>();
      for (int i = 0; i < quantity; i++) {
        streams.add(new FileBody(temp));
      }

      final ModelNode response = executePost(operation, encoded, streams);
      Assert.assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());

    } finally {
      temp.delete();
    }

    // And remove the deployments again
    final ModelNode remove = removeDeploymentsOperation(quantity);
    final ContentBody operation = getOperationBody(remove, encoded);
    final ModelNode response = executePost(operation, encoded);
    Assert.assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());
  }
Esempio n. 4
1
  @Test
  public void testChildrenRIMsDifferentEntity() {
    ResourceState initial = new ResourceState("Note", "initial", mockActions(), "/note/{id}");
    ResourceState comment =
        new ResourceState("Comment", "draft", mockActions(), "/comments/{noteid}");

    // example uri linkage uses 'id' from Note entity to transition to 'noteid' of comments resource
    Map<String, String> uriLinkageMap = new HashMap<String, String>();
    uriLinkageMap.put("noteid", "id");
    // create comment for note
    initial.addTransition(
        new Transition.Builder()
            .method("PUT")
            .target(comment)
            .uriParameters(uriLinkageMap)
            .build());
    // update comment
    comment.addTransition(new Transition.Builder().method("PUT").target(comment).build());

    // supply a transformer to check that this is copied into child resource
    BeanTransformer transformer = new BeanTransformer();

    ResourceStateMachine stateMachine = new ResourceStateMachine(initial, transformer);
    HTTPHypermediaRIM parent =
        new HTTPHypermediaRIM(mockCommandController(), stateMachine, createMockMetadata());
    Collection<ResourceInteractionModel> resources = parent.getChildren();
    assertEquals(1, resources.size());
    assertEquals(comment.getPath(), resources.iterator().next().getResourcePath());
    assertEquals(
        transformer,
        ((HTTPHypermediaRIM) resources.iterator().next()).getHypermediaEngine().getTransformer());
  }
Esempio n. 5
1
 @Test
 public void max3float() {
   assertEquals(0.3f, Math.max(0.1f, 0.2f, 0.3f), 0.0);
   assertEquals(0.31f, Math.max(0.31f, 0.2f, 0.3f), 0.0);
   assertEquals(0.5f, Math.max(0.1f, 0.5f, 0.3f), 0.0);
   assertEquals(0.5f, Math.max(-10.1f, 0.5f, -0.3f), 0.0);
 }
Esempio n. 6
1
 @Test
 public void min4float() {
   assertEquals(-10.1f, Math.min(-10.1f, 5.45f, -3.12f, 36.9f), 0.0);
   assertEquals(-5.45f, Math.min(10.1f, -5.45f, -3.12f, 6.9f), 0.0);
   assertEquals(3.12f, Math.min(10.1f, 5.45f, 3.12f, 36.9f), 0.0);
   assertEquals(16.9f, Math.min(100.1f, 25.45f, 23.12f, 16.9f), 0.0);
 }
Esempio n. 7
1
 @Test
 public void max4int() {
   assertEquals(5, Math.max(-10, 5, 3, 1));
   assertEquals(10, Math.max(10, 5, 3, 1));
   assertEquals(13, Math.max(-10, 5, 13, 1));
   assertEquals(15, Math.max(-10, 5, 3, 15));
 }
  /**
   * Test with a subtitle with multiple format to read.
   *
   * @throws IOException if there was an I/O error.
   */
  @Test
  public void testMultipleFormatSubtitle() throws IOException {
    final SubtitleFormat subtitleFormat = mock(SubtitleFormat.class);
    final SubtitleReader subtitleReader = mock(SubtitleReader.class);
    final SubtitleFile subtitleFile = mock(SubtitleFile.class);
    final Path file = subtitleFolder.newFile("single.srt").toPath();

    when(subtitleFormatManager.getFormatByPath(file))
        .thenReturn(new HashSet<>(Arrays.asList(subtitleFormat, mock(SubtitleFormat.class))));
    when(userPrompt.askChoice(
            anyCollectionOf(SubtitleFormat.class),
            eq(TRANSLATION_KEY.chooseSubtitleFormat()),
            eq(file)))
        .thenReturn(subtitleFormat);
    when(subtitleFormat.getReader()).thenReturn(subtitleReader);
    when(subtitleReader.readFile(file)).thenReturn(subtitleFile);
    final Map<SubtitleFile, SubtitleFormat> subtitles = subtitleProvider.loadSubtitles(file);
    assertEquals(1, subtitles.size());
    final Entry<SubtitleFile, SubtitleFormat> loaded = subtitles.entrySet().iterator().next();
    assertEquals(subtitleFile, loaded.getKey());
    assertEquals(subtitleFormat, loaded.getValue());
    verify(userPrompt)
        .askChoice(
            anyCollectionOf(SubtitleFormat.class),
            eq(TRANSLATION_KEY.chooseSubtitleFormat()),
            eq(file));
  }
Esempio n. 9
0
 @Test
 public void test3LTSolve() {
   for (int seed = 0; seed < 10; seed++) {
     m = new CPModel();
     s = new CPSolver();
     int k = 2;
     IntegerVariable v0 = makeIntVar("v0", 0, 10);
     IntegerVariable v1 = makeIntVar("v1", 0, 10);
     m.addConstraint(distanceLT(v0, v1, k));
     s.read(m);
     s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
     s.setValIntSelector(new RandomIntValSelector(seed));
     try {
       s.propagate();
     } catch (ContradictionException e) {
       LOGGER.info(e.getMessage()); // To change body of catch statement use File | Settings | File
       // Templates.
     }
     s.solveAll();
     int nbNode = s.getNodeCount();
     LOGGER.info("solutions : " + s.getNbSolutions() + " nbNode : " + nbNode);
     assertEquals(s.getNbSolutions(), 31);
     assertEquals(nbNodeFromRegulatModel(seed), nbNode);
   }
 }
  @Test
  public void testRemoveRemovesItemFromSet() throws Exception {
    final AppenderControlArraySet set = new AppenderControlArraySet();
    set.add(createControl("A"));
    set.add(createControl("B"));
    set.add(createControl("C"));
    set.add(createControl("D"));
    assertEquals(4, set.get().length);

    set.remove("B");
    assertEquals(3, set.get().length);
    final AppenderControl[] three = set.get();
    assertEquals("A", three[0].getAppenderName());
    assertEquals("C", three[1].getAppenderName());
    assertEquals("D", three[2].getAppenderName());

    set.remove("C");
    assertEquals(2, set.get().length);
    final AppenderControl[] two = set.get();
    assertEquals("A", two[0].getAppenderName());
    assertEquals("D", two[1].getAppenderName());

    set.remove("A");
    assertEquals(1, set.get().length);
    final AppenderControl[] one = set.get();
    assertEquals("D", one[0].getAppenderName());

    set.remove("D");
    assertTrue(set.isEmpty());
  }
  /** Confirm that the equals method can distinguish all the required fields. */
  @Test
  public void testEquals() {
    QuarterDateFormat qf1 =
        new QuarterDateFormat(TimeZone.getTimeZone("GMT"), new String[] {"1", "2", "3", "4"});
    QuarterDateFormat qf2 =
        new QuarterDateFormat(TimeZone.getTimeZone("GMT"), new String[] {"1", "2", "3", "4"});
    assertEquals(qf1, qf2);
    assertEquals(qf2, qf1);

    qf1 = new QuarterDateFormat(TimeZone.getTimeZone("PST"), new String[] {"1", "2", "3", "4"});
    assertFalse(qf1.equals(qf2));
    qf2 = new QuarterDateFormat(TimeZone.getTimeZone("PST"), new String[] {"1", "2", "3", "4"});
    assertEquals(qf1, qf2);

    qf1 = new QuarterDateFormat(TimeZone.getTimeZone("PST"), new String[] {"A", "2", "3", "4"});
    assertFalse(qf1.equals(qf2));
    qf2 = new QuarterDateFormat(TimeZone.getTimeZone("PST"), new String[] {"A", "2", "3", "4"});
    assertEquals(qf1, qf2);

    qf1 =
        new QuarterDateFormat(TimeZone.getTimeZone("PST"), new String[] {"A", "2", "3", "4"}, true);
    assertFalse(qf1.equals(qf2));
    qf2 =
        new QuarterDateFormat(TimeZone.getTimeZone("PST"), new String[] {"A", "2", "3", "4"}, true);
    assertEquals(qf1, qf2);
  }
Esempio n. 12
0
  @Test
  public void testCreateAndDropTable() throws Exception {
    catalog.createDatabase("tmpdb1", TajoConstants.DEFAULT_TABLESPACE_NAME);
    assertTrue(catalog.existDatabase("tmpdb1"));
    catalog.createDatabase("tmpdb2", TajoConstants.DEFAULT_TABLESPACE_NAME);
    assertTrue(catalog.existDatabase("tmpdb2"));

    TableDesc table1 = createMockupTable("tmpdb1", "table1");
    catalog.createTable(table1);

    TableDesc table2 = createMockupTable("tmpdb2", "table2");
    catalog.createTable(table2);

    Set<String> tmpdb1 = Sets.newHashSet(catalog.getAllTableNames("tmpdb1"));
    assertEquals(1, tmpdb1.size());
    assertTrue(tmpdb1.contains("table1"));

    Set<String> tmpdb2 = Sets.newHashSet(catalog.getAllTableNames("tmpdb2"));
    assertEquals(1, tmpdb2.size());
    assertTrue(tmpdb2.contains("table2"));

    catalog.dropDatabase("tmpdb1");
    assertFalse(catalog.existDatabase("tmpdb1"));

    tmpdb2 = Sets.newHashSet(catalog.getAllTableNames("tmpdb2"));
    assertEquals(1, tmpdb2.size());
    assertTrue(tmpdb2.contains("table2"));

    catalog.dropDatabase("tmpdb2");
    assertFalse(catalog.existDatabase("tmpdb2"));
  }
Esempio n. 13
0
  @Test
  public final void testRegisterAndFindFunc() throws Exception {
    assertFalse(catalog.containFunction("test10", FunctionType.GENERAL));
    FunctionDesc meta =
        new FunctionDesc(
            "test10",
            TestFunc2.class,
            FunctionType.GENERAL,
            CatalogUtil.newSimpleDataType(Type.INT4),
            CatalogUtil.newSimpleDataTypeArray(Type.INT4, Type.BLOB));

    catalog.createFunction(meta);
    assertTrue(
        catalog.containFunction(
            "test10", CatalogUtil.newSimpleDataTypeArray(Type.INT4, Type.BLOB)));
    FunctionDesc retrived =
        catalog.getFunction("test10", CatalogUtil.newSimpleDataTypeArray(Type.INT4, Type.BLOB));

    assertEquals(retrived.getFunctionName(), "test10");
    assertEquals(retrived.getLegacyFuncClass(), TestFunc2.class);
    assertEquals(retrived.getFuncType(), FunctionType.GENERAL);

    assertFalse(
        catalog.containFunction(
            "test10", CatalogUtil.newSimpleDataTypeArray(Type.BLOB, Type.INT4)));
  }
Esempio n. 14
0
  @Test
  public void testGetSpeed() {
    // Test 10M
    final Speed10M speed10M = new Speed10MBuilder().setSpeed10M(true).build();
    Speed getSpeed = Utils.getSpeed("10M");
    assertEquals(speed10M, getSpeed);

    // Test 100M
    final Speed100M speedObject100M = new Speed100MBuilder().setSpeed100M(true).build();
    getSpeed = Utils.getSpeed("100M");
    assertEquals(speedObject100M, getSpeed);

    // Test 1G
    final Speed1G speedObject1G = new Speed1GBuilder().setSpeed1G(true).build();
    getSpeed = Utils.getSpeed("1G");
    assertEquals(speedObject1G, getSpeed);

    // Test 10G
    final Speed10G speedObject10G = new Speed10GBuilder().setSpeed10G(true).build();
    getSpeed = Utils.getSpeed("10G");
    assertEquals(speedObject10G, getSpeed);

    // Test other
    getSpeed = Utils.getSpeed("1");
    assertEquals(null, getSpeed);
  }
Esempio n. 15
0
  @Test
  public void testStats() throws InterruptedException {
    l.lock();
    assertTrue(l.isLocked());
    assertTrue(l.isLockedByCurrentThread());
    assertEquals(1, l.getLockCount());

    l.unlock();
    assertFalse(l.isLocked());
    assertEquals(0, l.getLockCount());
    assertEquals(-1L, l.getRemainingLeaseTime());

    l.lock(1, TimeUnit.MINUTES);
    assertTrue(l.isLocked());
    assertTrue(l.isLockedByCurrentThread());
    assertEquals(1, l.getLockCount());
    assertTrue(l.getRemainingLeaseTime() > 1000 * 30);

    final CountDownLatch latch = new CountDownLatch(1);
    new Thread() {
      public void run() {
        assertTrue(l.isLocked());
        assertFalse(l.isLockedByCurrentThread());
        assertEquals(1, l.getLockCount());
        assertTrue(l.getRemainingLeaseTime() > 1000 * 30);
        latch.countDown();
      }
    }.start();
    assertTrue(latch.await(1, TimeUnit.MINUTES));
  }
  @Test
  public void testRemoveParameter() {
    SimpleParameterManager manager = new SimpleParameterManager();
    SimpleParameter<?> parameter1 = new SimpleParameter<>();
    SimpleParameter<?> parameter2 = new SimpleParameter<>();
    SimpleParameter<?> parameter3 = new SimpleParameter<>();

    manager.addParameter(parameter1);
    manager.addParameter(parameter2);
    manager.addParameter(parameter3);
    assertEquals(3, manager.getParameters().size());
    assertTrue(manager.getParameters().contains(parameter1));
    assertTrue(manager.getParameters().contains(parameter2));
    assertTrue(manager.getParameters().contains(parameter3));

    manager.removeParameter(parameter1);
    assertEquals(2, manager.getParameters().size());
    assertFalse(manager.getParameters().contains(parameter1));
    assertTrue(manager.getParameters().contains(parameter2));
    assertTrue(manager.getParameters().contains(parameter3));

    manager.removeParameter(parameter2);
    assertEquals(1, manager.getParameters().size());
    assertFalse(manager.getParameters().contains(parameter1));
    assertFalse(manager.getParameters().contains(parameter2));
    assertTrue(manager.getParameters().contains(parameter3));

    manager.removeParameter(parameter3);
    assertEquals(0, manager.getParameters().size());
    assertFalse(manager.getParameters().contains(parameter1));
    assertFalse(manager.getParameters().contains(parameter2));
    assertFalse(manager.getParameters().contains(parameter3));
  }
Esempio n. 17
0
 @Test
 public void min4int() {
   assertEquals(-10, Math.min(-10, 5, 3, 1));
   assertEquals(-5, Math.min(10, -5, 13, 1));
   assertEquals(3, Math.min(10, 5, 3, 15));
   assertEquals(1, Math.min(10, 5, 3, 1));
 }
Esempio n. 18
0
 @Test
 public void max4float() {
   assertEquals(36.9f, Math.max(10.1f, 5.45f, -3.12f, 36.9f), 0.0);
   assertEquals(10.1f, Math.max(10.1f, 5.45f, -3.12f, 6.9f), 0.0);
   assertEquals(-3.12f, Math.max(-10.1f, -5.45f, -3.12f, -36.9f), 0.0);
   assertEquals(25.45f, Math.max(10.1f, 25.45f, -3.12f, 16.9f), 0.0);
 }
  /** Test of countOfAirplanes method, of class NumberofAirplanesintheSky. */
  @Test
  public void testCountOfAirplanes() {
    System.out.println("countOfAirplanes");
    List<Interval> airplanes = null;
    NumberofAirplanesintheSky instance = new NumberofAirplanesintheSky();
    int expResult = 0;
    int result = instance.countOfAirplanes(airplanes);
    assertEquals(expResult, result);

    List<Interval> airplanes2 = new ArrayList<Interval>();
    airplanes2.add(new Interval(1, 10));
    airplanes2.add(new Interval(2, 3));
    airplanes2.add(new Interval(4, 7));
    airplanes2.add(new Interval(5, 8));
    assertEquals(3, instance.countOfAirplanes(airplanes2));

    // [[10,14],[10,15],[10,16],[1,10],[2,10],[3,10],[4,10]]
    List<Interval> airplanes3 = new ArrayList<Interval>();
    airplanes3.add(new Interval(10, 14));
    airplanes3.add(new Interval(10, 15));
    airplanes3.add(new Interval(10, 16));
    airplanes3.add(new Interval(1, 10));
    airplanes3.add(new Interval(2, 10));
    airplanes3.add(new Interval(3, 10));
    airplanes3.add(new Interval(4, 10));
    assertEquals(4, instance.countOfAirplanes(airplanes3));
    // TODO review the generated test code and remove the default call to fail.
    // fail("The test case is a prototype.");
  }
  /** Test the calculation of the zero-utility-duration. */
  @Test
  public void testZeroUtilityDuration() {
    double zeroUtilDurW = getZeroUtilDuration_hrs(8.0, 1.0);
    double zeroUtilDurH = getZeroUtilDuration_hrs(16.0, 1.0);
    double zeroUtilDurW2 = getZeroUtilDuration_hrs(8.0, 2.0);

    {
      ActivityUtilityParameters.Factory factory = new ActivityUtilityParameters.Factory();
      factory.setType("w");
      factory.setPriority(1.0);
      factory.setTypicalDuration_s(8.0 * 3600);
      ActivityUtilityParameters params = factory.create();
      assertEquals(zeroUtilDurW, params.getZeroUtilityDuration_h(), EPSILON);
    }

    {
      ActivityUtilityParameters.Factory factory = new ActivityUtilityParameters.Factory();
      factory.setType("h");
      factory.setPriority(1.0);
      factory.setTypicalDuration_s(16.0 * 3600);
      ActivityUtilityParameters params = factory.create();
      assertEquals(zeroUtilDurH, params.getZeroUtilityDuration_h(), EPSILON);
    }

    {
      ActivityUtilityParameters.Factory factory = new ActivityUtilityParameters.Factory();
      factory.setType("w2");
      // test that the priority is respected as well
      factory.setPriority(2.0);
      factory.setTypicalDuration_s(8.0 * 3600);
      ActivityUtilityParameters params = factory.create();
      assertEquals(zeroUtilDurW2, params.getZeroUtilityDuration_h(), EPSILON);
    }
  }
  @Test
  public void testStartStop() throws Exception {
    expectConfigure();
    expectStart(Collections.EMPTY_LIST);
    expectStop();

    PowerMock.replayAll();

    store.configure(DEFAULT_PROPS);
    assertEquals(TOPIC, capturedTopic.getValue());
    assertEquals(
        "org.apache.kafka.common.serialization.ByteArraySerializer",
        capturedProducerProps.getValue().get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG));
    assertEquals(
        "org.apache.kafka.common.serialization.ByteArraySerializer",
        capturedProducerProps.getValue().get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG));
    assertEquals(
        "org.apache.kafka.common.serialization.ByteArrayDeserializer",
        capturedConsumerProps.getValue().get(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG));
    assertEquals(
        "org.apache.kafka.common.serialization.ByteArrayDeserializer",
        capturedConsumerProps.getValue().get(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG));

    store.start();
    store.stop();

    PowerMock.verifyAll();
  }
  public void encryption(SimpleHDKeyChain unencChain) throws UnreadableWalletException {
    DeterministicKey key1 = unencChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    SimpleHDKeyChain encChain = unencChain.toEncrypted("open secret");
    DeterministicKey encKey1 = encChain.findKeyFromPubKey(key1.getPubKey());
    checkEncryptedKeyChain(encChain, key1);

    // Round-trip to ensure de/serialization works and that we can store two chains and they both
    // deserialize.
    List<Protos.Key> serialized = encChain.toProtobuf();
    System.out.println(protoToString(serialized));
    encChain = SimpleHDKeyChain.fromProtobuf(serialized, encChain.getKeyCrypter());
    checkEncryptedKeyChain(encChain, unencChain.findKeyFromPubKey(key1.getPubKey()));

    DeterministicKey encKey2 = encChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    // Decrypt and check the keys match.
    SimpleHDKeyChain decChain = encChain.toDecrypted("open secret");
    DeterministicKey decKey1 = decChain.findKeyFromPubHash(encKey1.getPubKeyHash());
    DeterministicKey decKey2 = decChain.findKeyFromPubHash(encKey2.getPubKeyHash());
    assertEquals(decKey1.getPubKeyPoint(), encKey1.getPubKeyPoint());
    assertEquals(decKey2.getPubKeyPoint(), encKey2.getPubKeyPoint());
    assertFalse(decKey1.isEncrypted());
    assertFalse(decKey2.isEncrypted());
    assertNotEquals(encKey1.getParent(), decKey1.getParent()); // parts of a different hierarchy
    // Check we can once again derive keys from the decrypted chain.
    decChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).sign(Sha256Hash.ZERO_HASH);
    decChain.getKey(KeyChain.KeyPurpose.CHANGE).sign(Sha256Hash.ZERO_HASH);
  }
  /** This method test a few specila inquirey fields are set up properly. */
  @Test
  public void testGetInquiryUrl() {
    Protocol protocol = initProtocol();

    final KcPersonService kcPersonService = context.mock(KcPersonService.class);
    final String principalId = GlobalVariables.getUserSession().getPrincipalId();
    context.checking(
        new Expectations() {
          {
            one(kcPersonService).getKcPersonByPersonId(principalId);
            will(returnValue(KcPerson.fromPersonId(principalId)));
          }
        });
    protocolLookupableHelperServiceImpl.setKcPersonService(kcPersonService);

    HtmlData inquiryUrl =
        protocolLookupableHelperServiceImpl.getInquiryUrl(protocol, "leadUnitNumber");
    assertEquals(((HtmlData.AnchorHtmlData) inquiryUrl).getHref(), UNIT_INQ_URL);
    inquiryUrl = protocolLookupableHelperServiceImpl.getInquiryUrl(protocol, "investigator");
    assertEquals(((HtmlData.AnchorHtmlData) inquiryUrl).getHref(), PERSON_INQ_URL);
    ProtocolPerson protocolPerson = (ProtocolPerson) protocol.getProtocolPersons().get(0);
    protocolPerson.setPersonId("");
    protocolPerson.setRolodexId(new Integer(1727));
    protocol.getProtocolPersons().clear();
    protocol.getProtocolPersons().add(protocolPerson);
    inquiryUrl = protocolLookupableHelperServiceImpl.getInquiryUrl(protocol, "investigator");
    assertEquals(((HtmlData.AnchorHtmlData) inquiryUrl).getHref(), ROLODEX_INQ_URL);
  }
Esempio n. 24
0
  /*
  	@Test
  	public void testBootstrapRIMsCRUD() {
  		String ENTITY_NAME = "NOTE";
  		String resourcePath = "/notes/{id}";
  		ResourceState initial = new ResourceState(ENTITY_NAME, "initial", mockActions(), resourcePath);
  		ResourceState exists = new ResourceState(ENTITY_NAME, "exists", mockActions(), resourcePath);
  		ResourceState deleted = new ResourceState(ENTITY_NAME, "deleted", mockActions(), resourcePath);

  		// create
  		initial.addTransition(new Transition.Builder().method("PUT").target(exists);
  		// update
  		exists.addTransition(new Transition.Builder().method("PUT").target(exists);
  		// delete
  		exists.addTransition("DELETE", deleted);

  		// mock command controller to do nothing
  		NewCommandController cc = mock(NewCommandController.class);
  		when(cc.fetchCommand(anyString(), anyString())).thenReturn(mock(InteractionCommand.class));

  		HTTPHypermediaRIM parent = new HTTPHypermediaRIM(cc, new ResourceStateMachine(initial));
  		verify(cc).fetchCommand("GET", resourcePath);
  		Collection<ResourceInteractionModel> resources = parent.getChildren();
  		assertEquals(0, resources.size());
  		verify(cc, times(1)).fetchCommand("GET", resourcePath);
  		verify(cc, times(1)).fetchCommand("PUT", resourcePath);
  		verify(cc, times(1)).fetchCommand("DELETE", resourcePath);
  	}

  	@Test
  	public void testBootstrapRIMsSubstate() {
  		String ENTITY_NAME = "DraftNote";
  		String resourcePath = "/notes/{id}";
    		ResourceState initial = new ResourceState(ENTITY_NAME, "initial", resourcePath);
  		ResourceState exists = new ResourceState(initial, "exists", "/exists");
  		ResourceState deleted = new ResourceState(exists, "deleted", null);
  		ResourceState draft = new ResourceState(ENTITY_NAME, "draft", "/notes/{id}/draft");
  		ResourceState deletedDraft = new ResourceState(draft, "deleted");

  		// create
  		initial.addTransition(new Transition.Builder().method("PUT").target(exists);
  		// create draft
  		initial.addTransition(new Transition.Builder().method("PUT").target(draft);
  		// updated draft
  		draft.addTransition(new Transition.Builder().method("PUT").target(draft);
  		// publish
  		draft.addTransition(new Transition.Builder().method("PUT").target(exists);
  		// delete draft
  		draft.addTransition("DELETE", deletedDraft);
  		// delete published
  		exists.addTransition("DELETE", deleted);

  		// mock command controller to do nothing
  		NewCommandController cc = mock(NewCommandController.class);
  		when(cc.fetchCommand(anyString(), anyString())).thenReturn(mock(InteractionCommand.class));

  		ResourceStateMachine stateMachine = new ResourceStateMachine(initial);
  		HTTPHypermediaRIM parent = new HTTPHypermediaRIM(cc, stateMachine);
  		verify(cc).fetchCommand("GET", "/notes/{id}");
  		Collection<ResourceInteractionModel> resources = parent.getChildren();
  		assertEquals(2, resources.size());
  		assertEquals(draft, resources.iterator().next().getCurrentState());
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}/exists");
  		verify(cc).fetchCommand("DELETE", "/notes/{id}/exists");
  		verify(cc).fetchCommand("PUT", "/notes/{id}/exists");
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}/draft");
  		verify(cc).fetchCommand("DELETE", "/notes/{id}/draft");
  		verify(cc).fetchCommand("PUT", "/notes/{id}/draft");
  	}

  	@Test
  	public void testBootstrapRIMsMultipleSubstates() {
  		String ENTITY_NAME = "PublishNote";
  		String resourcePath = "/notes/{id}";
    		ResourceState initial = new ResourceState(ENTITY_NAME, "initial", resourcePath);
  		ResourceState published = new ResourceState(ENTITY_NAME, "published", "/notes/{id}/published");
  		ResourceState publishedDeleted = new ResourceState(published, "publishedDeleted", null);
  		ResourceState draft = new ResourceState(ENTITY_NAME, "draft", "/notes/{id}/draft");
  		ResourceState deletedDraft = new ResourceState(draft, "draftDeleted");

  		// create draft
  		initial.addTransition(new Transition.Builder().method("PUT").target(draft);
  		// updated draft
  		draft.addTransition(new Transition.Builder().method("PUT").target(draft);
  		// publish
  		draft.addTransition(new Transition.Builder().method("PUT").target(published);
  		// delete draft
  		draft.addTransition("DELETE", deletedDraft);
  		// delete published
  		published.addTransition("DELETE", publishedDeleted);

  		// mock command controller to do nothing
  		NewCommandController cc = mock(NewCommandController.class);
  		when(cc.fetchCommand(anyString(), anyString())).thenReturn(mock(InteractionCommand.class));

  		ResourceStateMachine stateMachine = new ResourceStateMachine(initial);
  		HTTPHypermediaRIM parent = new HTTPHypermediaRIM(cc, stateMachine);
  		verify(cc).fetchCommand("GET", "/notes/{id}");
  		Collection<ResourceInteractionModel> resources = parent.getChildren();
  		assertEquals(2, resources.size());
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}");
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}/draft");
  		verify(cc).fetchCommand("PUT", "/notes/{id}/draft");
  		verify(cc).fetchCommand("DELETE", "/notes/{id}/draft");
  		verify(cc, times(1)).fetchCommand("GET", "/notes/{id}/published");
  		verify(cc).fetchCommand("DELETE", "/notes/{id}/published");
  		verify(cc).fetchCommand("PUT", "/notes/{id}/published");
  	}

  	@Test
  	public void testBootstrapRIMsMultipleSubstates1() {
  		String ENTITY_NAME = "BOOKING";
  		String resourcePath = "/bookings";

  		// the booking
  		ResourceState begin = new ResourceState(ENTITY_NAME, "begin", resourcePath);
    		ResourceState bookingCreated = new ResourceState(begin, "bookingCreated", "/{id}");
    		ResourceState bookingCancellation = new ResourceState(bookingCreated, "cancellation", "/cancellation");
    		ResourceState deleted = new ResourceState(bookingCancellation, "deleted", null);

  		begin.addTransition(new Transition.Builder().method("PUT").target(bookingCreated);
  		bookingCreated.addTransition(new Transition.Builder().method("PUT").target(bookingCancellation);
  		bookingCancellation.addTransition("DELETE", deleted);

  		// the payment
  		ResourceState payment = new ResourceState(bookingCreated, "payment", "/payment");
  		ResourceState confirmation = new ResourceState(payment, "pconfirmation", "/pconfirmation");
  		ResourceState waitingForConfirmation = new ResourceState(payment, "pwaiting", "/pwaiting");

  		payment.addTransition(new Transition.Builder().method("PUT").target(waitingForConfirmation);
  		payment.addTransition(new Transition.Builder().method("PUT").target(confirmation);
  		waitingForConfirmation.addTransition(new Transition.Builder().method("PUT").target(confirmation);

  		// linking the two state machines together
  		bookingCreated.addTransition(new Transition.Builder().method("PUT").target(payment);  // TODO needs to be conditional
  		confirmation.addTransition(new Transition.Builder().method("PUT").target(bookingCancellation);

  		// mock command controller to do nothing
  		NewCommandController cc = mock(NewCommandController.class);
  		when(cc.fetchCommand(anyString(), anyString())).thenReturn(mock(InteractionCommand.class));

  		HTTPHypermediaRIM parent = new HTTPHypermediaRIM(cc, new ResourceStateMachine(begin));
  		verify(cc, times(1)).fetchCommand("GET", "/bookings");
  		Collection<ResourceInteractionModel> resources = parent.getChildren();
  		assertEquals(5, resources.size());
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}");
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}/cancellation");
  		verify(cc).fetchCommand("DELETE", "/bookings/{id}/cancellation");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}/cancellation");
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}/payment");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}/payment");
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}/payment/pconfirmation");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}/payment/pconfirmation");
  		verify(cc, times(1)).fetchCommand("GET", "/bookings/{id}/payment/pwaiting");
  		verify(cc).fetchCommand("PUT", "/bookings/{id}/payment/pwaiting");
  	}
  */
  @Test
  public void testChildrenRIMsSubstate() {
    String ENTITY_NAME = "DraftNote";
    String resourcePath = "/notes/{id}";
    ResourceState initial = new ResourceState(ENTITY_NAME, "initial", mockActions(), resourcePath);
    ResourceState draft = new ResourceState(ENTITY_NAME, "draft", mockActions(), "/draft");

    // create draft
    initial.addTransition(new Transition.Builder().method("PUT").target(draft).build());
    // updated draft
    draft.addTransition(new Transition.Builder().method("PUT").target(draft).build());

    // supply a transformer to check that this is copied into child resource
    BeanTransformer transformer = new BeanTransformer();

    ResourceStateMachine stateMachine = new ResourceStateMachine(initial, transformer);
    HTTPHypermediaRIM parent =
        new HTTPHypermediaRIM(mockCommandController(), stateMachine, createMockMetadata());
    Collection<ResourceInteractionModel> resources = parent.getChildren();
    assertEquals(1, resources.size());
    assertEquals(draft.getPath(), resources.iterator().next().getResourcePath());
    assertEquals(
        transformer,
        ((HTTPHypermediaRIM) resources.iterator().next()).getHypermediaEngine().getTransformer());
  }
Esempio n. 25
0
  @Test
  public void testCreateRefFromUri() throws BadRequestException {
    final ParentListRef comptes_expected =
        ParentListRefImpl.create( //
            Mediatheque.ref(UUID.fromString("448028fd-fce5-45a5-8ef4-2b591800a7e2")) //
            ,
            Compte.mCompte //
            ,
            "comptes") //
        ;
    final ParentListRef<Mediatheque.Ref, Compte> comptes_result =
        Mediatheque.mMediatheque.comptes.parse(
            "mediatheque/448028fd-fce5-45a5-8ef4-2b591800a7e2/comptes");
    assertEquals(comptes_expected, comptes_result);
    // ListRef result1 = Mediatheque.mMediatheque.comptes_ref();

    final UUID idMediatheque = UUID.randomUUID();
    final Mediatheque.Ref mediatheque_expected = Mediatheque.ref(idMediatheque);
    final Mediatheque.Ref mediatheque_result =
        Mediatheque.mMediatheque.createRefFromUri("mediatheque/" + idMediatheque);
    assertEquals(mediatheque_expected, mediatheque_result);

    final UUID idIndividu = UUID.randomUUID();
    final Individu.Ref individu_expected = Individu.ref(idIndividu);
    final Individu.Ref individu_result =
        Individu.mIndividu.createRefFromUri("individu/" + idIndividu);
    assertEquals(individu_expected, individu_result);

    final Compte.Ref compte_expected = Compte.ref(mediatheque_expected, individu_expected);
    final Compte.Ref compte_result =
        Compte.mCompte.createRefFromUri(
            "mediatheque/" + idMediatheque + "/comptes/individu/" + idIndividu);
    assertEquals(compte_expected, compte_result);
  }
Esempio n. 26
0
  @Test
  public void testDropDatabaseWithAllTables() throws Exception {
    Map<String, List<String>> createdTablesMap = createBaseDatabaseAndTables();

    // Each time we drop one database, check all databases and their tables.
    for (String databaseName : new ArrayList<>(createdTablesMap.keySet())) {
      // drop one database
      assertTrue(catalog.existDatabase(databaseName));
      catalog.dropDatabase(databaseName);
      createdTablesMap.remove(databaseName);

      // check all tables which belong to other databases
      for (Map.Entry<String, List<String>> entry : createdTablesMap.entrySet()) {
        assertTrue(catalog.existDatabase(entry.getKey()));

        // checking all tables for this database
        Collection<String> tablesForThisDatabase = catalog.getAllTableNames(entry.getKey());
        assertEquals(createdTablesMap.get(entry.getKey()).size(), tablesForThisDatabase.size());
        for (String tableName : tablesForThisDatabase) {
          assertTrue(
              createdTablesMap
                  .get(entry.getKey())
                  .contains(IdentifierUtil.extractSimpleName(tableName)));
        }
      }
    }

    // Finally, default and system database will remain. So, its result is 1.
    assertEquals(2, catalog.getAllDatabaseNames().size());
  }
  @Test
  public void testScanRequestWithROI() throws Exception {

    BoundingBox bbox = new BoundingBox();
    bbox.setFastAxisStart(0);
    bbox.setSlowAxisStart(1);
    bbox.setFastAxisLength(10);
    bbox.setSlowAxisLength(11);

    GridModel gmodel = new GridModel();
    gmodel.setFastAxisName("myFast");
    gmodel.setSlowAxisName("mySlow");
    gmodel.setBoundingBox(bbox);
    gmodel.setFastAxisPoints(3);
    gmodel.setSlowAxisPoints(4);

    CircularROI croi = new CircularROI();
    ScanRequest<IROI> request = new ScanRequest<>();

    CompoundModel cmodel = new CompoundModel();
    cmodel.setData(gmodel, croi);
    request.setCompoundModel(cmodel);

    assertEquals( // Concise.
        "mscan(grid(('myFast', 'mySlow'), (0.0, 1.0), (10.0, 12.0), count=(3, 4), snake=False, roi=circ((0.0, 0.0), 1.0)))",
        pyExpress(request, false));
    assertEquals( // Verbose.
        "mscan(path=[grid(axes=('myFast', 'mySlow'), start=(0.0, 1.0), stop=(10.0, 12.0), count=(3, 4), snake=False, roi=[circ(origin=(0.0, 0.0), radius=1.0)])])",
        pyExpress(request, true));
  }
 @Test
 public void testCreateConceptForm() throws Exception {
   request = new MockHttpServletRequest("GET", "/module/cpm/proposals.list");
   final ModelAndView handle = adapter.handle(request, response, controller);
   assertEquals("/module/cpm/proposals", handle.getViewName());
   assertEquals(200, response.getStatus());
 }
  @Test
  public void testOverride() throws Exception {
    final Response response = target().path("/").request("text/plain").post(Entity.text("content"));

    assertEquals("content", response.readEntity(String.class));
    assertEquals(HEADER_VALUE_SERVER, response.getHeaderString(HEADER_NAME));
  }
  @Test
  public void demoMethodNameMappingExpressionSource() {
    Map<String, String> expressionMap = new HashMap<String, String>();
    expressionMap.put("test", "#return");
    MethodNameMappingPublisherMetadataSource metadataSource =
        new MethodNameMappingPublisherMetadataSource(expressionMap);
    Map<String, String> channelMap = new HashMap<String, String>();
    channelMap.put("test", "c");
    metadataSource.setChannelMap(channelMap);

    Map<String, Map<String, String>> headerExpressionMap =
        new HashMap<String, Map<String, String>>();
    Map<String, String> headerExpressions = new HashMap<String, String>();
    headerExpressions.put("bar", "#return");
    headerExpressions.put("name", "'oleg'");
    headerExpressionMap.put("test", headerExpressions);
    metadataSource.setHeaderExpressionMap(headerExpressionMap);

    MessagePublishingInterceptor interceptor = new MessagePublishingInterceptor(metadataSource);
    interceptor.setBeanFactory(beanFactory);
    interceptor.setChannelResolver(channelResolver);
    ProxyFactory pf = new ProxyFactory(new TestBeanImpl());
    pf.addAdvice(interceptor);
    TestBean proxy = (TestBean) pf.getProxy();
    proxy.test();
    Message<?> message = testChannel.receive(0);
    assertNotNull(message);
    assertEquals("foo", message.getPayload());
    assertEquals("foo", message.getHeaders().get("bar"));
    assertEquals("oleg", message.getHeaders().get("name"));
  }