예제 #1
0
  public void testUpdateDeltaOnly() throws Exception {
    // local root with just a base in it
    makeLocalFile("00005.base.cueball");

    MockFetcher fetcher = new MockFetcher(LOCAL_ROOT, "00006.delta.cueball", "00007.delta.cueball");
    MockCueballMerger merger = new MockCueballMerger();
    CueballUpdater updater =
        new CueballUpdater(LOCAL_ROOT, 12, 5, fetcher, merger, new NoCompressionCodec(), 1);

    updater.update(7, Collections.singleton(45));

    // make sure fetcher got the right args
    assertEquals(5, fetcher.latestLocalVersion);
    assertEquals(Collections.singleton(45), fetcher.excludeVersions);

    // make sure the merger got the right args
    assertEquals(LOCAL_ROOT + "/00005.base.cueball", merger.latestBase);
    assertEquals(
        new HashSet<String>(
            Arrays.asList(
                LOCAL_ROOT + "/00006.delta.cueball", LOCAL_ROOT + "/00007.delta.cueball")),
        merger.deltas);
    assertEquals(12, merger.keyHashSize);
    assertEquals(5, merger.valueSize);
    assertEquals(LOCAL_ROOT + "/00007.base.cueball", merger.newBasePath);

    // make sure that the mock base created by the merger still exists
    assertTrue(localFileExists("/00007.base.cueball"));
    // old base should be deleted
    assertFalse(localFileExists("/00005.base.cueball"));
    // delta that was fetched should be deleted
    assertFalse(localFileExists(LOCAL_ROOT + "/00006.delta.cueball"));
    assertFalse(localFileExists(LOCAL_ROOT + "/00007.delta.cueball"));
  }
  @Test
  public void ensureRecordsTest() {
    int empId = 11303;
    List<PayPeriod> payPeriods =
        periodService.getOpenPayPeriods(PayPeriodType.AF, empId, SortOrder.ASC);
    // Print existing records
    Set<TimeRecord> existingRecords =
        timeRecordService
            .getTimeRecords(Collections.singleton(empId), payPeriods, TimeRecordStatus.getAll())
            .stream()
            .map(TimeRecord::new)
            .collect(Collectors.toSet());
    logger.info("-------- EXISTING RECORDS --------");
    printRecords(existingRecords);

    Stopwatch sw = Stopwatch.createStarted();
    // Generate records
    manager.ensureRecords(empId);
    logger.info("generation took {} ms", sw.stop().elapsed(TimeUnit.MILLISECONDS));

    // Print difference
    Set<TimeRecord> newRecords =
        new TreeSet<>(
            timeRecordService.getTimeRecords(
                Collections.singleton(empId), payPeriods, TimeRecordStatus.getAll()));
    logger.info("-------- NEW RECORDS --------");
    printRecords(Sets.difference(newRecords, existingRecords));
  }
예제 #3
0
 @Test
 public void testPowerSetOfThreeElementsHasCorrectSubsets() {
   LongSet<Set<String>> powerSet =
       LongPowerSet.create(new HashSet<>(Arrays.asList("a", "b", "c")));
   assertEquals("expect 8 subsets in the power set of a 3 element set", 8, powerSet.longSize());
   Set<Set<String>> constructedSet = new HashSet<>();
   for (Set<String> subset : powerSet) {
     constructedSet.add(subset);
   }
   Set<String> emptySet = Collections.emptySet();
   Set<String> singleElementSet1 = Collections.singleton("a");
   Set<String> singleElementSet2 = Collections.singleton("b");
   Set<String> singleElementSet3 = Collections.singleton("c");
   Set<String> twoElementSet1 = new HashSet<>(Arrays.asList("a", "b"));
   Set<String> twoElementSet2 = new HashSet<>(Arrays.asList("a", "c"));
   Set<String> twoElementSet3 = new HashSet<>(Arrays.asList("b", "c"));
   Set<String> threeElementSet = new HashSet<>(Arrays.asList("a", "b", "c"));
   Set<Set<String>> expectedSet =
       new HashSet<>(
           Arrays.asList(
               emptySet,
               singleElementSet1,
               singleElementSet2,
               singleElementSet3,
               twoElementSet1,
               twoElementSet2,
               twoElementSet3,
               threeElementSet));
   assertEquals(
       "expect iterated contents of power set to be correct", expectedSet, constructedSet);
   assertTrue("expect power set to contain correct subsets", powerSet.containsAll(expectedSet));
 }
예제 #4
0
  /**
   * Put cas authentication attributes into model.
   *
   * @param model the model
   * @param registeredService the registered service
   * @return the cas authentication attributes
   */
  protected Map<String, Object> getCasProtocolAuthenticationAttributes(
      final Map<String, Object> model, final RegisteredService registeredService) {

    final Map<String, Object> filteredAuthenticationAttributes =
        new HashMap<>(getAuthenticationAttributes(model));

    filteredAuthenticationAttributes.put(
        CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_AUTHENTICATION_DATE,
        Collections.singleton(getAuthenticationDate(model)));
    filteredAuthenticationAttributes.put(
        CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_FROM_NEW_LOGIN,
        Collections.singleton(isAssertionBackedByNewLogin(model)));
    filteredAuthenticationAttributes.put(
        CasProtocolConstants.VALIDATION_REMEMBER_ME_ATTRIBUTE_NAME,
        Collections.singleton(isRememberMeAuthentication(model)));

    final Optional<MultifactorAuthenticationProvider> contextProvider =
        getSatisfiedMultifactorAuthenticationProvider(model);
    if (contextProvider.isPresent() && StringUtils.isNotBlank(authenticationContextAttribute)) {
      filteredAuthenticationAttributes.put(
          this.authenticationContextAttribute,
          Collections.singleton(contextProvider.get().getId()));
    }

    return filteredAuthenticationAttributes;
  }
    protected void merge(
        VariantGraph into,
        Iterable<Token> witnessTokens,
        Map<Token, VariantGraphVertex> alignments) {
      Preconditions.checkArgument(!Iterables.isEmpty(witnessTokens), "Empty witness");
      final Witness witness = Iterables.getFirst(witnessTokens, null).getWitness();

      LOG.debug("{} + {}: Merge comparand into graph", into, witness);
      witnessTokenVertices = Maps.newHashMap();
      VariantGraphVertex last = into.getStart();
      final Set<Witness> witnessSet = Collections.singleton(witness);
      for (Token token : witnessTokens) {
        VariantGraphVertex matchingVertex = alignments.get(token);
        if (matchingVertex == null) {
          matchingVertex = into.add(token);
        } else {
          if (LOG.isTraceEnabled()) {
            LOG.trace("Adding matched {} to {}", token, matchingVertex);
          }
          matchingVertex.add(Collections.singleton(token));
        }
        witnessTokenVertices.put(token, matchingVertex);

        into.connect(last, matchingVertex, witnessSet);
        last = matchingVertex;
      }
      into.connect(last, into.getEnd(), witnessSet);
    }
예제 #6
0
  public void testPreferenceDependencies() throws RaplaException {
    Allocatable allocatable = facade.newResource();
    facade.store(allocatable);

    CalendarSelectionModel calendar = facade.newCalendarModel(facade.getUser());
    calendar.setSelectedObjects(Collections.singleton(allocatable));
    calendar.setViewId(WeekViewFactory.WEEK_VIEW);
    CalendarModelConfiguration config = ((CalendarModelImpl) calendar).createConfiguration();

    RaplaMap<CalendarModelConfiguration> calendarList =
        facade.newRaplaMap(Collections.singleton(config));

    Preferences preferences = facade.getPreferences();
    Preferences editPref = facade.edit(preferences);
    TypedComponentRole<RaplaMap<CalendarModelConfiguration>> TEST_ENTRY =
        new TypedComponentRole<RaplaMap<CalendarModelConfiguration>>("TEST");
    editPref.putEntry(TEST_ENTRY, calendarList);
    facade.store(editPref);
    try {
      facade.remove(allocatable);
      fail("DependencyException should have thrown");
    } catch (DependencyException ex) {
    }

    calendarList = facade.newRaplaMap(new ArrayList<CalendarModelConfiguration>());
    editPref = facade.edit(preferences);
    editPref.putEntry(TEST_ENTRY, calendarList);
    facade.store(editPref);

    facade.remove(allocatable);
  }
예제 #7
0
 public EndNodesCollector(
     final Node start,
     final Node end,
     final ProjectRelationshipFilter filter,
     final boolean checkExistence) {
   this(Collections.singleton(start), Collections.singleton(end), filter, checkExistence);
 }
  public void testSetOnlineUsers_UpdateEvent() throws Exception {
    myTransport.setOnlineUsers(new HashSet<User>());

    User user =
        myTransport.createUser(
            "someUser", new OnlineUserInfo(null, 0, null, new UserPresence(PresenceMode.AWAY)));
    myTransport.setOnlineUsers(Collections.singleton(user));

    addEventListener();

    user =
        myTransport.createUser(
            "someUser", new OnlineUserInfo(null, 0, null, new UserPresence(PresenceMode.AWAY)));
    myTransport.setOnlineUsers(Collections.singleton(user));

    assertEquals("Same user data, no events expected: " + myEvents, 0, myEvents.size());

    user =
        myTransport.createUser(
            "someUser",
            new OnlineUserInfo(null, 0, null, new UserPresence(PresenceMode.EXTENDED_AWAY)));
    myTransport.setOnlineUsers(Collections.singleton(user));

    UserEvent.Updated event = (UserEvent.Updated) checkEvent(true);
    assertEquals("Precense changed: " + myEvents, "presence", event.getPropertyName());
  }
예제 #9
0
    public ErrorClassDescriptor(@Nullable String name) {
      super(
          getErrorModule(),
          Name.special(name == null ? "<ERROR CLASS>" : "<ERROR CLASS: " + name + ">"),
          Modality.OPEN,
          Collections.<JetType>emptyList(),
          SourceElement.NO_SOURCE);

      ConstructorDescriptorImpl errorConstructor =
          ConstructorDescriptorImpl.create(this, Annotations.EMPTY, true, SourceElement.NO_SOURCE);
      errorConstructor.initialize(
          Collections.<TypeParameterDescriptor>emptyList(),
          Collections.<ValueParameterDescriptor>emptyList(),
          Visibilities.INTERNAL);
      JetScope memberScope = createErrorScope(getName().asString());
      errorConstructor.setReturnType(
          new ErrorTypeImpl(
              TypeConstructorImpl.createForClass(
                  this,
                  Annotations.EMPTY,
                  false,
                  getName().asString(),
                  Collections.<TypeParameterDescriptorImpl>emptyList(),
                  Collections.singleton(KotlinBuiltIns.getInstance().getAnyType())),
              memberScope));

      initialize(
          memberScope,
          Collections.<ConstructorDescriptor>singleton(errorConstructor),
          errorConstructor);
    }
예제 #10
0
 @Test
 public void testQuerySelectWhereIn() {
   final String name = "Hello!";
   Person person = randomPerson();
   person.setName(name);
   data.insert(person);
   Group group = new Group();
   group.setName("Hello!");
   data.insert(group);
   person.getGroups().add(group);
   data.update(person);
   Return<Result<Tuple>> groupNames = data.select(Group.NAME).where(Group.NAME.equal(name));
   Person p = data.select(Person.class).where(Person.NAME.in(groupNames)).get().first();
   assertEquals(p.getName(), name);
   p = data.select(Person.class).where(Person.NAME.notIn(groupNames)).get().firstOrNull();
   assertNull(p);
   p =
       data.select(Person.class)
           .where(Person.NAME.in(Arrays.asList("Hello!", "Other")))
           .get()
           .first();
   assertEquals(p.getName(), name);
   p =
       data.select(Person.class)
           .where(Person.NAME.in(Collections.singleton("Hello!")))
           .get()
           .first();
   assertEquals(p.getName(), name);
   assertTrue(
       data.select(Person.class)
           .where(Person.NAME.notIn(Collections.singleton("Hello!")))
           .get()
           .toList()
           .isEmpty());
 }
예제 #11
0
  public void testNormalOperation2() throws IOException {

    TopicIF otherTopic = getTopicById(tm, "gamst");
    TopicIF otype = getTopicById(tm, "gamst");
    int numOcc = otherTopic.getOccurrences().size();

    // build params
    List plist = new ArrayList();
    plist.add(Collections.EMPTY_SET);
    plist.add(Collections.singleton(otherTopic));
    plist.add(Collections.singleton(otype));
    ActionParametersIF params = makeParameters(plist, "http://www.sf.net");
    ActionResponseIF response = makeResponse();

    // execute
    action.perform(params, response);

    // test
    assertFalse("Occurrence not added", numOcc >= otherTopic.getOccurrences().size());
    Iterator<OccurrenceIF> i = otherTopic.getOccurrences().iterator();
    boolean hasit = false;
    while (i.hasNext()) {
      OccurrenceIF foo = i.next();
      if (foo.getLocator().getAddress().equals("http://www.sf.net/")) hasit = true;
    }
    assertFalse("Occurrence is not set for the topic", !(hasit));
  }
예제 #12
0
 protected <S, P> void filterUnambiguousPaths(
     final Pda<S, P> pda, S state, Map<S, Integer> dist, Map<S, List<S>> followers) {
   if (followers.containsKey(state)) return;
   List<S> f = Lists.newArrayList(pda.getFollowers(state));
   if (f.size() <= 1) {
     followers.put(state, f);
     if (f.size() == 1) filterUnambiguousPaths(pda, f.get(0), dist, followers);
     return;
   }
   int closestDist = dist.get(f.get(0));
   S closest = f.get(0);
   for (int i = 1; i < f.size(); i++) {
     int d = dist.get(f.get(i));
     if (d < closestDist) {
       closestDist = d;
       closest = f.get(i);
     }
   }
   IsPop<S, P> isPop = new IsPop<S, P>(pda);
   Set<S> closestPops = nfaUtil.findFirst(pda, Collections.singleton(closest), isPop);
   Iterator<S> it = f.iterator();
   while (it.hasNext()) {
     S next = it.next();
     if (next != closest) {
       Set<S> nextPops = nfaUtil.findFirst(pda, Collections.singleton(next), isPop);
       if (!closestPops.equals(nextPops)) it.remove();
     }
   }
   followers.put(state, f);
   for (S follower : f) filterUnambiguousPaths(pda, follower, dist, followers);
 }
예제 #13
0
  @Test
  public void testReplace() {
    final AnalysesModel model = new AnalysesModel();
    final MCMCPresentation inco1 = new MCMCPresentation(d_wrapper, "inco1");
    final MCMCPresentation inco2 = new MCMCPresentation(d_wrapper, "inco2");

    model.add(ModelType.Inconsistency, inco1);
    JUnitUtil.assertAllAndOnly(
        model.getModels(ModelType.Inconsistency), Collections.singleton(inco1));

    TreeModelListener listener = EasyMock.createStrictMock(TreeModelListener.class);

    TreeModelEvent event1a =
        new TreeModelEvent(
            model,
            new Object[] {model.getRoot(), ModelType.Inconsistency},
            new int[] {0},
            new Object[] {inco2});
    listener.treeNodesChanged(TreeModelEventMatcher.eqTreeModelEvent(event1a));

    EasyMock.replay(listener);
    model.addTreeModelListener(listener);
    model.replace(ModelType.Inconsistency, inco1, inco2);
    EasyMock.verify(listener);

    JUnitUtil.assertAllAndOnly(
        model.getModels(ModelType.Inconsistency), Collections.singleton(inco2));
  }
예제 #14
0
  @Test
  public void testEmptyInputs() {
    TestTransaction tx1 = new TestTransaction(env);

    Set<Bytes> rowSet = Collections.singleton(Bytes.of("foo"));
    Set<Column> colSet = Collections.singleton(new Column("a", "b"));

    Set<Bytes> emptyRowSet = Collections.emptySet();
    Set<Column> emptyColSet = Collections.emptySet();
    Set<RowColumn> emptyRowColSet = Collections.emptySet();

    Assert.assertEquals(0, tx1.get(Bytes.of("foo"), emptyColSet).size());
    Assert.assertEquals(0, tx1.get(emptyRowSet, emptyColSet).size());
    Assert.assertEquals(0, tx1.get(emptyRowSet, colSet).size());
    Assert.assertEquals(0, tx1.get(rowSet, emptyColSet).size());
    Assert.assertEquals(0, tx1.get(rowSet, emptyColSet).size());
    Assert.assertEquals(0, tx1.get(emptyRowColSet).size());

    Set<String> erss = Collections.emptySet();
    Set<String> rss = Collections.singleton("foo");

    Assert.assertEquals(0, tx1.gets("foo", emptyColSet).size());
    Assert.assertEquals(0, tx1.gets(erss, emptyColSet).size());
    Assert.assertEquals(0, tx1.gets(erss, colSet).size());
    Assert.assertEquals(0, tx1.gets(rss, emptyColSet).size());
    Assert.assertEquals(0, tx1.gets(rss, emptyColSet).size());
    Assert.assertEquals(0, tx1.gets(emptyRowColSet).size());
  }
예제 #15
0
  public void testHosts() throws Exception {
    ZkRing ring = ZkRing.create(getZk(), coordinator, ring_group_root, 1, null, 1);
    assertEquals(0, ring.getHosts().size());

    Host host = ring.addHost(LOCALHOST);
    assertEquals(LOCALHOST, host.getAddress());
    for (int i = 0; i < 20; i++) {
      if (!ring.getHosts().isEmpty()) {
        break;
      }
      Thread.sleep(100);
    }
    assertEquals(Collections.singleton(host), ring.getHosts());

    assertEquals(LOCALHOST, ring.getHostByAddress(LOCALHOST).getAddress());
    ring.close();

    // assure that hosts reload well, too
    ring = new ZkRing(getZk(), ring_root, null, coordinator);
    assertEquals(1, ring.getHosts().size());

    assertEquals(Collections.singleton(host), ring.getHosts());

    assertEquals(LOCALHOST, ring.getHostByAddress(LOCALHOST).getAddress());

    assertTrue(ring.removeHost(LOCALHOST));
    assertNull(ring.getHostByAddress(LOCALHOST));
    assertFalse(ring.removeHost(LOCALHOST));

    ring.close();
  }
 @Test
 public void testParse() throws Exception {
   OperationsJsonParser parser = new OperationsJsonParser();
   Operations actual =
       parser.parse(ResourceUtil.getJsonObjectFromResource("/json/operations/valid.json"));
   assertThat(
       actual,
       is(
           new Operations(
               Collections.singleton(
                   new OperationGroup(
                       "opsbar-transitions",
                       Collections.singleton(
                           new OperationLink(
                               "action_id_4",
                               "issueaction-workflow-transition",
                               "Start Progress",
                               "Start work on the issue",
                               "/secure/WorkflowUIDispatcher.jspa?id=93813&action=4&atl_token=",
                               10,
                               null)),
                       Collections.singleton(
                           new OperationGroup(
                               null,
                               Collections.<OperationLink>emptyList(),
                               Collections.<OperationGroup>emptyList(),
                               new OperationHeader(
                                   "opsbar-transitions_more", "Workflow", null, null),
                               null)),
                       null,
                       20)))));
 }
 public List<OWLOntologyChange> addMatrixValue(OWLObject rowObj, Object columnObj, Object value) {
   if (columnObj instanceof OWLObjectProperty) {
     Set<OWLNamedIndividual> values = null;
     if (value instanceof OWLNamedIndividual) {
       values = Collections.singleton((OWLNamedIndividual) value);
     } else if (value instanceof Set) {
       // @@TODO check the contents of the set
       values = (Set<OWLNamedIndividual>) value;
     }
     if (values != null) {
       return helper.addRelationships(
           (OWLNamedIndividual) rowObj,
           (OWLObjectProperty) columnObj,
           values,
           mngr.getActiveOntology());
     }
   } else if (columnObj instanceof OWLDataProperty) {
     Set<OWLLiteral> values = null;
     if (value instanceof OWLLiteral) {
       values = Collections.singleton((OWLLiteral) value);
     } else if (value instanceof Set) {
       // @@TODO check the contents of the set
       values = (Set<OWLLiteral>) value;
     }
     if (values != null) {
       return helper.addRelationships(
           (OWLNamedIndividual) rowObj,
           (OWLDataProperty) columnObj,
           values,
           mngr.getActiveOntology());
     }
   }
   return super.addMatrixValue(rowObj, columnObj, value);
 }
 @Override
 @Before
 public void init() throws IncQueryBaseException {
   super.init();
   if (!navigationHelper.isInWildcardMode()) {
     navigationHelper.registerObservedTypes(
         Collections.singleton(SchoolPackage.eINSTANCE.getStudent()),
         Collections.singleton(EcorePackage.eINSTANCE.getEString()),
         Collections.singleton((EStructuralFeature) SchoolPackage.eINSTANCE.getStudent_Name()));
   }
   Set<EReference> refs = new HashSet<EReference>();
   refs.add(SchoolPackage.eINSTANCE.getStudent_FriendsWith());
   transitiveClosureHelper =
       IncQueryBaseFactory.getInstance()
           .createTransitiveClosureHelper(this.navigationHelper, refs);
   aStudent =
       (Student)
           navigationHelper.findByAttributeValue("Abel Hegedus").iterator().next().getEObject();
   bStudent =
       (Student)
           navigationHelper.findByAttributeValue("Gabor Bergmann").iterator().next().getEObject();
   cStudent =
       (Student)
           navigationHelper.findByAttributeValue("Zoltan Ujhelyi").iterator().next().getEObject();
 }
 @Override
 public Set<ValueRequirement> getRequirements(
     final FunctionCompilationContext context,
     final ComputationTarget target,
     final ValueRequirement desiredValue) {
   Set<String> values =
       desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY);
   if ((values == null) || values.isEmpty()) {
     return Collections.singleton(
         new ValueRequirement(
             ValueRequirementNames.HISTORICAL_TIME_SERIES_LATEST,
             target.toSpecification(),
             desiredValue
                 .getConstraints()
                 .copy()
                 .withoutAny(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY)
                 .with(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY, "")
                 .get()));
   } else if (values.size() > 1) {
     return Collections.singleton(
         new ValueRequirement(
             ValueRequirementNames.HISTORICAL_TIME_SERIES_LATEST,
             target.toSpecification(),
             desiredValue
                 .getConstraints()
                 .copy()
                 .withoutAny(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY)
                 .with(HistoricalTimeSeriesFunctionUtils.ADJUST_PROPERTY, values.iterator().next())
                 .get()));
   }
   return Collections.emptySet();
 }
예제 #20
0
  @BeforeClass
  public static void createTribes() throws NodeValidationException {
    Settings baseSettings =
        Settings.builder()
            .put(NetworkModule.HTTP_ENABLED.getKey(), false)
            .put("transport.type", MockTcpTransportPlugin.MOCK_TCP_TRANSPORT_NAME)
            .put(DiscoveryModule.DISCOVERY_TYPE_SETTING.getKey(), "local")
            .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
            .put(NodeEnvironment.MAX_LOCAL_STORAGE_NODES_SETTING.getKey(), 2)
            .build();

    tribe1 =
        new TribeClientNode(
                Settings.builder()
                    .put(baseSettings)
                    .put("cluster.name", "tribe1")
                    .put("node.name", "tribe1_node")
                    .put(NodeEnvironment.NODE_ID_SEED_SETTING.getKey(), random().nextLong())
                    .build(),
                Collections.singleton(MockTcpTransportPlugin.class))
            .start();
    tribe2 =
        new TribeClientNode(
                Settings.builder()
                    .put(baseSettings)
                    .put("cluster.name", "tribe2")
                    .put("node.name", "tribe2_node")
                    .put(NodeEnvironment.NODE_ID_SEED_SETTING.getKey(), random().nextLong())
                    .build(),
                Collections.singleton(MockTcpTransportPlugin.class))
            .start();
  }
예제 #21
0
  /**
   * This test ensures the same binding sets are created as the result of a {@link IterativeJoin}
   * regardless of which side the notification is triggered on.
   */
  @Test
  public void naturalJoin_sideDoesNotMatter() {
    // Create the binding sets that will be joined.
    final ValueFactory vf = new ValueFactoryImpl();

    final MapBindingSet bs1 = new MapBindingSet();
    bs1.addBinding("id", vf.createLiteral("some_uid"));
    bs1.addBinding("name", vf.createLiteral("Alice"));
    final VisibilityBindingSet vbs1 = new VisibilityBindingSet(bs1, "a");

    final MapBindingSet bs2 = new MapBindingSet();
    bs2.addBinding("id", vf.createLiteral("some_uid"));
    bs2.addBinding("hair", vf.createLiteral("brown"));
    final VisibilityBindingSet vbs2 = new VisibilityBindingSet(bs2, "b");

    // new vbs1 shows up on the left, matches vbs2 on the right
    final Iterator<VisibilityBindingSet> newLeftIt =
        join.newLeftResult(vbs1, Collections.singleton(vbs2).iterator());
    final VisibilityBindingSet newLeftResult = newLeftIt.next();

    // new vbs2 shows up on the right, matches vbs1 on the left
    final Iterator<VisibilityBindingSet> newRightIt =
        join.newRightResult(Collections.singleton(vbs1).iterator(), vbs2);
    final VisibilityBindingSet newRightResult = newRightIt.next();

    // Ensure those two results are the same.
    assertEquals(newLeftResult, newRightResult);
  }
예제 #22
0
  private void testSimpleTags(Placeable<?> s) {

    assertTrue(s.getResourceTags().isEmpty());

    s.addResourceTags();
    assertTrue(s.getResourceTags().isEmpty());

    s.addResourceTags("ingest");
    assertEquals(Collections.singleton("ingest"), s.getResourceTags());

    s.addResourceTags();
    assertEquals(Collections.singleton("ingest"), s.getResourceTags());

    s.addResourceTags("ingest");
    assertEquals(Collections.singleton("ingest"), s.getResourceTags());

    Set<String> expected = new HashSet<>();
    expected.add("ingest");
    expected.add("database");

    s.addResourceTags("database");
    assertEquals(expected, s.getResourceTags());

    expected.add("db2");
    expected.add("sales");
    s.addResourceTags("sales", "db2");
    assertEquals(expected, s.getResourceTags());
  }
예제 #23
0
  @Test
  public void testObjectSet() {
    Object result =
        unconvert(
            "getObjectSet",
            "setObjectSet",
            new AttributeValue()
                .withL(
                    new AttributeValue()
                        .withM(
                            new HashMap<String, AttributeValue>() {
                              {
                                put("name", new AttributeValue("name"));
                                put("value", new AttributeValue().withN("123"));
                                put("null", new AttributeValue().withNULL(true));
                              }
                            })));

    assertEquals(Collections.singleton(new SubClass()), result);

    result =
        unconvert(
            "getObjectSet",
            "setObjectSet",
            new AttributeValue().withL(new AttributeValue().withNULL(true)));

    assertEquals(Collections.<SubClass>singleton(null), result);
  }
예제 #24
0
  /**
   * Test method for {@link net.sf.hajdbc.balancer.load.LoadBalancer#add(net.sf.hajdbc.Database)}.
   */
  @Test
  public void add() {
    Balancer<Void, MockDatabase> balancer =
        this.factory.createBalancer(Collections.<MockDatabase>emptySet());

    boolean result = balancer.add(this.databases[1]);
    assertTrue(result);
    assertCollectionEquals(Collections.singleton(this.databases[1]), balancer);

    balancer = this.factory.createBalancer(Collections.singleton(this.databases[0]));

    result = balancer.add(this.databases[1]);
    assertTrue(result);
    assertCollectionEquals(Arrays.asList(this.databases[0], this.databases[1]), balancer);

    balancer =
        this.factory.createBalancer(
            new HashSet<MockDatabase>(Arrays.asList(this.databases[0], this.databases[1])));

    result = balancer.add(this.databases[1]);
    assertFalse(result);
    assertCollectionEquals(Arrays.asList(this.databases[0], this.databases[1]), balancer);

    balancer =
        this.factory.createBalancer(new HashSet<MockDatabase>(Arrays.asList(this.databases)));

    result = balancer.add(this.databases[1]);
    assertFalse(result);
    assertCollectionEquals(Arrays.asList(this.databases), balancer);
  }
예제 #25
0
  /**
   * Implementation for the filtered get methods {@link #getAssets(Collection, String, Visibility,
   * String)} and {@link #getAssetsWithUnboundedMaxVersion(Collection, String, Visibility)}.
   *
   * @param types The types to look for or <code>null</code> will return all types
   * @param productIds The product IDs to look for or <code>null</code> will return assets for any
   *     product ID
   * @param visibility The visibility to look for or <code>null</code> will return all visibility
   *     values (or none)
   * @param productVersions The value of the minimum version in the appliesToFilterInfo to look for
   * @param unboundedMaxVersion <code>true</code> if
   * @return
   * @throws IOException
   * @throws RequestFailureException
   */
  private Collection<Asset> getFilteredAssets(
      Collection<Type> types,
      Collection<String> productIds,
      Visibility visibility,
      Collection<String> productVersions,
      boolean unboundedMaxVersion)
      throws IOException, RequestFailureException {
    Map<FilterableAttribute, Collection<String>> filters =
        new HashMap<MassiveClient.FilterableAttribute, Collection<String>>();
    if (types != null && !types.isEmpty()) {
      Collection<String> typeValues = new HashSet<String>();
      for (Type type : types) {
        typeValues.add(type.getValue());
      }
      filters.put(FilterableAttribute.TYPE, typeValues);
    }
    filters.put(FilterableAttribute.PRODUCT_ID, productIds);
    if (visibility != null) {
      filters.put(FilterableAttribute.VISIBILITY, Collections.singleton(visibility.toString()));
    }
    filters.put(FilterableAttribute.PRODUCT_MIN_VERSION, productVersions);

    if (unboundedMaxVersion) {
      filters.put(
          FilterableAttribute.PRODUCT_HAS_MAX_VERSION,
          Collections.singleton(Boolean.FALSE.toString()));
    }

    return getFilteredAssets(filters);
  }
  @Test
  public void testCapitalizationFixes() throws ConnectionException {

    ApplicationScope scope = new ApplicationScopeImpl(new SimpleId("organization"));

    StringField field = new StringField("count", "MiXeD CaSe");
    Id entityId = new SimpleId(UUIDGenerator.newTimeUUID(), "entity");
    UUID version = UUIDGenerator.newTimeUUID();
    UniqueValue stored = new UniqueValueImpl(field, entityId, version);
    strategy.write(scope, stored).execute();

    UniqueValueSet fields =
        strategy.load(scope, entityId.getType(), Collections.<Field>singleton(field));

    UniqueValue value = fields.getValue(field.getName());

    assertEquals(field.getName(), value.getField().getName());

    assertEquals(entityId, value.getEntityId());

    // now test will all upper and all lower, we should get it all the same
    fields =
        strategy.load(
            scope,
            entityId.getType(),
            Collections.<Field>singleton(new StringField(field.getName(), "MIXED CASE")));

    value = fields.getValue(field.getName());

    assertEquals(field.getName(), value.getField().getName());

    assertEquals(entityId, value.getEntityId());

    fields =
        strategy.load(
            scope,
            entityId.getType(),
            Collections.<Field>singleton(new StringField(field.getName(), "mixed case")));

    value = fields.getValue(field.getName());

    assertEquals(field.getName(), value.getField().getName());

    assertEquals(entityId, value.getEntityId());

    Iterator<UniqueValue> allFieldsWritten = strategy.getAllUniqueFields(scope, entityId);

    assertTrue(allFieldsWritten.hasNext());

    // test this interface. In most cases, we won't know the field name, so we want them all
    UniqueValue writtenFieldEntry = allFieldsWritten.next();
    Assert.assertNotNull(writtenFieldEntry);

    assertEquals(field.getName(), writtenFieldEntry.getField().getName());
    assertEquals(field.getValue().toLowerCase(), writtenFieldEntry.getField().getValue());
    assertEquals(version, writtenFieldEntry.getEntityVersion());

    assertFalse(allFieldsWritten.hasNext());
  }
예제 #27
0
파일: ActionDB.java 프로젝트: stephan1/my
  /**
   * Création d'une société à partir de la base GestionDefault
   *
   * @param baseDefault nom de la base par défaut
   * @param newBase nom de la nouvelle base
   */
  public static void dupliqueDB(String baseDefault, String newBase, StatusListener l) {
    final DBSystemRoot sysRoot = Configuration.getInstance().getSystemRoot();

    // FIXME ADD TRIGGER TO UPDATE SOLDE COMPTE_PCE
    // ComptaPropsConfiguration instance = ComptaPropsConfiguration.create();
    // Configuration.setInstance(instance);

    try {
      log(l, "Création du schéma");
      if (!sysRoot.getRootsToMap().contains(baseDefault)) {
        sysRoot.getRootsToMap().add(baseDefault);
        sysRoot.refetch(Collections.singleton(baseDefault));
      }
      final DBRoot baseSQLDefault = sysRoot.getRoot(baseDefault);
      log(l, "Traitement des " + baseSQLDefault.getChildrenNames().size() + " tables");

      final SQLCreateRoot createRoot =
          baseSQLDefault.getDefinitionSQL(sysRoot.getServer().getSQLSystem());
      final SQLDataSource ds = sysRoot.getDataSource();
      // be safe don't add DROP SCHEMA
      ds.execute(createRoot.asString(newBase, false, true));
      sysRoot.getRootsToMap().add(newBase);
      // TODO find a more functional way
      final boolean origVal = Boolean.getBoolean(SQLSchema.NOAUTO_CREATE_METADATA);
      if (!origVal) System.setProperty(SQLSchema.NOAUTO_CREATE_METADATA, "true");
      sysRoot.refetch(Collections.singleton(newBase));
      if (!origVal) System.setProperty(SQLSchema.NOAUTO_CREATE_METADATA, "false");
      final DBRoot baseSQLNew = sysRoot.getRoot(newBase);

      final Set<SQLTable> newTables = baseSQLNew.getTables();
      int i = 0;
      final SQLSyntax syntax = sysRoot.getServer().getSQLSystem().getSyntax();
      // MAYBE SQLCreateRoot can avoid creating foreign constraints, then we insert data,
      // finally SQLCreateRoot adds just the constraints
      ds.execute(syntax.disableFKChecks(baseSQLNew));
      for (final SQLTable table : newTables) {
        String tableName = table.getName();

        log(l, "Copie de la table " + tableName + " " + (i + 1) + "/" + newTables.size());
        // Dump Table
        dumpTable(baseSQLDefault, table);
        log(l, "Table " + tableName + " " + (i + 1) + "/" + newTables.size() + " OK");
        i++;
      }
      ds.execute(syntax.enableFKChecks(baseSQLNew));

      if (syntax.getSystem() == SQLSystem.POSTGRESQL) {
        log(l, "Maj des séquences des tables");
        new FixSerial(sysRoot).changeAll(baseSQLNew);
      }

      log(l, "Duplication terminée");

    } catch (Throwable e) {
      e.printStackTrace();
      ExceptionHandler.handle("Erreur pendant la création de la base!", e);
      log(l, "Erreur pendant la duplication");
    }
  }
예제 #28
0
 void test(String... args) {
   task =
       tool.getTask(null, fm, null, null, Collections.singleton(T6412656.class.getName()), null);
   task.setProcessors(Collections.singleton(new MyProc(this)));
   task.call();
   if (count == 0) throw new AssertionError("Annotation processor not run");
   System.out.println("OK");
 }
예제 #29
0
 /**
  * Creates a meta data initialised to the specified values.
  *
  * @param contact Party responsible for the metadata information.
  * @param dateStamp Date that the metadata was created.
  * @param identificationInfo Basic information about the resource to which the metadata applies.
  */
 public MetaDataImpl(
     final ResponsibleParty contact,
     final Date dateStamp,
     final Identification identificationInfo) {
   setContacts(Collections.singleton(contact));
   setDateStamp(dateStamp);
   setIdentificationInfo(Collections.singleton(identificationInfo));
 }
예제 #30
0
 public Collection<Integer> getAgentInstanceIds() {
   if (contextName == null) {
     return Collections.singleton(-1);
   }
   if (createTableResources.getResourcesNonZero() != null) {
     return createTableResources.getResourcesNonZero().keySet();
   }
   return Collections.singleton(-1);
 }