org.eclipse.collections.api.set.MutableSet Java Examples

The following examples show how to use org.eclipse.collections.api.set.MutableSet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ALSServingModel.java    From oryx with Apache License 2.0 6 votes vote down vote up
/**
 * Like {@link #retainRecentAndUserIDs(Collection)} and {@link #retainRecentAndItemIDs(Collection)}
 * but affects the known-items data structure.
 *
 * @param users users that should be retained, which are coming in the new model updates
 * @param items items that should be retained, which are coming in the new model updates
 */
void retainRecentAndKnownItems(Collection<String> users, Collection<String> items) {
  // Keep all users in the new model, or, that have been added since last model
  MutableSet<String> recentUserIDs = UnifiedSet.newSet();
  X.addAllRecentTo(recentUserIDs);
  try (AutoLock al = knownItemsLock.autoWriteLock()) {
    knownItems.keySet().removeIf(key -> !users.contains(key) && !recentUserIDs.contains(key));
  }

  // This will be easier to quickly copy the whole (smallish) set rather than
  // deal with locks below
  MutableSet<String> allRecentKnownItems = UnifiedSet.newSet();
  Y.addAllRecentTo(allRecentKnownItems);

  Predicate<String> notKeptOrRecent = value -> !items.contains(value) && !allRecentKnownItems.contains(value);
  try (AutoLock al = knownItemsLock.autoReadLock()) {
    knownItems.values().forEach(knownItemsForUser -> {
      synchronized (knownItemsForUser) {
        knownItemsForUser.removeIf(notKeptOrRecent);
      }
    });
  }
}
 
Example #2
Source File: ArtifactPlatformRestrictionsTest.java    From obevo with Apache License 2.0 6 votes vote down vote up
private void assertTest(boolean result, final String platformName, final MutableSet<String> includes,
        final MutableSet<String> excludes) {
    Environment env = new Environment();

    Platform platform = mock(Platform.class);
    when(platform.getName()).thenReturn(platformName);
    env.setPlatform(platform);

    Restrictable restrictable = new Restrictable() {
        @Override
        public ImmutableList<ArtifactRestrictions> getRestrictions() {
            return Lists.immutable.<ArtifactRestrictions>of(new ArtifactPlatformRestrictions(includes, excludes));
        }
    };

    Assert.assertEquals(result, ArtifactRestrictions.apply().accept(restrictable, env));
}
 
Example #3
Source File: DbChangeRestrictionsReader.java    From obevo with Apache License 2.0 6 votes vote down vote up
public ImmutableList<ArtifactRestrictions> valueOf(TextMarkupDocumentSection section) {
    if (section == null) {
        return Lists.immutable.of();
    }

    MutableList<ArtifactRestrictions> restrictions = Lists.mutable.empty();

    Twin<MutableSet<String>> envRestrictions = readRestrictions(section, TextMarkupDocumentReader.INCLUDE_ENVS, TextMarkupDocumentReader.EXCLUDE_ENVS);
    if (envRestrictions != null) {
        restrictions.add(new ArtifactEnvironmentRestrictions(envRestrictions.getOne(), envRestrictions.getTwo()));
    }

    Twin<MutableSet<String>> platformRestrictions = readRestrictions(section, TextMarkupDocumentReader.INCLUDE_PLATFORMS, TextMarkupDocumentReader.EXCLUDE_PLATFORMS);
    if (platformRestrictions != null) {
        restrictions.add(new ArtifactPlatformRestrictions(platformRestrictions.getOne(), platformRestrictions.getTwo()));
    }

    return restrictions.toImmutable();
}
 
Example #4
Source File: DefaultRollbackDetector.java    From obevo with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true/false if all the schemas in the environment either need rollback (true) or don't (false).
 *
 * If some do and some don't, an exception is thrown.
 */
@Override
public boolean determineRollback(final String productVersion, final ImmutableSet<String> schemas, final DeployExecutionDao deployExecutionDao) {
    MutableMap<String, Boolean> rollbackFlags = schemas.toMap(
            Functions.<String>getPassThru(),
            new Function<String, Boolean>() {
                @Override
                public Boolean valueOf(String schema) {
                    LOG.info("Checking rollback status on Product Version {} and Schema {}", productVersion, schema);
                    return DefaultRollbackDetector.this.determineRollbackForSchema(productVersion, deployExecutionDao.getDeployExecutions(schema));
                }
            }
    );

    MutableSet<Boolean> values = rollbackFlags.valuesView().toSet();
    if (values.size() > 1) {
        MutableSetMultimap<Boolean, String> schemasByRollbackFlag = rollbackFlags.flip();
        MutableSet<String> rollbackSchemas = schemasByRollbackFlag.get(Boolean.TRUE);
        MutableSet<String> nonrollbackSchemas = schemasByRollbackFlag.get(Boolean.FALSE);

        throw new IllegalArgumentException("The following schemas were calculated for rollback [" + rollbackSchemas + "], though the rest were not [" + nonrollbackSchemas + "]; cannot proceed in this mixed mode");
    }

    return values.iterator().next().booleanValue();
}
 
Example #5
Source File: Change.java    From obevo with Apache License 2.0 6 votes vote down vote up
public ImmutableSet<String> getAcceptableHashes() {
    /**
     * This is here for backwards-compatibility w/ systems that were doing the hashing prior to making all the
     * hashing agnostic of the white-space (before, we only had the table changes be white-space agnostic).
     * We need the various contentHashStrategies to account for past versions of the algorithm.
     */
    return this.contentHashStrategies.flatCollect(new Function<DbChangeHashStrategy, Iterable<String>>() {
        @Override
        public Iterable<String> valueOf(DbChangeHashStrategy hashStrategy) {
            MutableSet<String> acceptableHashes = Sets.mutable.empty();
            acceptableHashes.add(hashStrategy.hashContent(content));
            if (convertedContent != null) {
                acceptableHashes.add(hashStrategy.hashContent(convertedContent));
            }
            return acceptableHashes;
        }
    }).toSet().toImmutable();
}
 
Example #6
Source File: SchemaGenerator.java    From obevo with Apache License 2.0 6 votes vote down vote up
private void generate(String schema) {
    MutableSet<MyInput> inputs = Sets.mutable.empty();

    inputs.withAll(getUserTypes(numTypes));
    inputs.withAll(getTables());
    inputs.withAll(getViews());
    inputs.withAll(getSps());

    MutableSet<String> types = Sets.mutable.of("table", "view", "sp", "usertype");
    File outputDir = new File("./target/testoutput");
    FileUtils.deleteQuietly(outputDir);
    outputDir.mkdirs();
    for (MyInput input : inputs) {
        MutableMap<String, Object> params = Maps.mutable.<String, Object>empty().withKeyValue(
                "name", input.getName()
        );
        for (String type : types) {
            params.put("dependent" + type + "s", input.getDependenciesByType().get(type));
        }

        File outputFile = new File(outputDir, schema + "/" + input.getType() + "/" + input.getName() + ".sql");
        outputFile.getParentFile().mkdirs();
        TestTemplateUtil.getInstance().writeTemplate("schemagen/" + input.getType() + ".sql.ftl", params, outputFile);
    }
}
 
Example #7
Source File: DbDeployer.java    From obevo with Apache License 2.0 6 votes vote down vote up
private ChecksumEntryInclusionPredicate createLookupIndexForObjectType(DbEnvironment env, ImmutableList<Change> sourceChanges, final String changeTypeName) {
    LookupIndex objectTypeIndex = new LookupIndex(Sets.immutable.with(changeTypeName));
    ImmutableList<Change> objectTypeChanges = sourceChanges.select(new Predicate<Change>() {
        @Override
        public boolean accept(Change it) {
            return it.getChangeTypeName().equals(changeTypeName);
        }
    });
    MutableSet<String> objectNames = objectTypeChanges.collect(new Function<Change, String>() {
        @Override
        public String valueOf(Change change) {
            return change.getObjectName();
        }
    }).collect(env.getPlatform().convertDbObjectName()).toSet();
    LookupIndex objectNameIndex = new LookupIndex(objectNames.toImmutable());
    return new ChecksumEntryInclusionPredicate(
            Lists.immutable.with(objectTypeIndex),
            Lists.immutable.with(objectNameIndex)
    );
}
 
Example #8
Source File: ALSServingModel.java    From oryx with Apache License 2.0 6 votes vote down vote up
void addKnownItems(String user, Collection<String> items) {
  if (!items.isEmpty()) {
    MutableSet<String> knownItemsForUser = doGetKnownItems(user);

    if (knownItemsForUser == null) {
      try (AutoLock al = knownItemsLock.autoWriteLock()) {
        // Check again
        knownItemsForUser = knownItems.computeIfAbsent(user, k -> UnifiedSet.newSet());
      }
    }

    synchronized (knownItemsForUser) {
      knownItemsForUser.addAll(items);
    }
  }
}
 
Example #9
Source File: Board.java    From mylizzie with GNU General Public License v3.0 6 votes vote down vote up
/**
 * cleans up what hasLibertyHelper does to the board state
 *
 * @param removedStones record for coords of removed stones
 * @param x            x coordinate -- needn't be valid
 * @param y            y coordinate -- needn't be valid
 * @param color        color to clean up. Must be a recursed stone type
 * @param stones       the stones array to modify
 * @param zobrist      the zobrist object to modify
 * @param removeStones if true, we will remove all these stones. otherwise, we will set them to their unrecursed version
 */
private void cleanupHasLibertiesHelper(MutableSet<Coordinates> removedStones, int x, int y, Stone color, Stone[] stones, Zobrist zobrist, boolean removeStones) {
    if (!isValid(x, y) || stones[getIndex(x, y)] != color)
        return;

    if (removeStones) {
        removedStones.add(Coordinates.of(x, y));
    }

    stones[getIndex(x, y)] = removeStones ? Stone.EMPTY : color.unrecursed();
    if (removeStones) {
        zobrist.toggleStone(x, y, color.unrecursed());
    }

    // use the flood fill algorithm to replace all adjacent recursed stones
    cleanupHasLibertiesHelper(removedStones, x + 1, y, color, stones, zobrist, removeStones);
    cleanupHasLibertiesHelper(removedStones, x, y + 1, color, stones, zobrist, removeStones);
    cleanupHasLibertiesHelper(removedStones, x - 1, y, color, stones, zobrist, removeStones);
    cleanupHasLibertiesHelper(removedStones, x, y - 1, color, stones, zobrist, removeStones);
}
 
Example #10
Source File: DbEnvironment.java    From obevo with Apache License 2.0 5 votes vote down vote up
public ImmutableList<Group> getGroups() {
    // ideally, the groups are defined in the groups field; however, we have not enforced this in the past, and most
    // folks just define the groups via the permission schemes. Hence, we add this extra getter here to allow
    // clients to get the groups they need
    MutableSet<String> groupNames = permissions.flatCollect(new Function<Permission, Iterable<Grant>>() {
        @Override
        public Iterable<Grant> valueOf(Permission permission) {
            return permission.getGrants();
        }
    }).flatCollect(new Function<Grant, Iterable<String>>() {
        @Override
        public Iterable<String> valueOf(Grant grant) {
            return grant.getGrantTargets().get(GrantTargetType.GROUP);
        }
    }).toSet();

    MutableSet<Group> permissionGroups = groupNames.collect(new Function<String, Group>() {
        @Override
        public Group valueOf(String name) {
            return new Group(name);
        }
    });

    permissionGroups.removeIf(Predicates.attributeIn(new Function<Group, Object>() {
        @Override
        public Object valueOf(Group group1) {
            return group1.getName();
        }
    }, this.groups.collect(new Function<Group, String>() {
        @Override
        public String valueOf(Group group) {
            return group.getName();
        }
    })));  // ensure that we don't duplicate groups across the permissions and config groups list

    return this.groups.newWithAll(permissionGroups);
}
 
Example #11
Source File: PlatformConfigReader.java    From obevo with Apache License 2.0 5 votes vote down vote up
private MutableList<PropertyInput> readConfigPackages(RichIterable<String> configPackages) {
    MutableSet<PropertyInput> prioritizedProperties = HashingStrategySets.mutable.of(HashingStrategies.fromFunction(new Function<PropertyInput, URL>() {
        @Override
        public URL valueOf(PropertyInput propertyInput) {
            return propertyInput.getPropertyFilePath();
        }
    }));

    for (String configPackage : configPackages) {
        ListIterable<FileObject> fileObjects = FileRetrievalMode.CLASSPATH.resolveFileObjects(configPackage)
                .flatCollect(new Function<FileObject, Iterable<FileObject>>() {
                    @Override
                    public Iterable<FileObject> valueOf(FileObject object) {
                        return ArrayAdapter.adapt(object.getChildren());
                    }
                });
        ListIterable<FileObject> propertyFiles = fileObjects
                .select(new Predicate<FileObject>() {
                    @Override
                    public boolean accept(FileObject it) {
                        return it.getName().getExtension().equals("yaml");
                    }
                });

        for (FileObject propertyFile : propertyFiles) {
            HierarchicalConfiguration<ImmutableNode> fileProps = loadPropertiesFromUrl(propertyFile);

            String configPriorityProp = fileProps.getString(PROP_CONFIG_PRIORITY);
            if (configPriorityProp != null) {
                int priority = Integer.parseInt(configPriorityProp);
                prioritizedProperties.add(new PropertyInput(propertyFile.getName().getBaseName(), propertyFile.getURLDa(), priority, fileProps));
            } else {
                LOG.warn("Property file {} was ignored as it did not contain {} property", propertyFile, PROP_CONFIG_PRIORITY);
            }
        }
    }
    return prioritizedProperties.toList();
}
 
Example #12
Source File: BoardData.java    From mylizzie with GNU General Public License v3.0 5 votes vote down vote up
public BoardData(ImmutablePair<Integer, Integer> boardSize, Stone[] stonesOnBoard, int[] lastMove, Stone lastMoveColor, boolean blackToPlay, Zobrist zobrist, int moveNumber, int[] moveNumberListOnBoard, List<VariationData> variationDataList, MutableSet<Coordinates> removedEnemyStoneIndexes, int blackPrisonersCount, int whitePrisonersCount) {
    this.boardSize = boardSize;
    this.stonesOnBoard = stonesOnBoard;
    this.lastMove = lastMove;
    this.lastMoveColor = lastMoveColor;
    this.blackToPlay = blackToPlay;
    this.zobrist = zobrist;
    this.moveNumber = moveNumber;
    this.moveNumberListOnBoard = moveNumberListOnBoard;
    this.variationDataList = variationDataList;
    this.removedEnemyStoneIndexes = removedEnemyStoneIndexes;
    this.blackPrisonersCount = blackPrisonersCount;
    this.whitePrisonersCount = whitePrisonersCount;
}
 
Example #13
Source File: ArtifactRestrictions.java    From obevo with Apache License 2.0 5 votes vote down vote up
private boolean matches(MutableSet<String> patterns, String value) {
    for (String pattern : patterns) {
        Pattern p = Pattern.compile(RegexUtil.convertWildcardPatternToRegex(pattern));
        if (p.matcher(value).matches()) {
            return true;
        }
    }
    return false;
}
 
Example #14
Source File: DbChangeRestrictionsReader.java    From obevo with Apache License 2.0 5 votes vote down vote up
private Twin<MutableSet<String>> readRestrictions(TextMarkupDocumentSection section, String includeKey, String excludeKey) {
    MutableSet<String> include = readList(section, includeKey);
    MutableSet<String> exclude = readList(section, excludeKey);
    if (include != null && exclude != null) {
        throw new IllegalArgumentException(
                String.format("Cannot define the %s param with both %s and %s; must be one or the other", TextMarkupDocumentReader.TAG_METADATA, includeKey, excludeKey)
        );
    } else if (include == null && exclude == null) {
        return null;
    } else {
        return Tuples.twin(include, exclude);
    }
}
 
Example #15
Source File: ArtifactRestrictions.java    From obevo with Apache License 2.0 5 votes vote down vote up
ArtifactRestrictions(MutableSet<String> includes, MutableSet<String> excludes) {
    this.includes = includes == null ? UnifiedSet.<String>newSet() : includes;
    this.excludes = excludes == null ? UnifiedSet.<String>newSet() : excludes;

    if (!this.includes.isEmpty() && !this.excludes.isEmpty()) {
        throw new IllegalArgumentException("Cannot specify both include and exclude");
    }
}
 
Example #16
Source File: DbChangeRestrictionsReader.java    From obevo with Apache License 2.0 5 votes vote down vote up
private MutableSet<String> readList(TextMarkupDocumentSection section, String key) {
    String val = section.getAttr(key);
    if (val == null) {
        return null;
    } else {
        return UnifiedSet.newSetWith(val.split(","));
    }
}
 
Example #17
Source File: ALSServingModel.java    From oryx with Apache License 2.0 5 votes vote down vote up
/**
 * @param user user to get known items for
 * @return set of known items for the user (immutable, but thread-safe)
 */
public Set<String> getKnownItems(String user) {
  MutableSet<String> knownItemsForUser = doGetKnownItems(user);
  if (knownItemsForUser == null) {
    return Collections.emptySet();
  }
  synchronized (knownItemsForUser) {
    if (knownItemsForUser.isEmpty()) {
      return Collections.emptySet();
    }
    // Must copy since the original object is synchronized
    return knownItemsForUser.clone().asUnmodifiable();
  }
}
 
Example #18
Source File: ExercisesAdvancedFinder.java    From reladomo-kata with Apache License 2.0 5 votes vote down vote up
@Test
public void testQ15()
{
    MutableSet<Attribute> wholeNumberAttributes
            = this.findAttributesClassifiedAs(AllTypesFinder.getFinderInstance(), "wholeNumber");
    Verify.assertSetsEqual(UnifiedSet.newSetWith("byteValue", "shortValue", "intValue", "longValue"),
            wholeNumberAttributes.collect(ATTRIBUTE_TO_NAME_SELECTOR));

    MutableSet<Attribute> floatingPointNumberAttributes
            = this.findAttributesClassifiedAs(AllTypesFinder.getFinderInstance(), "floatingPointNumber");
    Verify.assertSetsEqual(UnifiedSet.newSetWith("floatValue", "doubleValue"),
            floatingPointNumberAttributes.collect(ATTRIBUTE_TO_NAME_SELECTOR));

    Verify.assertEmpty(this.findAttributesClassifiedAs(AllTypesFinder.getFinderInstance(), "imaginaryNumber"));
}
 
Example #19
Source File: Db2PostDeployActionIT.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void checkForInvalidViews() throws Exception {
    sqlExecutor.executeWithinContext(physicalSchema, new Procedure<Connection>() {
        @Override
        public void value(Connection conn) {
            // Setup the invalid objects
            try {
                sqlExecutor.getJdbcTemplate().update(conn, "drop table INVALIDTEST_TABLE");
            } catch (DataAccessException ignore) {
                // ignore exceptions on dropping
            }
            sqlExecutor.getJdbcTemplate().update(conn, "create table INVALIDTEST_TABLE (a INT)");
            sqlExecutor.getJdbcTemplate().update(conn, "create or replace view INVALIDTEST_VIEW AS SELECT * FROM INVALIDTEST_TABLE");
            sqlExecutor.getJdbcTemplate().update(conn, "create or replace view INVALIDTEST_VIEW2 AS SELECT * FROM INVALIDTEST_VIEW WHERE 1=2");
            sqlExecutor.getJdbcTemplate().update(conn, "drop table INVALIDTEST_TABLE");

            MutableSet<String> invalidObjects = db2PostDeployAction.getInvalidObjects(conn, env.getPhysicalSchemas()).collect(new Function<SchemaObjectRow, String>() {
                @Override
                public String valueOf(SchemaObjectRow schemaObjectRow) {
                    return schemaObjectRow.getName();
                }
            }).toSet();
            assertThat("The two views created should go invalid when we drop the table that they are based on",
                    invalidObjects, hasItems("INVALIDTEST_VIEW", "INVALIDTEST_VIEW2"));

            // Check that the query can return invalid objects
            db2PostDeployAction.checkForInvalidObjects(conn, env.getPhysicalSchemas());

            // With this DB2 version, verify that we did try to execute the recompile and that if it fails (which we expect to in this case) that we log a warning
            // Verify that we did find an invalid object and tried to execute a recompile
            // (Note that it is difficult to reproduce this use case in some DB2 versions; hence, this check is optional)
            try {
                assertEquals(true, metricsCollector.getMetrics().toSerializedForm().get(Db2PostDeployAction.POST_DEPLOY_WARNINGS));
            } catch (AssertionError e) {
                Assume.assumeNoException("Expecting view to be invalid, but was not in this case", e);
            }
        }
    });
}
 
Example #20
Source File: TextMarkupDocumentReaderTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
private void assertSection(final TextMarkupDocumentSection section, String name, String content,
        MapIterable<String, String> attrs, MutableSet<String> toggles) {
    assertEquals(name, section.getName());
    assertEquals(content, section.getContent());
    attrs.forEachKeyValue((key, value) -> assertEquals(value, section.getAttr(key)));
    for (String toggle : toggles) {
        assertTrue("Finding toggle " + toggle, section.isTogglePresent(toggle));
    }
}
 
Example #21
Source File: ArtifactEnvironmentRestrictionsTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
private void assertTest(boolean result, String envName, final MutableSet<String> includes,
        final MutableSet<String> excludes) {
    Environment env = new Environment();
    env.setName(envName);

    Restrictable restrictable = new Restrictable() {
        @Override
        public ImmutableList<ArtifactRestrictions> getRestrictions() {
            return Lists.immutable.<ArtifactRestrictions>of(new ArtifactEnvironmentRestrictions(includes, excludes));
        }
    };

    Assert.assertEquals(result, ArtifactRestrictions.apply().accept(restrictable, env));
}
 
Example #22
Source File: DeserializerTest.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@Test
public void mutableSet() throws IOException {
    testCollection(Sets.mutable.of("1", "2", "3"),
                   "[\"1\", \"2\", \"3\"]",
                   new TypeReference<MutableSet<String>>() {});
    testCollection(BooleanSets.mutable.of(true, false, true), "[true, false, true]", MutableBooleanSet.class);
    testCollection(ByteSets.mutable.of((byte) 1, (byte) 2, (byte) 3), "[1, 2, 3]", MutableByteSet.class);
    testCollection(ShortSets.mutable.of((short) 1, (short) 2, (short) 3), "[1, 2, 3]", MutableShortSet.class);
    testCollection(CharSets.mutable.of('a', 'b', 'c'), "\"abc\"", MutableCharSet.class);
    testCollection(IntSets.mutable.of(1, 2, 3), "[1, 2, 3]", MutableIntSet.class);
    testCollection(FloatSets.mutable.of(1.1F, 2.3F, 3.5F), "[1.1, 2.3, 3.5]", MutableFloatSet.class);
    testCollection(LongSets.mutable.of(1, 2, 3), "[1, 2, 3]", MutableLongSet.class);
    testCollection(DoubleSets.mutable.of(1.1, 2.3, 3.5), "[1.1, 2.3, 3.5]", MutableDoubleSet.class);
}
 
Example #23
Source File: Db2PostDeployAction.java    From obevo with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
MutableSet<SchemaObjectRow> getInvalidObjects(Connection conn, RichIterable<PhysicalSchema> physicalSchemas) {
    LOG.info("Checking for invalid objects");

    String schemaInClause = physicalSchemas.collect(new Function<PhysicalSchema, String>() {
        @Override
        public String valueOf(PhysicalSchema physicalSchema) {
            return physicalSchema.getPhysicalName();
        }
    }).makeString("('", "','", "')");

    MutableSet<SchemaObjectRow> oldInvalidObjects = queryOldInvalidObjects(conn, schemaInClause);
    try {
        MutableSet<SchemaObjectRow> newInvalidObjects = queryNewInvalidObjects(conn, schemaInClause);

        if (oldInvalidObjects.isEmpty() && newInvalidObjects.notEmpty()) {
            deployMetricsCollector.addMetric("invalidObjectQuery.resultsOnlyInNew", true);
        } else if (oldInvalidObjects.notEmpty() && newInvalidObjects.isEmpty()) {
            deployMetricsCollector.addMetric("invalidObjectQuery.resultsOnlyInOld", true);
        }

        return oldInvalidObjects.withAll(newInvalidObjects);
    } catch (DataAccessException e) {
        deployMetricsCollector.addMetric("oldInvalidObjectQueryRequired", true);
        LOG.debug("Failed to execute new invalid objects SQL; falling back to old query");
        return oldInvalidObjects;
    }
}
 
Example #24
Source File: DbDataComparisonConfigFactory.java    From obevo with Apache License 2.0 5 votes vote down vote up
private static DbDataComparisonConfig createFromProperties(final Configuration config) {
    Properties propsView = ConfigurationConverter.getProperties(config);  // config.getString() automatically parses
    // for commas...would like to avoid this
    DbDataComparisonConfig compConfig = new DbDataComparisonConfig();
    compConfig.setInputTables(Lists.mutable.with(propsView.getProperty("tables.include").split(",")));
    compConfig.setExcludedTables(Lists.mutable.with(propsView.getProperty("tables.exclude").split(",")).toSet());
    String comparisonsStr = propsView.getProperty("comparisons");

    MutableList<Pair<String, String>> compCmdPairs = Lists.mutable.empty();
    MutableSet<String> dsNames = UnifiedSet.newSet();
    for (String compPairStr : comparisonsStr.split(";")) {
        String[] pairParts = compPairStr.split(",");
        compCmdPairs.add(Tuples.pair(pairParts[0], pairParts[1]));

        // note - if I knew where the Pair.TO_ONE TO_TWO selectors were, I'd use those
        dsNames.add(pairParts[0]);
        dsNames.add(pairParts[1]);
    }

    compConfig.setComparisonCommandNamePairs(compCmdPairs);

    MutableList<DbDataSource> dbDataSources = dsNames.toList().collect(new Function<String, DbDataSource>() {
        @Override
        public DbDataSource valueOf(String dsName) {
            Configuration dsConfig = config.subset(dsName);

            DbDataSource dbDataSource = new DbDataSource();
            dbDataSource.setName(dsName);
            dbDataSource.setUrl(dsConfig.getString("url"));
            dbDataSource.setSchema(dsConfig.getString("schema"));
            dbDataSource.setUsername(dsConfig.getString("username"));
            dbDataSource.setPassword(dsConfig.getString("password"));
            dbDataSource.setDriverClassName(dsConfig.getString("driverClass"));

            return dbDataSource;
        }
    });
    compConfig.setDbDataSources(dbDataSources);
    return compConfig;
}
 
Example #25
Source File: DbMergeInfo.java    From obevo with Apache License 2.0 5 votes vote down vote up
public static RichIterable<DbMergeInfo> parseFromProperties(Configuration config) {
    MutableSet<String> dbs = CollectionAdapter.wrapSet(config.getList(String.class, "instances", Lists.mutable.<String>empty()));

    MutableList<String> exceptions = Lists.mutable.empty();
    MutableList<DbMergeInfo> dbMergeInfos = Lists.mutable.empty();
    for (String db : dbs) {
        Configuration subset = config.subset(db);
        if (subset.containsKey("inputDir")) {
            File inputDir = new File(subset.getString("inputDir"));
            if (!inputDir.canRead()) {
                if (inputDir.getPath().contains("\r")) {
                    exceptions.add("Could not find " + db + "." + "inputDir file (use forward-slash instead of back-slash in path): " + inputDir.getPath().replaceAll("\r", ""));
                } else {
                    exceptions.add("Could not find " + db + "." + "inputDir file: " + inputDir);
                }
            }
            DbMergeInfo mergeInfo = new DbMergeInfo(db, inputDir);
            if (subset.containsKey("driverClassName")) {
                mergeInfo.setDriverClassName(subset.getString("driverClassName"));
                mergeInfo.setUrl(subset.getString("url"));
                mergeInfo.setUsername(subset.getString("username"));
                mergeInfo.setPassword(subset.getString("password"));
                mergeInfo.setPhysicalSchema(subset.getString("physicalSchema"));
            }

            dbMergeInfos.add(mergeInfo);
        }
    }

    if (exceptions.notEmpty()) {
        throw new IllegalArgumentException("Invalid properties found in configuration:\n" + exceptions.collect(new Function<String, String>() {
            @Override
            public String valueOf(String it) {
                return "* " + it;
            }
        }).makeString("\n"));
    }
    return dbMergeInfos;
}
 
Example #26
Source File: Board.java    From mylizzie with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Removes a chain if it has no liberties
 *
 *
 * @param removedStones record for coords of removed stones
 * @param x       x coordinate -- needn't be valid
 * @param y       y coordinate -- needn't be valid
 * @param color   the color of the chain to remove
 * @param stones  the stones array to modify
 * @param zobrist the zobrist object to modify
 * @return whether or not stones were removed
 */
private boolean removeDeadChain(MutableSet<Coordinates> removedStones, int x, int y, Stone color, Stone[] stones, Zobrist zobrist) {
    if (!isValid(x, y) || stones[getIndex(x, y)] != color)
        return false;

    boolean hasLiberties = hasLibertiesHelper(x, y, color, stones);

    // either remove stones or reset what hasLibertiesHelper does to the board
    cleanupHasLibertiesHelper(removedStones, x, y, color.recursed(), stones, zobrist, !hasLiberties);

    // if hasLiberties is false, then we removed stones
    return !hasLiberties;
}
 
Example #27
Source File: ExercisesAdvancedFinder.java    From reladomo-kata with Apache License 2.0 5 votes vote down vote up
public MutableSet<Attribute> findAttributesClassifiedAs(
        RelatedFinder finder,
        final String classificationTypeValue)
{
    Assert.fail("Implement this functionality to make the test pass");
    return null;
}
 
Example #28
Source File: DbEnvironmentCleaner.java    From obevo with Apache License 2.0 5 votes vote down vote up
private ImmutableList<DbCleanCommand> getDropStatements(PhysicalSchema physicalSchema) {
    DaCatalog database = this.dbMetadataManager.getDatabase(physicalSchema, new DaSchemaInfoLevel().setRetrieveAllObjectsMinimum().setRetrieveTableForeignKeys(true), true, true);

    MutableSet<DbCleanCommand> cleanCommands = Sets.mutable.empty();

    cleanCommands.withAll(getRoutineDrops(database, physicalSchema));
    cleanCommands.withAll(getTableDrops(database, physicalSchema));
    cleanCommands.withAll(getObjectDrops(database.getPackages(), ChangeType.PACKAGE_STR, physicalSchema));
    cleanCommands.withAll(getObjectDrops(database.getSequences(), ChangeType.SEQUENCE_STR, physicalSchema));
    cleanCommands.withAll(getObjectDrops(database.getSynonyms(), ChangeType.SYNONYM_STR, physicalSchema));
    cleanCommands.withAll(getObjectDrops(database.getRules(), ChangeType.RULE_STR, physicalSchema));
    cleanCommands.withAll(getObjectDrops(database.getUserTypes(), ChangeType.USERTYPE_STR, physicalSchema));

    return cleanCommands.toList().toImmutable();
}
 
Example #29
Source File: DbEnvironment.java    From obevo with Apache License 2.0 5 votes vote down vote up
public ImmutableList<User> getUsers() {
    // See note in getGroups() on why we get the users from the permissions
    MutableSet<String> userNames = permissions.flatCollect(new Function<Permission, Iterable<Grant>>() {
        @Override
        public Iterable<Grant> valueOf(Permission permission) {
            return permission.getGrants();
        }
    }).flatCollect(new Function<Grant, Iterable<String>>() {
        @Override
        public Iterable<String> valueOf(Grant grant) {
            return grant.getGrantTargets().get(GrantTargetType.USER);
        }
    }).toSet();  // remove duplicates within the permissions list

    MutableSet<User> permissionUsers = userNames.collect(new Function<String, User>() {
        @Override
        public User valueOf(String username) {
            return new User(username, null, false);
        }
    });

    final ImmutableList<String> existingUserNames = this.users.collect(new Function<User, String>() {
        @Override
        public String valueOf(User user) {
            return user.getName();
        }
    });
    permissionUsers.removeIf(new Predicate<User>() {
        @Override
        public boolean accept(User it) {
            return existingUserNames.contains(it.getName());
        }
    });  // ensure that we don't duplicate users across the permissions and config users list

    return this.users.newWithAll(permissionUsers);
}
 
Example #30
Source File: ArtifactEnvironmentRestrictions.java    From obevo with Apache License 2.0 4 votes vote down vote up
public ArtifactEnvironmentRestrictions(MutableSet<String> include, MutableSet<String> exclude) {
    super(include, exclude);
}