コード例 #1
0
  @Test
  public void testPollBatch() {
    try {
      ClosableBlockingQueue<String> queue = new ClosableBlockingQueue<>();

      assertNull(queue.pollBatch());

      queue.add("a");
      queue.add("b");

      assertEquals(asList("a", "b"), queue.pollBatch());
      assertNull(queue.pollBatch());

      queue.add("c");

      assertEquals(singletonList("c"), queue.pollBatch());
      assertNull(queue.pollBatch());

      assertTrue(queue.close());

      try {
        queue.pollBatch();
        fail("should cause an exception");
      } catch (IllegalStateException ignored) {
        // expected
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
  private void evictOrRemoveTest(boolean evict) {

    final String KEY = KEY_BASE + testCount++;

    assertNull("local is clean", localAccessStrategy.get(KEY, System.currentTimeMillis()));
    assertNull("remote is clean", remoteAccessStrategy.get(KEY, System.currentTimeMillis()));

    localAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1));
    assertEquals(VALUE1, localAccessStrategy.get(KEY, System.currentTimeMillis()));
    remoteAccessStrategy.putFromLoad(KEY, VALUE1, System.currentTimeMillis(), new Integer(1));
    assertEquals(VALUE1, remoteAccessStrategy.get(KEY, System.currentTimeMillis()));

    // Wait for async propagation
    sleep(250);

    if (evict) {
      localAccessStrategy.evict(KEY);
    } else {
      localAccessStrategy.remove(KEY);
    }

    assertEquals(null, localAccessStrategy.get(KEY, System.currentTimeMillis()));

    assertEquals(null, remoteAccessStrategy.get(KEY, System.currentTimeMillis()));
  }
コード例 #3
0
  @Test
  public void testRemovePut() throws Exception {
    HttpFields header = new HttpFields();

    header.put("name0", "value0");
    header.put("name1", "value1");
    header.put("name2", "value2");

    assertEquals("value0", header.getStringField("name0"));
    assertEquals("value1", header.getStringField("name1"));
    assertEquals("value2", header.getStringField("name2"));

    header.remove("name1");

    assertEquals("value0", header.getStringField("name0"));
    assertNull(header.getStringField("name1"));
    assertEquals("value2", header.getStringField("name2"));
    assertNull(header.getStringField("name3"));

    int matches = 0;
    Enumeration<String> e = header.getFieldNames();
    while (e.hasMoreElements()) {
      Object o = e.nextElement();
      if ("name0".equals(o)) matches++;
      if ("name1".equals(o)) matches++;
      if ("name2".equals(o)) matches++;
    }
    assertEquals(2, matches);

    e = header.getValues("name1");
    assertEquals(false, e.hasMoreElements());
  }
コード例 #4
0
 private void assertVersionNumber(
     HBaseVersion.VersionNumber version,
     Integer expectedMajor,
     Integer expectedMinor,
     Integer expectedPatch,
     String expectedClassifier,
     boolean snapshot) {
   if (expectedMajor == null) {
     assertNull(version.getMajor());
   } else {
     assertEquals(expectedMajor, version.getMajor());
   }
   if (expectedMinor == null) {
     assertNull(version.getMinor());
   } else {
     assertEquals(expectedMinor, version.getMinor());
   }
   if (expectedPatch == null) {
     assertNull(version.getPatch());
   } else {
     assertEquals(expectedPatch, version.getPatch());
   }
   if (expectedClassifier == null) {
     assertNull(version.getClassifier());
   } else {
     assertEquals(expectedClassifier, version.getClassifier());
   }
   assertEquals(snapshot, version.isSnapshot());
 }
コード例 #5
0
ファイル: LocationTest.java プロジェクト: gregb/JCloisterZone
 @Test
 public void intersect() {
   assertEquals(Location.E, Location.E.intersect(Location.E));
   assertNull(Location.E.intersect(Location.W));
   assertEquals(Location.E, Location.WE.intersect(Location.SE));
   assertNull(Location.NW.intersect(Location.NR.union(Location.EL)));
 }
コード例 #6
0
  @Test
  public void testEndpointConsumptionRelations() throws Exception {
    // Create endpoint consumption
    SoaNodeId endpointConsumptionId = new SoaNodeId(EndpointConsumption.DOCTYPE, "MyConsumption");
    DocumentModel endpointConsumptionModel =
        documentService.create(documentManager, endpointConsumptionId);
    EndpointConsumption endpointConsumption =
        endpointConsumptionModel.getAdapter(EndpointConsumption.class);
    Assert.assertNotNull("EndpointConsumption adapter must be available", endpointConsumption);
    documentManager.save();

    // Manipulate and test it
    Assert.assertNull(
        "EndpointConsumption must not initially consume endpoints",
        endpointConsumption.getConsumedEndpoint());
    SoaNodeId consumedEndpoint = new EndpointId("myenv", "myurl");
    endpointConsumption.setConsumedEndpoint(consumedEndpoint);
    Assert.assertEquals(
        "EndpointConsumption must be set as expected",
        consumedEndpoint,
        endpointConsumption.getConsumedEndpoint());
    DocumentModel foundEndpointModel =
        documentService.findSoaNode(documentManager, consumedEndpoint);
    Assert.assertNotNull("Consumed endpoint must be created", foundEndpointModel);
    endpointConsumption.setConsumedEndpoint(null);
    Assert.assertNull(
        "EndpointConsumption must be removed", endpointConsumption.getConsumedEndpoint());
  }
コード例 #7
0
 private static void assertQueueEmpty(PendingWriteQueue queue) {
   Assert.assertTrue(queue.isEmpty());
   Assert.assertEquals(0, queue.size());
   Assert.assertNull(queue.current());
   Assert.assertNull(queue.removeAndWrite());
   Assert.assertNull(queue.removeAndWriteAll());
 }
コード例 #8
0
  @Test
  public void testMoveKeyTask() {
    if (I18nModule.isTransToolEnabled()) {
      prepareDevToolTests();
      Locale testLocale = i18nMgr.getLocaleOrDefault("de");
      String ktm = "key.to.move";
      i18nMgr.setCachingEnabled(true);
      Properties sourcePropResolved = i18nMgr.getResolvedProperties(testLocale, testSourceBundle);
      Properties sourceProp =
          i18nMgr.getPropertiesWithoutResolvingRecursively(testLocale, testSourceBundle);
      String matchString = sourceProp.getProperty(ktm);
      assertTrue(sourcePropResolved.getProperty("key.to.stay2").indexOf(matchString) != -1);

      tDMgr.moveKeyToOtherBundle(testSourceBundle, testTargetBundle, ktm);
      sourceProp = i18nMgr.getPropertiesWithoutResolvingRecursively(testLocale, testSourceBundle);
      Properties targetProp =
          i18nMgr.getPropertiesWithoutResolvingRecursively(testLocale, testTargetBundle);
      assertNull(sourceProp.getProperty(ktm));
      assertNotNull(targetProp.getProperty(ktm));
      Properties sourceMetaProp =
          i18nMgr.getPropertiesWithoutResolvingRecursively(null, testSourceBundle);
      Properties targetMetaProp =
          i18nMgr.getPropertiesWithoutResolvingRecursively(null, testTargetBundle);
      assertNull(sourceMetaProp.getProperty(ktm + I18nManager.METADATA_ANNOTATION_POSTFIX));
      assertNull(sourceMetaProp.getProperty(ktm + I18nManager.METADATA_KEY_PRIORITY_POSTFIX));
      assertTrue(targetMetaProp.containsKey(ktm + I18nManager.METADATA_ANNOTATION_POSTFIX));
      assertEquals(
          "100", targetMetaProp.getProperty(ktm + I18nManager.METADATA_KEY_PRIORITY_POSTFIX));
      // check for changed references in value
      // if correctly done, should still be resolvable
      assertTrue(sourcePropResolved.getProperty("key.to.stay2").indexOf(matchString) != -1);
      tDMgr.logToFile("moveKey");
    }
  }
コード例 #9
0
 @Test
 public void testGetProfileFirstTime() throws Exception {
   Profile profile = ofy().load().key(Key.create(Profile.class, user.getUserId())).now();
   assertNull(profile);
   profile = conferenceApi.getProfile(user);
   assertNull(profile);
 }
コード例 #10
0
  @Test
  public void cannotAddExternalGroupsThatDoNotExist() throws Exception {
    Set<String> externalGroupSet = new HashSet<>();
    externalGroupSet.add(
        "acme1|   cn=Engineering,ou=groups,dc=example,dc=com cn=HR,ou=groups,dc=example,dc=com   cn=mgmt,ou=groups,dc=example,dc=com");
    externalGroupSet.add("acme1.dev|cn=Engineering,ou=groups,dc=example,dc=com");
    bootstrap.setExternalGroupMap(externalGroupSet);
    bootstrap.afterPropertiesSet();
    assertEquals(
        0,
        eDB.getExternalGroupMapsByExternalGroup(
                "cn=Engineering,ou=groups,dc=example,dc=com", Origin.LDAP)
            .size());
    assertEquals(
        0,
        eDB.getExternalGroupMapsByExternalGroup("cn=HR,ou=groups,dc=example,dc=com", Origin.LDAP)
            .size());
    assertEquals(
        0,
        eDB.getExternalGroupMapsByExternalGroup("cn=mgmt,ou=groups,dc=example,dc=com", Origin.LDAP)
            .size());

    assertNull(eDB.getExternalGroupMapsByGroupName("acme1", Origin.LDAP));
    assertNull(eDB.getExternalGroupMapsByGroupName("acme1.dev", Origin.LDAP));
  }
コード例 #11
0
  /*
   * In order to test this specific scenario, we use Byteman to insert a monitor in the specific moment
   *  where the transition from STOP_REQUESTED to the next state is going to occur.
   *  This monitor will force the thread to wait until upperCount is incremented to 1.
   */
  @Test
  public void test() throws Exception {
    ServiceName serviceName = ServiceName.of("service");
    TestServiceListener serviceListener = new TestServiceListener();

    // install service as usual
    Future<ServiceController<?>> serviceStart = serviceListener.expectServiceStart(serviceName);
    serviceContainer.addService(serviceName, Service.NULL).addListener(serviceListener).install();
    ServiceController<?> serviceController = assertController(serviceName, serviceStart);

    Future<ServiceController<?>> serviceStopping =
        serviceListener.expectNoServiceStopping(serviceName);
    Future<ServiceController<?>> serviceStop = serviceListener.expectNoServiceStop(serviceName);
    serviceStart = serviceListener.expectNoServiceStart(serviceName);
    // set the mode to NEVER, so that serviceController enters STOP_REQUESTED state
    serviceController.setMode(ServiceController.Mode.NEVER);
    // set the mode to ACTIVE, so that serviceController transitions to UP state
    serviceController.setMode(ServiceController.Mode.ACTIVE);
    // no notifications are expected
    assertNull(serviceStop.get());
    assertNull(serviceStopping.get());
    assertNull(serviceStart.get());
    // service should still be in the up state
    assertSame(ServiceController.State.UP, serviceController.getState());
  }
コード例 #12
0
 @Test
 public void testDataDropDown() {
   assertNull(DropDownData.create(null));
   assertNull(DropDownData.create(null, null));
   assertNotNull(DropDownData.create(new String[] {"hey"}));
   assertNotNull(DropDownData.create("abc", new String[] {"hey"}));
 }
コード例 #13
0
ファイル: TestSpecimen.java プロジェクト: cbsrbiobank/biobank
  @Test
  public void testSetQuantityFromType() throws Exception {
    SpecimenTypeWrapper type = parentSpc.getSpecimenType();
    Assert.assertNull(parentSpc.getQuantity());

    parentSpc.setSpecimenType(null);
    parentSpc.setQuantityFromType();
    // no specimen type, no change
    Assert.assertNull(parentSpc.getQuantity());

    parentSpc.setSpecimenType(type);
    parentSpc.setQuantityFromType();
    // no aliquotedspecimen with this type in study, no change
    Assert.assertNull(parentSpc.getQuantity());

    StudyWrapper study = parentSpc.getCollectionEvent().getPatient().getStudy();
    AliquotedSpecimenWrapper as =
        AliquotedSpecimenHelper.addAliquotedSpecimen(study, parentSpc.getSpecimenType());
    study.reload();
    Assert.assertNotNull(as.getVolume());
    Assert.assertTrue(!as.getVolume().equals(BigDecimal.ZERO));

    parentSpc.setQuantityFromType();

    Assert.assertTrue(as.getVolume().equals(parentSpc.getQuantity()));
  }
コード例 #14
0
ファイル: TestEntity.java プロジェクト: ClickerMonkey/Ents
  @Test
  public void testExpireAndDelete() {
    assertEquals(0, EXTENT.getInstances());

    Entity e = new Entity(EXTENT);

    assertEquals(1, EXTENT.getInstances());

    assertFalse(e.isExpired());
    assertNotNull(e.getTemplate());
    assertNotNull(e.getRenderer());

    e.expire();

    assertTrue(e.isExpired());

    assertNotNull(e.getTemplate());
    assertNotNull(e.getRenderer());

    e.delete();

    assertNull(e.getTemplate());
    assertNull(e.getRenderer());

    assertEquals(0, EXTENT.getInstances());

    e.delete();

    assertTrue(e.isExpired());
    assertNull(e.getTemplate());
    assertNull(e.getRenderer());

    assertEquals(0, EXTENT.getInstances());
  }
コード例 #15
0
  @Test
  public void get_with_hashingStrategy() {
    UnifiedSetWithHashingStrategy<Person> people =
        UnifiedSetWithHashingStrategy.newSet(
                HashingStrategies.nullSafeHashingStrategy(LAST_NAME_HASHING_STRATEGY), 2)
            .withAll(PEOPLE.castToList());

    // Putting null then testing geting a null
    Verify.assertSize(3, people.with((Person) null));
    Assert.assertNull(people.get(null));

    // Testing it is getting the same reference
    Assert.assertSame(JOHNSMITH, people.get(JANESMITH));
    Assert.assertSame(JOHNSMITH, people.get(JOHNSMITH));
    Assert.assertSame(JOHNDOE, people.get(JANEDOE));
    Assert.assertSame(JOHNDOE, people.get(JOHNDOE));

    Assert.assertSame(JOHNSMITH, people.get(new Person("Anything", "Smith")));
    Assert.assertNull(people.get(new Person("John", "NotHere")));

    // Testing get throws NullPointerException if the hashingStrategy is not null safe
    Verify.assertThrows(
        NullPointerException.class,
        () -> {
          UnifiedSetWithHashingStrategy.newSet(LAST_NAME_HASHING_STRATEGY).get(null);
        });
  }
コード例 #16
0
  // ----------------------------- load 1 object ----------------------------
  @Test
  public void testLoadPojoWithId() {
    try {
      Representation mockRep = RepresentationFactory.createLightweightRepresentation();
      AbstractPojo loadedPojo = papi.loadPojo(mockRepresentationId);
      Representation loadedRep = (Representation) loadedPojo;
      assertEquals(loadedRep.getDbId(), mockRepresentationId);
      assertEquals(loadedRep.getTitle(), mockRep.getTitle());

      // not existent
      AbstractPojo p1 = papi.loadPojo("#-1:-1");
      assertNull(p1);
      AbstractPojo p2 = papi.loadPojo(NonExistentClusterId);
      assertNull(p2);
    } catch (Exception e) {
      fail(e.getMessage());
    }

    // wrong input
    try {
      papi.loadPojo(AbcId);
      fail();
    } catch (IllegalArgumentException e) {
      assert (true);
    }
  }
コード例 #17
0
  @Test
  public void null_behavior() {
    UnifiedSetWithHashingStrategy<Integer> unifiedSet =
        UnifiedSetWithHashingStrategy.newSet(INTEGER_HASHING_STRATEGY, 8).withAll(MORE_COLLISIONS);
    MORE_COLLISIONS
        .clone()
        .reverseForEach(
            each -> {
              Assert.assertTrue(unifiedSet.add(null));
              Assert.assertFalse(unifiedSet.add(null));
              Verify.assertContains(null, unifiedSet);
              Verify.assertPostSerializedEqualsAndHashCode(unifiedSet);

              Assert.assertTrue(unifiedSet.remove(null));
              Assert.assertFalse(unifiedSet.remove(null));
              Verify.assertNotContains(null, unifiedSet);

              Verify.assertPostSerializedEqualsAndHashCode(unifiedSet);

              Assert.assertNull(unifiedSet.put(null));
              Assert.assertNull(unifiedSet.put(null));
              Assert.assertNull(unifiedSet.removeFromPool(null));
              Assert.assertNull(unifiedSet.removeFromPool(null));

              Verify.assertContains(each, unifiedSet);
              Assert.assertTrue(unifiedSet.remove(each));
              Assert.assertFalse(unifiedSet.remove(each));
              Verify.assertNotContains(each, unifiedSet);
            });
  }
コード例 #18
0
  @Test
  public void testLoadCompleteModelWithDbId() {
    try {
      Model mockModel = ModelFactory.createModelWithMultipleLinks();
      Model loadedModel = papi.loadCompleteModelWithDbId(mockModelId);
      assertNotNull(loadedModel);
      assertEquals(loadedModel.getDbId(), mockModelId);
      assertEquals(loadedModel.getTitle(), mockModel.getTitle());
      assertEquals(loadedModel.getImportedId(), mockModel.getImportedId());
      assertEquals(loadedModel.getOrigin(), mockModel.getOrigin());
      assertEquals(
          loadedModel.getLatestRevision().getRevisionNumber(),
          mockModel.getLatestRevision().getRevisionNumber());
      assertEquals(loadedModel.getNrOfRevisions(), mockModel.getNrOfRevisions());
      assertEquals(loadedModel.getNrOfRepresentations(), mockModel.getNrOfRepresentations());
      loadedModel.toStringExtended();

      // not existent
      Model m1 = papi.loadCompleteModelWithDbId(NonExistentClusterId);
      assertNull(m1);
      Model m2 = papi.loadCompleteModelWithDbId(wrongModId);
      assertNull(m2);

    } catch (Exception e) {
      fail(e.getMessage());
    }

    // wrong input
    try {
      papi.loadCompleteModelWithDbId(AbcId);
      fail();
    } catch (IllegalArgumentException e) {
      assert (true);
    }
  }
  @Test
  public void testServerSideOnlyInfo() throws Exception {
    GetMapConfigurationRequest request = new GetMapConfigurationRequest();
    request.setApplicationId("appServerSideOnly");
    request.setMapId("mapServerSideOnly");
    GetMapConfigurationResponse response =
        (GetMapConfigurationResponse)
            dispatcher.execute(GetMapConfigurationRequest.COMMAND, request, null, "en");
    if (response.isError()) {
      response.getErrors().get(0).printStackTrace();
    }
    Assert.assertFalse(response.isError());
    ClientMapInfo mapInfo = response.getMapInfo();
    Assert.assertNotNull(mapInfo);

    // user data
    ClientUserDataInfo info = mapInfo.getUserData();
    Assert.assertNull(info);

    // widget data
    Assert.assertNotNull(mapInfo.getWidgetInfo());
    Assert.assertNull(mapInfo.getWidgetInfo("appDummy")); // not present
    Assert.assertNotNull(mapInfo.getWidgetInfo("layerTree")); // present
    Assert.assertNull(mapInfo.getWidgetInfo("mapDummy")); // filtered because ServerSideOnlyInfo

    // ViewBounds LimitOption
    Assert.assertEquals(
        BoundsLimitOption.COMPLETELY_WITHIN_MAX_BOUNDS, mapInfo.getViewBoundsLimitOption());
  }
コード例 #20
0
  @Test
  public void testLoadRepresentation() {
    try {
      Representation mockRep = RepresentationFactory.createLightweightRepresentation();
      Representation loadedRep = papi.loadRepresentation(mockRepresentationId);
      assertNotNull(loadedRep);
      assertEquals(loadedRep.getDbId(), mockRepresentationId);
      assertEquals(loadedRep.getDataContent().length, mockRep.getDataContent().length);
      assertEquals(loadedRep.getFormat(), mockRep.getFormat());
      assertEquals(loadedRep.getNotation(), mockRep.getNotation());
      assertEquals(loadedRep.getOriginalFilePath(), mockRep.getOriginalFilePath());
      assertEquals(loadedRep.getRevisionNumber(), mockRep.getRevisionNumber());
      assertEquals(loadedRep.getTitle(), mockRep.getTitle());
      assertEquals(loadedRep.belongsToLatestRevision(), mockRep.belongsToLatestRevision());

      // not existent
      Representation r1 = papi.loadRepresentation(NonExistentClusterId);
      assertNull(r1);
      Representation r2 = papi.loadRepresentation(wrongRepId);
      assertNull(r2);

    } catch (Exception e) {
      fail("error: testLoad " + e.getMessage());
    }

    // wrong input
    try {
      papi.loadRepresentation(AbcId);
      fail();
    } catch (IllegalArgumentException e) {
      assert (true);
    }
  }
コード例 #21
0
  @Test
  public void testRemoveAndWriteAllReentrance() {
    EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
    final PendingWriteQueue queue = new PendingWriteQueue(channel.pipeline().firstContext());

    ChannelPromise promise = channel.newPromise();
    promise.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            queue.removeAndWriteAll();
          }
        });
    queue.add(1L, promise);

    ChannelPromise promise2 = channel.newPromise();
    queue.add(2L, promise2);
    queue.removeAndWriteAll();
    channel.flush();
    assertTrue(promise.isSuccess());
    assertTrue(promise2.isSuccess());
    assertTrue(channel.finish());

    assertEquals(1L, channel.readOutbound());
    assertEquals(2L, channel.readOutbound());
    assertNull(channel.readOutbound());
    assertNull(channel.readInbound());
  }
コード例 #22
0
  @Test
  public void testExceptions() throws Exception {
    KatharsisInvokerException ex =
        new KatharsisInvokerException(HttpServletResponse.SC_BAD_REQUEST);
    assertTrue(ex instanceof RuntimeException);
    assertEquals(HttpServletResponse.SC_BAD_REQUEST, ex.getStatusCode());
    assertNull(ex.getCause());
    assertNull(ex.getMessage());
    assertNotNull(ex.toString());

    ex = new KatharsisInvokerException(HttpServletResponse.SC_BAD_REQUEST, "Invocation failed.");
    assertEquals(HttpServletResponse.SC_BAD_REQUEST, ex.getStatusCode());
    assertNull(ex.getCause());
    assertEquals("Invocation failed.", ex.getMessage());
    assertNotNull(ex.toString());

    ex =
        new KatharsisInvokerException(
            HttpServletResponse.SC_BAD_REQUEST, new Exception("Root cause."));
    assertEquals(HttpServletResponse.SC_BAD_REQUEST, ex.getStatusCode());
    assertNotNull(ex.getCause());
    assertEquals("Root cause.", ex.getCause().getMessage());
    assertNotNull(ex.toString());

    ex =
        new KatharsisInvokerException(
            HttpServletResponse.SC_BAD_REQUEST, "Invocation failed.", new Exception("Root cause."));
    assertEquals(HttpServletResponse.SC_BAD_REQUEST, ex.getStatusCode());
    assertNotNull(ex.getCause());
    assertEquals("Root cause.", ex.getCause().getMessage());
    assertEquals("Invocation failed.", ex.getMessage());
    assertNotNull(ex.toString());
  }
コード例 #23
0
  @Test
  public void testUpdateWithConditionalUrl() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost =
        new HttpPut("http://localhost:" + ourPort + "/Patient?identifier=system%7C001");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("location").getValue());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("content-location").getValue());

    assertNull(ourLastId);
    assertNull(ourLastIdParam);
    assertEquals("Patient?identifier=system%7C001", ourLastConditionalUrl);
  }
コード例 #24
0
ファイル: DBTest.java プロジェクト: pombredanne/featherdb
  @Test
  public void testCommonUpdate() {
    try {
      if (backend.doesDocumentExist("foodb", "common")) {
        backend.deleteDocument("foodb", "common");
      }
      JSONDocument d =
          (JSONDocument) Document.newDocument(db.getBackend(), "foodb", "common", "unittest");
      d.put("foo", "bar");
      d.getCommonData().put("_commonfoo", "bar");
      d = (JSONDocument) db.getBackend().saveDocument(d);
      String rev = d.getRevision();

      // d = (JSONDocument) Document.newRevision(db.getBackend(), d);
      d.getCommonData().put("_commonfoo", "baz");
      d = (JSONDocument) db.getBackend().saveDocument(d);
      assertEquals(rev, d.getRevision());

      Document current = db.getBackend().getDocument("foodb", "common");
      assertEquals(current.getRevision(), rev);
      assertTrue(db.getBackend().getDocumentRevisions("foodb", "common").length() == 1);

    } catch (BackendException e) {
      e.printStackTrace();
      assertNull(e);
    } catch (DocumentCreationException e) {
      e.printStackTrace();
      assertNull(e);
    }
  }
コード例 #25
0
  @Test
  public void withFieldAliases() {
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("qf", "title^0.4 comment^0.40 date^1.0");
    parameters.put("xwiki.multilingualFields", "title, property.*, foo, comment");
    parameters.put("xwiki.supportedLocales", "en, fr, zh_TW");
    parameters.put("xwiki.typedDynamicFields", "property.*");
    parameters.put("xwiki.dynamicFieldTypes", "boolean, int");

    String query =
        "title:text AND x:y AND property.Blog.BlogPostClass.summary:wiki AND title_ro:value";
    SolrParams paramsWithAliases = plugin.withFieldAliases(query, new MapSolrParams(parameters));

    assertEquals("title__ title_en title_fr title_zh_TW", paramsWithAliases.get("f.title.qf"));
    assertEquals(
        "property.Blog.BlogPostClass.summary__ property.Blog.BlogPostClass.summary_en "
            + "property.Blog.BlogPostClass.summary_fr property.Blog.BlogPostClass.summary_zh_TW "
            + "property.Blog.BlogPostClass.summary_boolean property.Blog.BlogPostClass.summary_int",
        paramsWithAliases.get("f.property.Blog.BlogPostClass.summary.qf"));

    // Event if this field doesn't appear in the query, it's a default field so it has to have the
    // alias.
    assertEquals(
        "comment__ comment_en comment_fr comment_zh_TW", paramsWithAliases.get("f.comment.qf"));

    // These fields are not declared as multilingual.
    assertNull(paramsWithAliases.get("f.x.qf"));
    assertNull(paramsWithAliases.get("f.title_ro.qf"));

    // This is a default field but it's not declared as multilingual.
    assertNull(paramsWithAliases.get("f.date.qf"));

    // This multilingual field doesn't appear in the query and it's not a default field either.
    assertNull(paramsWithAliases.get("f.foo.qf"));
  }
コード例 #26
0
  @Test
  public void testAuthenticatesWithAppHandle() {
    user =
        createUser(
            TEST_VISTA_ID,
            TEST_DIVISION,
            TEST_DUZ,
            TEST_REMOTE_HOSTNAME + "(" + TEST_REMOTE_ADDRESS + ")" + TEST_APP_HANDLE,
            true,
            true,
            true,
            true,
            new SimpleGrantedAuthority("ROLE_ONE"),
            new SimpleGrantedAuthority("ROLE_TWO"));
    when(mockUserDetailService.login(
            TEST_VISTA_ID,
            TEST_DIVISION,
            TEST_APP_HANDLE,
            TEST_REMOTE_ADDRESS,
            TEST_REMOTE_HOSTNAME))
        .thenReturn(user);

    VistaAuthenticationToken token =
        new VistaAuthenticationToken(
            TEST_VISTA_ID,
            TEST_DIVISION,
            TEST_APP_HANDLE,
            TEST_REMOTE_ADDRESS,
            TEST_REMOTE_HOSTNAME);
    Authentication result = provider.authenticate(token);

    if (!(result instanceof VistaAuthenticationToken)) {
      fail("Should have returned instance of VistaAuthenticationToken");
    }
    assertNotSame(token, result);

    VistaAuthenticationToken castResult = (VistaAuthenticationToken) result;
    assertTrue(VistaUserDetails.class.isAssignableFrom(castResult.getPrincipal().getClass()));
    assertEquals(TEST_VISTA_ID, castResult.getVistaId());
    assertNull(castResult.getAccessCode());
    assertNull(castResult.getVerifyCode());
    assertEquals(TEST_APP_HANDLE, castResult.getAppHandle());
    assertEquals(TEST_REMOTE_ADDRESS, castResult.getRemoteAddress());
    assertEquals(TEST_REMOTE_HOSTNAME, castResult.getRemoteHostName());
    assertEquals(
        "ROLE_ONE",
        new ArrayList<GrantedAuthority>(castResult.getAuthorities()).get(0).getAuthority());
    assertEquals(
        "ROLE_TWO",
        new ArrayList<GrantedAuthority>(castResult.getAuthorities()).get(1).getAuthority());
    assertEquals(TEST_REMOTE_HOSTNAME + "(" + TEST_REMOTE_ADDRESS + ")", castResult.getDetails());

    verify(mockUserDetailService)
        .login(
            TEST_VISTA_ID,
            TEST_DIVISION,
            TEST_APP_HANDLE,
            TEST_REMOTE_ADDRESS,
            TEST_REMOTE_HOSTNAME);
  }
  @Test
  public void withHeaderMapperDefaultMapping() {
    AmqpInboundChannelAdapter adapter =
        context.getBean("withHeaderMapperDefaultMapping", AmqpInboundChannelAdapter.class);

    AbstractMessageListenerContainer mlc =
        TestUtils.getPropertyValue(
            adapter, "messageListenerContainer", AbstractMessageListenerContainer.class);
    MessageListener listener =
        TestUtils.getPropertyValue(mlc, "messageListener", MessageListener.class);
    MessageProperties amqpProperties = new MessageProperties();
    amqpProperties.setAppId("test.appId");
    amqpProperties.setClusterId("test.clusterId");
    amqpProperties.setContentEncoding("test.contentEncoding");
    amqpProperties.setContentLength(99L);
    amqpProperties.setContentType("test.contentType");
    amqpProperties.setHeader("foo", "foo");
    amqpProperties.setHeader("bar", "bar");
    Message amqpMessage = new Message("hello".getBytes(), amqpProperties);
    listener.onMessage(amqpMessage);
    QueueChannel requestChannel = context.getBean("requestChannel", QueueChannel.class);
    org.springframework.integration.Message<?> siMessage = requestChannel.receive(0);
    assertNull(siMessage.getHeaders().get("bar"));
    assertNull(siMessage.getHeaders().get("foo"));
    assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_ENCODING));
    assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CLUSTER_ID));
    assertNotNull(siMessage.getHeaders().get(AmqpHeaders.APP_ID));
    assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE));
  }
コード例 #28
0
  @Test
  public void get() {
    UnifiedSetWithHashingStrategy<Integer> set =
        UnifiedSetWithHashingStrategy.newSet(INTEGER_HASHING_STRATEGY, SIZE).withAll(COLLISIONS);
    set.removeAll(COLLISIONS);
    for (Integer integer : COLLISIONS) {
      Assert.assertNull(set.get(integer));
      Assert.assertNull(set.get(null));
      set.add(integer);
      //noinspection UnnecessaryBoxing,CachedNumberConstructorCall,BoxingBoxedValue
      Assert.assertSame(integer, set.get(new Integer(integer)));
    }
    Assert.assertEquals(COLLISIONS.toSet(), set);

    // the pool interface supports getting null keys
    UnifiedSetWithHashingStrategy<Integer> chainedWithNull =
        UnifiedSetWithHashingStrategy.newSetWith(INTEGER_HASHING_STRATEGY, null, COLLISION_1);
    Verify.assertContains(null, chainedWithNull);
    Assert.assertNull(chainedWithNull.get(null));

    // getting a non-existent from a chain with one slot should short-circuit to return null
    UnifiedSetWithHashingStrategy<Integer> chainedWithOneSlot =
        UnifiedSetWithHashingStrategy.newSetWith(
            INTEGER_HASHING_STRATEGY, COLLISION_1, COLLISION_2);
    chainedWithOneSlot.remove(COLLISION_2);
    Assert.assertNull(chainedWithOneSlot.get(COLLISION_2));
  }
コード例 #29
0
 @Test
 public void testCSVTable() throws IOException {
   CSVDataReference inMemory = referenceTable;
   CSVDataReference urlCon = new CSVDataLocation(url, null, true, null, true);
   try (CSVDataConnection refCon = inMemory.openConnection();
       CSVDataConnection testCon = urlCon.openConnection()) {
     int count = 0;
     do {
       CSVRecord reference = refCon.readNext();
       CSVRecord test = testCon.readNext();
       if (reference == null) {
         Assert.assertNull(test);
         break;
       } else if (test == null) {
         Assert.assertNull(reference);
         break;
       } else {
         count++;
         Assert.assertNotSame(reference, test);
         Assert.assertEquals(reference, test);
       }
     } while (true);
     Assert.assertEquals(37, count);
   }
 }
  @Test
  public void testPublisherConfirmReceivedTwoTemplates() throws Exception {
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    templateWithConfirmsEnabled.setConfirmCallback(
        new ConfirmCallback() {

          @Override
          public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            latch1.countDown();
          }
        });
    templateWithConfirmsEnabled.convertAndSend(
        ROUTE, (Object) "message", new CorrelationData("abc"));
    RabbitTemplate secondTemplate = new RabbitTemplate(connectionFactoryWithConfirmsEnabled);
    secondTemplate.setConfirmCallback(
        new ConfirmCallback() {

          @Override
          public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            latch2.countDown();
          }
        });
    secondTemplate.convertAndSend(ROUTE, (Object) "message", new CorrelationData("def"));
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    assertNull(templateWithConfirmsEnabled.getUnconfirmed(-1));
    assertNull(secondTemplate.getUnconfirmed(-1));
  }