org.eclipse.collections.api.map.MutableMap Java Examples

The following examples show how to use org.eclipse.collections.api.map.MutableMap. 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: Exercise3Test.java    From reladomo-kata with Apache License 2.0 6 votes vote down vote up
/**
 * Sum the ages of all {@code Pet}s.
 * Use Reladomo's aggregation methods.
 * <p>
 * <p>Name {@code groupBy} column as "personId</p>
 * <p>Name {@code sum} column as "petAge"</p>
 * <p>Use appropriate methods on {@link AggregateList}</p>
 */
@Test
public void getTotalAgeOfAllSmithPets()
{
    AggregateList aggregateList = null;

    aggregateList.addAggregateAttribute("petAge", PetFinder.petAge().sum());
    aggregateList.addGroupBy("personId", PetFinder.personId());

    MutableMap<Integer, Integer> personIdToTotalPetAgeMap = Iterate.toMap(
            aggregateList,
            aggregateData -> aggregateData.getAttributeAsInteger("personId"),
            aggregateData -> aggregateData.getAttributeAsInteger("petAge")
    );

    Verify.assertMapsEqual(
            Maps.mutable.with(1, 3, 2, 20, 3, 4),
            personIdToTotalPetAgeMap
    );
}
 
Example #2
Source File: CsvReaderDataSourceTest.java    From obevo with Apache License 2.0 6 votes vote down vote up
private void verifyCsv(String input, MutableList<String> keyFields, MutableMap<String, String>... rows) throws Exception {
    CsvReaderDataSource ds = new CsvReaderDataSource(csvVersion, "test", new StringReader(input), ',', StringFunctions.toLowerCase(), "null");
    ds.setCatoConfiguration(new CatoSimpleJavaConfiguration(new SimpleCatoProperties(keyFields)));
    ds.init();
    ds.open();
    final MutableList<Map<String, Object>> dataRows = IteratorIterate.collect(ds, new Function<CatoDataObject, Map<String, Object>>() {
        @Override
        public Map<String, Object> valueOf(CatoDataObject catoDataObject) {
            Map<String, Object> data = Maps.mutable.empty();
            for (String field : catoDataObject.getFields()) {
                data.put(field, catoDataObject.getValue(field));
            }
            data.remove(CsvReaderDataSource.ROW_NUMBER_FIELD);

            return data;
        }
    }, Lists.mutable.<Map<String, Object>>empty());
    ds.close();

    assertEquals(rows.length, dataRows.size());
    for (int i = 0; i < dataRows.size(); i++) {
        assertEquals("Error on row " + i, rows[i], dataRows.get(i));
    }
}
 
Example #3
Source File: AquaRevengMain.java    From obevo with Apache License 2.0 6 votes vote down vote up
private ImmutableMap<ChangeType, Pattern> initPatternMap(Platform platform) {
    MutableMap<String, Pattern> params = Maps.mutable.<String, Pattern>with()
            .withKeyValue(ChangeType.SP_STR, Pattern.compile("(?i)create\\s+proc(?:edure)?\\s+(\\w+)", Pattern.DOTALL))
            .withKeyValue(ChangeType.FUNCTION_STR, Pattern.compile("(?i)create\\s+func(?:tion)?\\s+(\\w+)", Pattern.DOTALL))
            .withKeyValue(ChangeType.VIEW_STR, Pattern.compile("(?i)create\\s+view\\s+(\\w+)", Pattern.DOTALL))
            .withKeyValue(ChangeType.SEQUENCE_STR, Pattern.compile("(?i)create\\s+seq(?:uence)?\\s+(\\w+)", Pattern.DOTALL))
            .withKeyValue(ChangeType.TABLE_STR, Pattern.compile("(?i)create\\s+table\\s+(\\w+)", Pattern.DOTALL))
            .withKeyValue(ChangeType.DEFAULT_STR, Pattern.compile("(?i)create\\s+default\\s+(\\w+)", Pattern.DOTALL))
            .withKeyValue(ChangeType.RULE_STR, Pattern.compile("(?i)create\\s+rule\\s+(\\w+)", Pattern.DOTALL))
            .withKeyValue(ChangeType.USERTYPE_STR, Pattern.compile("(?i)^\\s*sp_addtype\\s+", Pattern.DOTALL))
            .withKeyValue(ChangeType.INDEX_STR, Pattern.compile("(?i)create\\s+(?:unique\\s+)?(?:\\w+\\s+)?index\\s+\\w+\\s+on\\s+(\\w+)", Pattern.DOTALL));

    MutableMap<ChangeType, Pattern> patternMap = Maps.mutable.<ChangeType, Pattern>with();
    for (String changeTypeName : params.keysView()) {
        if (platform.hasChangeType(changeTypeName)) {
            ChangeType changeType = platform.getChangeType(changeTypeName);
            patternMap.put(changeType, params.get(changeTypeName));
        }
    }

    return patternMap.toImmutable();
}
 
Example #4
Source File: IqDataSource.java    From obevo with Apache License 2.0 6 votes vote down vote up
public IqDataSource(DbEnvironment env, Credential userCredential, int numThreads, IqDataSourceFactory subDataSourceFactory) {
    this.env = env;
    this.subDataSourceFactory = subDataSourceFactory;

    MutableMap<PhysicalSchema, DataSource> dsMap = Maps.mutable.empty();
    for (PhysicalSchema physicalSchema : env.getPhysicalSchemas()) {
        String schema = physicalSchema.getPhysicalName();
        LOG.info("Creating datasource against schema {}", schema);
        DataSource ds = subDataSourceFactory.createDataSource(env,
                userCredential,
                schema,
                numThreads
        );

        dsMap.put(physicalSchema, ds);
    }

    this.dsMap = dsMap.toImmutable();
    this.setCurrentSchema(this.env.getPhysicalSchemas().getFirst());  // set one arbitrarily as the default
}
 
Example #5
Source File: PrepareDbChangeForDb.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Override
public String prepare(String content, ChangeInput change, DbEnvironment env) {
    MutableMap<String, String> tokens = Maps.mutable.<String, String>empty()
            .withKeyValue("dbSchemaSuffix", env.getDbSchemaSuffix())
            .withKeyValue("dbSchemaPrefix", env.getDbSchemaPrefix());

    for (Schema schema : env.getSchemas()) {
        PhysicalSchema physicalSchema = env.getPhysicalSchema(schema.getName());
        tokens.put(schema.getName() + "_physicalName", physicalSchema.getPhysicalName());
        if (env.getPlatform() != null) {
            tokens.put(schema.getName() + "_schemaSuffixed", env.getPlatform().getSchemaPrefix(physicalSchema));
            tokens.put(schema.getName() + "_subschemaSuffixed", env.getPlatform().getSubschemaPrefix(physicalSchema));
        }
    }

    if (env.getDefaultTablespace() != null) {
        tokens.put("defaultTablespace", env.getDefaultTablespace());
    }

    tokens.putAll(env.getTokens().castToMap());  // allow clients to override these values if needed

    return new Tokenizer(tokens, env.getTokenPrefix(), env.getTokenSuffix()).tokenizeString(content);
}
 
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: OptionDialog.java    From mylizzie with GNU General Public License v3.0 6 votes vote down vote up
private void initOtherComponents() {
    getRootPane().registerKeyboardAction(e -> setVisible(false),
            KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            JComponent.WHEN_IN_FOCUSED_WINDOW);

    getRootPane().registerKeyboardAction(e -> doApplySettings(),
            KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
            JComponent.WHEN_IN_FOCUSED_WINDOW);

    MutableMap<OptionSetting.BoardSize, JRadioButton> m = Maps.mutable.empty();
    m.put(new OptionSetting.BoardSize(19, 19), radioButtonBoard19x19);
    m.put(new OptionSetting.BoardSize(15, 15), radioButtonBoard15x15);
    m.put(new OptionSetting.BoardSize(13, 13), radioButtonBoard13x13);
    m.put(new OptionSetting.BoardSize(9, 9), radioButtonBoard9x9);
    m.put(new OptionSetting.BoardSize(7, 7), radioButtonBoard7x7);
    m.put(new OptionSetting.BoardSize(5, 5), radioButtonBoard5x5);

    boardSizeToRadioButtonMap = m.toImmutable();
}
 
Example #8
Source File: PlatformConfiguration.java    From obevo with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the default name-to-platform mappings. We put this in a separate protected method to allow external
 * distributions to override these values as needed.
 */
private ImmutableMap<String, ImmutableHierarchicalConfiguration> getDbPlatformMap() {
    final String platformKey = "db.platforms";

    ListIterable<ImmutableHierarchicalConfiguration> platformConfigs = ListAdapter.adapt(config.immutableChildConfigurationsAt("db.platforms"));

    MutableMap<String, ImmutableHierarchicalConfiguration> platformByName = Maps.mutable.empty();

    for (ImmutableHierarchicalConfiguration platformConfig : platformConfigs) {
        String platformName = platformConfig.getRootElementName();
        String platformClass = platformConfig.getString("class");
        if (platformClass == null) {
            LOG.warn("Improper platform config under {} for platform {}: missing class property. Will skip", platformKey, platformName);
        } else {
            platformByName.put(platformName, platformConfig);
            LOG.debug("Registering platform {} at class {}", platformName, platformClass);
        }
    }

    return platformByName.toImmutable();
}
 
Example #9
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 #10
Source File: DeserializerTest.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
@Test
public void objectObjectMaps() throws IOException {
    Assert.assertEquals(
            mapperWithModule().readValue("{\"abc\":\"def\"}", new TypeReference<MutableMap<String, String>>() {}),
            Maps.mutable.of("abc", "def")
    );
    Assert.assertEquals(
            mapperWithModule().readValue("{\"abc\":\"def\"}", new TypeReference<ImmutableMap<String, String>>() {}),
            Maps.immutable.of("abc", "def")
    );
    Assert.assertEquals(
            mapperWithModule().readValue("{\"abc\":\"def\"}", new TypeReference<MapIterable<String, String>>() {}),
            Maps.mutable.of("abc", "def")
    );
    Assert.assertEquals(
            mapperWithModule().readValue("{\"abc\":\"def\"}",
                                         new TypeReference<UnsortedMapIterable<String, String>>() {}),
            Maps.mutable.of("abc", "def")
    );
}
 
Example #11
Source File: OfficialLeelazAnalyzerV1.java    From mylizzie with GNU General Public License v3.0 6 votes vote down vote up
public static MoveData parseMoveDataLine(String line) {
    ParsingResult<?> result = runner.run(line);
    if (!result.matched) {
        return null;
    }

    MutableMap<String, Object> data = (MutableMap<String, Object>) result.valueStack.peek();

    MutableList<String> variation = (MutableList<String>) data.get("PV");
    String coordinate = (String) data.get("MOVE");
    int playouts = Integer.parseInt((String) data.get("CALCULATION"));
    double winrate = Double.parseDouble((String) data.get("VALUE")) / 100.0;
    double probability = getRate((String) data.get("POLICY"));

    return new MoveData(coordinate, playouts, winrate, probability, variation);
}
 
Example #12
Source File: OfficialLeelazAnalyzerV2.java    From mylizzie with GNU General Public License v3.0 6 votes vote down vote up
public static MutableList<MoveData> parseMoveDataLine(String line) {
    ParsingResult<?> result = runner.run(line);
    if (!result.matched) {
        return null;
    }

    return Streams.stream(result.valueStack)
            .map(o -> {
                MutableMap<String, Object> data = (MutableMap<String, Object>) o;

                MutableList<String> variation = (MutableList<String>) data.get("PV");
                String coordinate = (String) data.get("MOVE");
                int playouts = Integer.parseInt((String) data.get("CALCULATION"));
                double winrate = Double.parseDouble((String) data.get("VALUE")) / 100.0;
                double probability = getRate((String) data.get("POLICY")) + getRate((String) data.get("OLDPOLICY"));

                return new MoveData(coordinate, playouts, winrate, probability, variation);
            })
            .collect(Collectors.toCollection(Lists.mutable::empty))
            .reverseThis()
            ;
}
 
Example #13
Source File: ExercisesAdvancedFinder.java    From reladomo-kata with Apache License 2.0 6 votes vote down vote up
@Test
public void testQ18()
{
    AllTypes allTypes = new AllTypes();

    // Test no changes
    this.applyChanges(allTypes, UnifiedMap.<Integer, Object>newMap());

    Assert.assertEquals(0, allTypes.getIntValue());
    Assert.assertNull(allTypes.getStringValue());
    Assert.assertFalse(allTypes.isBooleanValue());
    Assert.assertEquals(0.0, allTypes.getDoubleValue(), 0.0);

    MutableMap<Integer, Object> changes = UnifiedMap.newMapWith(
            Tuples.<Integer, Object>pair(124, 65536),  // int
            Tuples.<Integer, Object>pair(237, "Charlie Croker"), // String
            Tuples.<Integer, Object>pair(874, true),  // boolean
            Tuples.<Integer, Object>pair(765, 1.2358));  // double
    this.applyChanges(allTypes, changes);

    Assert.assertEquals(65536, allTypes.getIntValue());
    Assert.assertEquals("Charlie Croker", allTypes.getStringValue());
    Assert.assertTrue(allTypes.isBooleanValue());
    Assert.assertEquals(1.2358, allTypes.getDoubleValue(), 0.0);
}
 
Example #14
Source File: DeserializerTest.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@Test
public void nestedMap() throws Exception {
    MutableMap<String, MutableMap<String, String>> pair = Maps.mutable.of("a", Maps.mutable.of("b", "c"));
    String json = "{\"a\":{\"b\":\"c\"}}";
    TypeReference<MutableMap<String, MutableMap<String, String>>> type =
            new TypeReference<MutableMap<String, MutableMap<String, String>>>() {};
    Assert.assertEquals(json, mapperWithModule().writerFor(type).writeValueAsString(pair));
    Assert.assertEquals(pair, mapperWithModule().readValue(json, type));
}
 
Example #15
Source File: PackageMetadataReader.java    From obevo with Apache License 2.0 5 votes vote down vote up
private ImmutableMap<String, String> getSourceEncodings(ImmutableHierarchicalConfiguration metadataConfig) {
    MutableList<ImmutableHierarchicalConfiguration> encodingConfigs = ListAdapter.adapt(metadataConfig.immutableChildConfigurationsAt("sourceEncodings"));
    MutableMap<String, String> encodingsMap = Maps.mutable.empty();

    for (ImmutableHierarchicalConfiguration encodingConfig : encodingConfigs) {
        String fileList = encodingConfig.getString("");
        for (String file : fileList.split(",")) {
            encodingsMap.put(file, encodingConfig.getRootElementName());
        }
    }

    return encodingsMap.toImmutable();
}
 
Example #16
Source File: SerializerTest.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@Test
public void objectObjectMaps() throws IOException {
    Assert.assertEquals(
            "{\"abc\":\"def\"}",
            mapperWithModule().writerFor(MutableMap.class).writeValueAsString(Maps.mutable.of("abc", "def"))
    );
    Assert.assertEquals(
            "{\"abc\":\"def\"}",
            mapperWithModule().writerFor(ImmutableMap.class).writeValueAsString(Maps.immutable.of("abc", "def"))
    );
    Assert.assertEquals(
            "{\"abc\":\"def\"}",
            mapperWithModule().writerFor(MapIterable.class).writeValueAsString(Maps.immutable.of("abc", "def"))
    );
    Assert.assertEquals(
            "{\"abc\":\"def\"}",
            mapperWithModule().writerFor(MutableMapIterable.class).writeValueAsString(Maps.mutable.of("abc", "def"))
    );
    Assert.assertEquals(
            "{\"abc\":\"def\"}",
            mapperWithModule().writeValueAsString(Maps.immutable.of("abc", "def"))
    );
    Assert.assertEquals(
            "{\"abc\":\"def\"}",
            mapperWithModule().writerFor(new TypeReference<MapIterable<String, String>>() {})
                    .writeValueAsString(Maps.immutable.of("abc", "def"))
    );
}
 
Example #17
Source File: RawDeserializationTest.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@Test
public void objectObjectMap() throws IOException {
    testCollection(Maps.mutable.of("a", 1, "b", Collections.emptyMap()), "{\"a\":1, \"b\":{}}",
            new TypeReference<MutableMap>() {},
            new TypeReference<ImmutableMap>() {});
    testCollection(Maps.mutable.of("a", 1, "b", Collections.emptyMap()), "{\"a\":1, \"b\":{}}",
            MutableMap.class,
            ImmutableMap.class);
}
 
Example #18
Source File: ExercisesAdvancedFinder.java    From reladomo-kata with Apache License 2.0 5 votes vote down vote up
@Test
public void testQ7()
{
    MutableMap<String, Integer> peopleByCountry = this.getCountOfPeopleByCountry();

    MutableMap<String, Integer> expectedResult = UnifiedMap.newMapWith(
            Tuples.pair("USA", 4),
            Tuples.pair("AU", 3),
            Tuples.pair("DE", 2),
            Tuples.pair("UK", 2),
            Tuples.pair("JPN", 4),
            Tuples.pair("MA", 1)
    );
    Verify.assertMapsEqual(expectedResult, peopleByCountry);
}
 
Example #19
Source File: ExercisesAdvancedFinder.java    From reladomo-kata with Apache License 2.0 5 votes vote down vote up
@Test
public void testQ17()
{
    MutableMap<Integer, Attribute> actualMap = this.getMyIdToAttributeMap();

    MutableMap<Integer, Attribute> expectedMap = UnifiedMap.newMapWith(
            Tuples.<Integer, Attribute>pair(Integer.valueOf(124), AllTypesFinder.intValue()),
            Tuples.<Integer, Attribute>pair(Integer.valueOf(237), AllTypesFinder.stringValue()),
            Tuples.<Integer, Attribute>pair(Integer.valueOf(874), AllTypesFinder.booleanValue()),
            Tuples.<Integer, Attribute>pair(Integer.valueOf(765), AllTypesFinder.doubleValue()));

    Verify.assertMapsEqual(expectedMap, actualMap);
}
 
Example #20
Source File: Exercise4Test.java    From reladomo-kata with Apache License 2.0 5 votes vote down vote up
/**
 * Similar to {@link Exercise3Test#getTotalAgeOfAllSmithPets()} only get the number of {@code Pet}s per {@code Person}.
 * <p>
 * Use Reladomo's aggregation methods.
 * </p>
 */
@Test
public void getNumberOfPetsPerPerson()
{
    AggregateList aggregateList = null;

    MutableMap<Integer, Integer> personIdToPetCountMap = Iterate.toMap(
            aggregateList,
            aggregateData -> aggregateData.getAttributeAsInteger("personId"),
            aggregateData -> aggregateData.getAttributeAsInteger("petCount"));

    Verify.assertMapsEqual(Maps.mutable.with(Tuples.pair(1, 1), Tuples.pair(2, 2), Tuples.pair(3, 1), Tuples.pair(5, 1), Tuples.pair(6, 1), Tuples.pair(7, 2)),
            personIdToPetCountMap);
}
 
Example #21
Source File: PostgresqlMetadataDialect.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public MutableMap<InformationSchemaKey, String> getInfoSchemaSqlOverrides(PhysicalSchema physicalSchema) {
    String sequenceSql = getSequenceSql(physicalSchema);
    if (sequenceSql != null) {
        return Maps.mutable.of(InformationSchemaKey.SEQUENCES, sequenceSql);
    } else {
        return null;
    }
}
 
Example #22
Source File: Main.java    From obevo with Apache License 2.0 5 votes vote down vote up
protected Main() {
    // use the hashing strategy to allow commands of any case to be handled
    MutableMap<String, Procedure<String[]>> commandMap = HashingStrategyMaps.mutable.of(HashingStrategies.fromFunction(new Function<String, String>() {
        @Override
        public String valueOf(String s) {
            return s.toLowerCase();
        }
    }));
    commandMap.putAll(getCommandMap().toMap());
    this.commandMap = commandMap.toImmutable();
}
 
Example #23
Source File: PhoenixGoAnalyzer.java    From mylizzie with GNU General Public License v3.0 5 votes vote down vote up
public static MutableList<MoveData> parseMoveDataLine(String line) {
    ParsingResult<?> result = runner.run(line);
    if (!result.matched) {
        return null;
    }

    MutableList<?> analyzed = Lists.mutable.withAll(result.valueStack);
    analyzed.sortThis((o1, o2) -> {
        MutableMap<String, Object> d1 = (MutableMap<String, Object>) o1;
        MutableMap<String, Object> d2 = (MutableMap<String, Object>) o2;
        return Integer.parseInt((String) d2.get("ORDER")) - Integer.parseInt((String) d1.get("ORDER"));
    });
    return analyzed.stream()
            .map(o -> {
                MutableMap<String, Object> data = (MutableMap<String, Object>) o;

                MutableList<String> variation = (MutableList<String>) data.get("PV");
                String coordinate = (String) data.get("MOVE");
                int playouts = Integer.parseInt((String) data.get("CALCULATION"));
                double winrate = Double.parseDouble((String) data.get("VALUE")) / 100.0;
                double probability = getRate((String) data.get("POLICY"));

                return new MoveData(coordinate, playouts, winrate, probability, variation);
            })
            .collect(Collectors.toCollection(Lists.mutable::empty))
            ;
}
 
Example #24
Source File: DbDataComparisonConfig.java    From obevo with Apache License 2.0 5 votes vote down vote up
public void init() {
    this.comparisonCommands = Lists.mutable.empty();
    MutableMap<String, DbDataSource> sourceMap = this.dbDataSources.groupByUniqueKey(new Function<DbDataSource, String>() {
        @Override
        public String valueOf(DbDataSource dbDataSource) {
            return dbDataSource.getName();
        }
    });
    for (Pair<String, String> comparisonCommandNamePair : this.comparisonCommandNamePairs) {
        this.comparisonCommands.add(new ComparisonCommand(
                sourceMap.get(comparisonCommandNamePair.getOne())
                , sourceMap.get(comparisonCommandNamePair.getTwo())
        ));
    }
}
 
Example #25
Source File: OfficialLeelazAnalyzerV1.java    From mylizzie with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
    ParsingResult<?> result = runner.run("info move D16 visits 7 winrate 4704 pv D16 Q16 D4");
    System.out.println(result.matched);
    System.out.println(result.valueStack.peek());

    result = runner.run("info move d1");
    System.out.println(result.matched);

    result = runner.run("info move pass visits 1537 winrate 4704 pv pass Q16 pass D1");
    System.out.println(result.matched);
    System.out.println(result.valueStack.peek());

    result = runner.run("info move pass visits 1537 winrate 4704 N 2305 pv pass Q16 pass D1");
    System.out.println(result.matched);
    System.out.println(result.valueStack.peek());
    MutableMap<String, Object> data = (MutableMap<String, Object>) result.valueStack.peek();

    result = runner.run("info move pass visits 1537 winrate 4704 network 2305 pv pass Q16 pass D1");
    System.out.println(result.matched);
    System.out.println(result.valueStack.peek());
    System.out.println(data.equals(result.valueStack.peek()));

    result = runner.run("info move pass visits 1537 winrate 4704 network 23.05 pv pass Q16 pass D1");
    System.out.println(result.matched);
    data = (MutableMap<String, Object>) result.valueStack.peek();
    System.out.println(Double.parseDouble((String) data.getOrDefault("POLICY", "0.0")));
}
 
Example #26
Source File: OfficialLeelazAnalyzerV1.java    From mylizzie with GNU General Public License v3.0 5 votes vote down vote up
boolean pushToList(String listKey, String value) {
    MutableMap<String, Object> valueMap = (MutableMap<String, Object>) peek();
    MutableList<String> list = (MutableList<String>) valueMap.get(listKey);
    list.add(value);

    return true;
}
 
Example #27
Source File: PhoenixGoAnalyzer.java    From mylizzie with GNU General Public License v3.0 5 votes vote down vote up
boolean pushToList(String listKey, String value) {
    MutableMap<String, Object> valueMap = (MutableMap<String, Object>) peek();
    MutableList<String> list = (MutableList<String>) valueMap.get(listKey);
    list.add(value);

    return true;
}
 
Example #28
Source File: OfficialLeelazAnalyzerV2.java    From mylizzie with GNU General Public License v3.0 5 votes vote down vote up
boolean pushToList(String listKey, String value) {
    MutableMap<String, Object> valueMap = (MutableMap<String, Object>) peek();
    MutableList<String> list = (MutableList<String>) valueMap.get(listKey);
    list.add(value);

    return true;
}
 
Example #29
Source File: AbstractReveng.java    From obevo with Apache License 2.0 4 votes vote down vote up
private MutableList<ChangeEntry> revengFile(SchemaObjectReplacer schemaObjectReplacer, List<Pair<String, RevengPatternOutput>> snippetPatternMatchPairs, String inputSchema, boolean debugLogEnabled) {
    final MutableList<ChangeEntry> changeEntries = Lists.mutable.empty();

    MutableMap<String, AtomicInteger> countByObject = Maps.mutable.empty();

    int selfOrder = 0;
    String candidateObject = "UNKNOWN";
    ChangeType candidateObjectType = UnclassifiedChangeType.INSTANCE;
    for (Pair<String, RevengPatternOutput> snippetPatternMatchPair : snippetPatternMatchPairs) {
        String sqlSnippet = snippetPatternMatchPair.getOne();
        try {
            sqlSnippet = removeQuotesFromProcxmode(sqlSnippet);  // sybase ASE

            MutableMap<String, Object> debugComments = Maps.mutable.empty();

            RevengPattern chosenRevengPattern = null;
            String secondaryName = null;
            final RevengPatternOutput patternMatch = snippetPatternMatchPair.getTwo();

            debugComments.put("newPatternMatch", patternMatch != null);

            if (patternMatch != null) {
                chosenRevengPattern = patternMatch.getRevengPattern();

                if (chosenRevengPattern.isShouldBeIgnored()) {
                    continue;
                }

                debugComments.put("objectType", patternMatch.getRevengPattern().getChangeType());
                // we add this here to allow post-processing to occur on RevengPatterns but still not define the object to write to
                if (patternMatch.getRevengPattern().getChangeType() != null) {
                    candidateObject = patternMatch.getPrimaryName();
                    debugComments.put("originalObjectName", candidateObject);
                    candidateObject = chosenRevengPattern.remapObjectName(candidateObject);

                    debugComments.put("secondaryName", patternMatch.getSecondaryName());
                    if (patternMatch.getSecondaryName() != null) {
                        secondaryName = patternMatch.getSecondaryName();
                    }
                    if (patternMatch.getRevengPattern().getChangeType().equalsIgnoreCase(UnclassifiedChangeType.INSTANCE.getName())) {
                        candidateObjectType = UnclassifiedChangeType.INSTANCE;
                    } else {
                        candidateObjectType = platform.getChangeType(patternMatch.getRevengPattern().getChangeType());
                    }
                }
            }

            // Ignore other schemas that may have been found in your parsing (came up during HSQLDB use case)

            sqlSnippet = schemaObjectReplacer.replaceSnippet(sqlSnippet);

            AtomicInteger objectOrder2 = countByObject.getIfAbsentPut(candidateObject, new Function0<AtomicInteger>() {
                @Override
                public AtomicInteger value() {
                    return new AtomicInteger(0);
                }
            });

            if (secondaryName == null) {
                secondaryName = "change" + objectOrder2.getAndIncrement();
            }

            RevEngDestination destination = new RevEngDestination(inputSchema, candidateObjectType, candidateObject, false, Optional.ofNullable(chosenRevengPattern).map(RevengPattern::isKeepLastOnly).orElse(false));

            String annotation = chosenRevengPattern != null ? chosenRevengPattern.getAnnotation() : null;
            MutableList<Function<String, LineParseOutput>> postProcessSqls = chosenRevengPattern != null ? chosenRevengPattern.getPostProcessSqls() : Lists.mutable.<Function<String, LineParseOutput>>empty();

            for (Function<String, LineParseOutput> postProcessSql : postProcessSqls) {
                LineParseOutput lineParseOutput = postProcessSql.valueOf(sqlSnippet);
                sqlSnippet = lineParseOutput.getLineOutput();
            }

            Integer suggestedOrder = patternMatch != null ? patternMatch.getRevengPattern().getSuggestedOrder() : null;

            if (debugLogEnabled && debugComments.notEmpty()) {
                String debugCommentsStr = debugComments.keyValuesView().collect(new Function<Pair<String, Object>, String>() {
                    @Override
                    public String valueOf(Pair<String, Object> object) {
                        return object.getOne() + "=" + object.getTwo();
                    }
                }).makeString("; ");
                sqlSnippet = "-- DEBUG COMMENT: " + debugCommentsStr + "\n" + sqlSnippet;
            }
            ChangeEntry change = new ChangeEntry(destination, sqlSnippet + "\nGO", secondaryName, annotation, ObjectUtils.firstNonNull(suggestedOrder, selfOrder++));

            postProcessChange.value(change, sqlSnippet);

            changeEntries.add(change);
        } catch (RuntimeException e) {
            throw new RuntimeException("Failed parsing on statement " + sqlSnippet, e);
        }
    }

    return changeEntries;
}
 
Example #30
Source File: FastListMultimap2.java    From alibaba-rsocket-broker with Apache License 2.0 4 votes vote down vote up
@Override
protected MutableMap<K, MutableList<V>> createMapWithKeyCount(int keyCount) {
    return UnifiedMap.newMap(keyCount);
}