org.eclipse.collections.api.list.MutableList Java Examples

The following examples show how to use org.eclipse.collections.api.list.MutableList. 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: IqLoadFileCreator.java    From obevo with Apache License 2.0 6 votes vote down vote up
IqLoadFileCreator(String tableName, MutableList<FieldToColumnMapping> fieldToColumnMappings, File iqLoadDir,
        String loadFilePrefix, IqLoadMode iqLoadMode, DataExtractor dataExtractor) {
    this.tableName = tableName;

    PartitionMutableList<FieldToColumnMapping> parsedMappings =
            fieldToColumnMappings.partition(Predicates.attributeIsNull(FieldToColumnMapping.defaultValue()));

    this.mappingsWithoutDefaults = parsedMappings.getSelected();
    this.mappingsWithDefaults = parsedMappings.getRejected();
    this.iqLoadDir = iqLoadDir;
    this.loadFilePrefix = loadFilePrefix;
    this.cub.register(new SybaseIqLoadFieldConverter(), String.class);
    this.iqLoadMode = iqLoadMode;
    this.dataExtractor = dataExtractor;
    this.fileToWrite = new File(this.getFilePath());
    this.filePathToLoad =
            iqLoadMode.isConvertToWindowsFileSyntax() ? this.getFilePath().replace("\\", "\\\\") : this.getFilePath()
                    .replace("\\", "/");
}
 
Example #2
Source File: OfficialLeelazAnalyzerV2.java    From mylizzie with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Process the lines in leelaz's output. Example: info move D16 visits 7 winrate 4704 pv D16 Q16 D4
 *
 * @param line an output line
 */
private void processEngineOutputLine(String line) {
    if (!StringUtils.startsWith(line, "info")) {
        return;
    }

    final MutableList<MoveData> currentBestMoves = parseMoveDataLine(line);
    if (CollectionUtils.isEmpty(currentBestMoves)) {
        return;
    }

    if (System.currentTimeMillis() - startPonderTime > Lizzie.optionSetting.getMaxAnalysisTime() * MILLISECONDS_IN_SECOND) {
        // we have pondered for enough time. pause pondering
        notificationExecutor.execute(this::pauseAnalyzing);
    }

    notificationExecutor.execute(() -> observers.bestMovesUpdated(currentBestMoves));
}
 
Example #3
Source File: PhoenixGoAnalyzer.java    From mylizzie with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Process the lines in leelaz's output. Example: info move D16 visits 7 winrate 4704 pv D16 Q16 D4
 *
 * @param line an output line
 */
private void processEngineOutputLine(String line) {
    String trimmed = StringUtils.trim(line);
    if (!StringUtils.startsWith(trimmed, "info")) {
        return;
    }

    final MutableList<MoveData> currentBestMoves = parseMoveDataLine(trimmed);
    if (CollectionUtils.isEmpty(currentBestMoves)) {
        return;
    }

    if (System.currentTimeMillis() - lastBestMoveUpdatedTime < 100) {
        return;
    }

    notificationExecutor.execute(() -> observers.bestMovesUpdated(currentBestMoves));
    lastBestMoveUpdatedTime = System.currentTimeMillis();
}
 
Example #4
Source File: PartitionPatternUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenAnySatisfiesCondition_thenCorrect() {
    MutableList<Integer> numbers = list;
    PartitionMutableList<Integer> partitionedFolks = numbers.partition(new Predicate<Integer>() {

        /**
         * 
         */
        private static final long serialVersionUID = -1551138743683678406L;

        public boolean accept(Integer each) {
            return each > 30;
        }
    });
    MutableList<Integer> greaterThanThirty = partitionedFolks.getSelected().sortThis();
    MutableList<Integer> smallerThanThirty = partitionedFolks.getRejected().sortThis();

    Assertions.assertThat(smallerThanThirty).containsExactly(1, 5, 8, 17, 23);
    Assertions.assertThat(greaterThanThirty).containsExactly(31, 38, 41);
}
 
Example #5
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 #6
Source File: ExercisesMTLoader.java    From reladomo-kata with Apache License 2.0 6 votes vote down vote up
private static MutableList<Employee> getFileList()
{
    Timestamp currentTimestamp = Timestamp.valueOf("2015-02-01 00:00:00.0");

    Employee mary = new Employee(currentTimestamp, 1, "Mary", "Lamb", 26);
    Employee bob = new Employee(currentTimestamp, 2, "Bob", "Smith", 29);
    Employee ted = new Employee(currentTimestamp, 3, "Ted", "Smith", 33);
    Employee jake = new Employee(currentTimestamp, 4, "Jake", "Snake", 42);
    Employee barry = new Employee(currentTimestamp, 5, "Barry", "Bird", 28);
    Employee terry = new Employee(currentTimestamp, 6, "Terry", "Chase", 19);
    Employee harry = new Employee(currentTimestamp, 7, "Harry", "White", 22);
    Employee john = new Employee(currentTimestamp, 8, "John", "Doe", 45);
    Employee jane = new Employee(currentTimestamp, 9, "Jane", "Wilson", 28);

    return FastList.newListWith(mary, bob, ted, jake, barry, terry, harry, john, jane);
}
 
Example #7
Source File: InMemoryTranslator.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Override
public final String prepare(String sql, final ChangeInput change, final Environment env) {
    if (change != null && Objects.equals(change.getChangeKey().getChangeType().getName(), ChangeType.STATICDATA_STR)
            && !StaticDataChangeTypeBehavior.isInsertModeStaticData(sql)) {
        return sql;
    }

    sql = CommentRemover.removeComments(sql, change != null ? change.getChangeKey().toString() : sql);
    MutableList<String> sqls = MultiLineStringSplitter.createSplitterOnSpaceAndLine("GO").valueOf(sql);

    MutableList<String> convertedSqls = sqls.collect(new Function<String, String>() {
        @Override
        public String valueOf(String object) {
            return InMemoryTranslator.this.translateStatement(object, change);
        }
    });

    return convertedSqls.makeString("\n\nGO\n\n");
}
 
Example #8
Source File: DbEnvironmentCleaner.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Override
public void cleanEnvironment(final boolean noPrompt) {
    Validate.isTrue(env.isCleanBuildAllowed(), "Clean build not allowed for this environment [" + env.getName()
            + "] ! Exiting...");

    // some schemas have complex dependencies that we currently aren't handling w/ the drop code. To work
    // around it, we just retry the drop if we have progress in dropping objects.
    // Note that regular forward deploys can handle dependencies properly; we just need the logic to extract
    // the object definitions out for all object types to enable this.
    int tryCount = 0;
    while (true) {
        tryCount++;
        LOG.info("Attempting to clean objects from environment");
        final Pair<Boolean, MutableList<Exception>> clearResults = clearEnvironmentInternal(noPrompt);
        if (!clearResults.getOne()) {
            throw new DeployerRuntimeException("Could not clean schema; remaining exceptions: " + clearResults.getTwo().collect(TO_EXCEPTION_STACK_TRACE));
        } else if (clearResults.getTwo().isEmpty()) {
            return;
        } else if (tryCount <= 10) {
            LOG.info("Failed to clean up schema on try #" + tryCount + " but able to make progress, will continue to try");
        } else {
            throw new DeployerRuntimeException("Could not clean schema after max " + tryCount + " tries; will exit with remaining exceptions: " + clearResults.getTwo().collect(TO_EXCEPTION_STACK_TRACE));
        }
    }
}
 
Example #9
Source File: BaselineTableChangeParser.java    From obevo with Apache License 2.0 6 votes vote down vote up
private MutableList<String> sortSqls(MutableList<String> sqls) {
    MutableList<String> orderedSqls = Lists.mutable.empty();
    MutableList<String> fkSqls = Lists.mutable.empty();
    MutableList<String> triggerSqls = Lists.mutable.empty();

    for (String sql : sqls) {
        Matcher matcher = RegexpPatterns.fkPattern.matcher(sql);
        Matcher triggerMatcher = RegexpPatterns.triggerPattern.matcher(sql);
        if (matcher.find()) {
            fkSqls.add(sql);
        } else if (triggerMatcher.find()) {
            triggerSqls.add(sql);
        } else {
            orderedSqls.add(sql);
        }
    }

    orderedSqls.addAll(fkSqls);
    orderedSqls.addAll(triggerSqls);
    return orderedSqls;
}
 
Example #10
Source File: CsvReaderDataSource.java    From obevo with Apache License 2.0 6 votes vote down vote up
/**
 * Putting this init here so that we can discover the file fields before running the actual rec
 */
public void init() {
    if (!this.initialized) {
        try {
            MutableList<String> fields;
            if (csvVersion == CsvStaticDataReader.CSV_V2) {
                CSVFormat csvFormat = CsvStaticDataReader.getCsvFormat(delim, nullToken);
                this.csvreaderV2 = new CSVParser(reader, csvFormat);
                this.iteratorV2 = csvreaderV2.iterator();
                fields = ListAdapter.adapt(IteratorUtils.toList(iteratorV2.next().iterator()));
            } else {
                this.csvreaderV1 = new au.com.bytecode.opencsv.CSVReader(this.reader, this.delim);
                fields = ArrayAdapter.adapt(this.csvreaderV1.readNext());
            }

            this.fields = fields.collect(this.convertDbObjectName);
        } catch (Exception e) {
            throw new DeployerRuntimeException(e);
        }
        this.initialized = true;
    }
}
 
Example #11
Source File: DbSimpleArtifactDeployer.java    From obevo with Apache License 2.0 6 votes vote down vote up
void deployArtifact(Connection conn, Change artifact) {
    MutableList<String> sqls = MultiLineStringSplitter.createSplitterOnSpaceAndLine("GO").valueOf(artifact.getConvertedContent());
    int index = 0;
    for (String sql : sqls) {
        index++;
        if (StringUtils.isBlank(sql)) {
            LOG.debug("Skipping blank sql");
        } else {
            LOG.debug("Executing change #{} in the artifact", index);

            try {
                dialect.doTryBlockForArtifact(conn, this.sqlExecutor, artifact);
                this.sqlExecutor.getJdbcTemplate().update(conn, sql);
            } catch (DataAccessException e) {
                throw new DeployerRuntimeException("Could not execute DDL:\nfor artifact [[["
                        + artifact.getDisplayString() + "]]] while executing SQL: [[[\n" + sql + "\n]]]", e);
            } finally {
                dialect.doFinallyBlockForArtifact(conn, this.sqlExecutor, artifact);
            }
        }
    }
}
 
Example #12
Source File: DbDataComparisonUtil.java    From obevo with Apache License 2.0 6 votes vote down vote up
private static MutableList<String> getKeyCols(DaTable tableInfo) {
    MutableList<String> keyCols = Lists.mutable.empty();
    DaIndex pk = tableInfo.getPrimaryKey();
    for (DaIndex index : tableInfo.getIndices()) {
        if (index.isUnique()) {
            pk = index;
            break;
        }
    }
    if (pk != null) {
        for (DaColumn col : pk.getColumns()) {
            keyCols.add(col.getName());
        }
    }
    return keyCols;
}
 
Example #13
Source File: BaselineValidatorMain.java    From obevo with Apache License 2.0 6 votes vote down vote up
private void validateNoBaselineBreaks(DbDeployerAppContext appContext, Predicate<? super CompareBreak> breakIgnorePredicate) {
    MutableList<CompareBreak> sortedCompareBreaks = this.calculateBaselineBreaks(appContext).toList().sortThis(
            Comparators.fromFunctions(
                    CompareBreak.TO_COMPARE_SUBJECT,
                    Functions.chain(CompareBreak.TO_CLAZZ, CLASS_TO_NAME),
                    Functions.chain(Functions.getToClass(), CLASS_TO_NAME)
            ));

    MutableList<CompareBreak> relevantBreaks = sortedCompareBreaks.reject(breakIgnorePredicate);

    LOG.info("Found " + relevantBreaks.size() + " breaks");

    if (!relevantBreaks.isEmpty()) {
        throw new IllegalArgumentException(
                "Found some mismatches between your change alters (LEFT) and your baseline files (RIGHT). Please review:\n"
                        + relevantBreaks.makeString("\n"));
    }
}
 
Example #14
Source File: AbstractMain.java    From obevo with Apache License 2.0 6 votes vote down vote up
private RichIterable<EnvType> getRequestedEnvironments(String sourcePath, String... envNames) {
    MutableCollection<EnvType> environments = getRequestedSystem(sourcePath);

    MutableList<EnvType> requestedEnvs = Lists.mutable.empty();

    if (envNames == null || envNames.length == 0) {
        requestedEnvs.add(readSingleEnvironment(environments, sourcePath));
    } else {
        for (EnvType sysEnv : environments) {
            for (String envPattern : envNames) {
                if (Pattern.compile(RegexUtil.convertWildcardPatternToRegex(envPattern))
                        .matcher(sysEnv.getName())
                        .matches()) {
                    requestedEnvs.add(sysEnv);
                }
            }
        }
    }

    if (requestedEnvs.isEmpty()) {
        throw new IllegalArgumentException("No environment with name/s "
                + Lists.mutable.with(envNames).makeString("(", ",", ")") + " found");
    }

    return requestedEnvs;
}
 
Example #15
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 #16
Source File: ExercisesRelationships.java    From reladomo-kata with Apache License 2.0 6 votes vote down vote up
@Test
public void testQ4()
{
    CustomerAccountList accountsBefore = CustomerAccountFinder.findMany(CustomerAccountFinder.all());
    CustomerList customersBefore = CustomerFinder.findMany(CustomerFinder.all());
    accountsBefore.forceResolve(); //to get this list resolved before we add the new customer.
    customersBefore.forceResolve();

    MutableList<Pair<String, String>> accountDescriptionAndTypePairs = FastList.newListWith(
            Tuples.pair("Tom's saving Account", "Savings"),
            Tuples.pair("Tom's running Account", "Running")
    );

    this.addCustomerAccounts("Tom Jones", "UK", accountDescriptionAndTypePairs);

    CustomerAccountList accountsAfter = CustomerAccountFinder.findMany(CustomerAccountFinder.all());
    CustomerList customersAfter = CustomerFinder.findMany(CustomerFinder.all());

    Assert.assertEquals(1, customersAfter.size() - customersBefore.size());
    Assert.assertEquals(2, accountsAfter.size() - accountsBefore.size());

    Customer tom = CustomerFinder.findOne(CustomerFinder.name().eq("Tom Jones"));
    CustomerAccountList tomsAccounts = new CustomerAccountList(CustomerAccountFinder.customerId().eq(tom.getCustomerId()));
    Verify.assertSize(2, tomsAccounts);
}
 
Example #17
Source File: PostgreSqlDbPlatform.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Override
protected ImmutableList<ChangeType> initializeChangeTypes() {
    MutableList<ChangeType> changeTypes = super.initializeChangeTypes().toList();

    DbChangeType sequenceType = getChangeType(changeTypes, ChangeType.SEQUENCE_STR);
    sequenceType = DbChangeTypeImpl.newDbChangeType(sequenceType).setGrantObjectQualifier("SEQUENCE").build();
    replaceChangeType(changeTypes, sequenceType);

    DbChangeType functionType = getChangeType(changeTypes, ChangeType.FUNCTION_STR);
    functionType = DbChangeTypeImpl.newDbChangeType(functionType).setGrantObjectQualifier("FUNCTION").build();
    replaceChangeType(changeTypes, functionType);

    DbChangeType typeType = DbChangeTypeImpl.newDbChangeType(ChangeType.USERTYPE_STR, true, 1, "TYPE").build();
    changeTypes.add(typeType);

    return changeTypes.toImmutable();
}
 
Example #18
Source File: BatchJmsMessageLoopTest.java    From reladomo with Apache License 2.0 5 votes vote down vote up
public MutableList<byte[]> consumeResult(String topic, final int firstWait, final int lastWait)
{
    try
    {
        final IncomingTopic incomingTopic = new IncomingTopic(createTopicForConsumer(topic), this.multiThreadedTm);
        final MutableList<byte[]> result = FastList.newList();
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand<Object>()
        {
            @Override
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                incomingTopic.enlistIntoTransaction();
                while (true)
                {
                    long timeout = result.size() > 0 ? 10 : firstWait;
                    // Wait for a message
                    BytesMessage message = (BytesMessage) incomingTopic.receive(timeout);
                    if (message == null)
                    {
                        break;
                    }
                    int bodyLength = (int) message.getBodyLength();
                    byte[] msgBytes = new byte[bodyLength];
                    message.readBytes(msgBytes);
                    result.add(msgBytes);
                }
                incomingTopic.delistFromTransaction(true);
                return null;
            }
        }, new TransactionStyle(20));
        incomingTopic.close();
        return result;
    }
    catch (Exception e)
    {
        throw new RuntimeException("failed to read messages", e);
    }
}
 
Example #19
Source File: TextMarkupDocumentReader.java    From obevo with Apache License 2.0 5 votes vote down vote up
private ImmutableList<TextMarkupDocumentSection> parseString(String text, ImmutableList<String> elementsToCheck, final boolean recurse,
        final String elementPrefix) {
    MutableList<Pair<String, String>> outerSections = splitIntoMainSections(text, elementsToCheck, elementPrefix);

    MutableList<TextMarkupDocumentSection> sections = outerSections.flatCollect(new ConvertOuterSectionToTextSection(recurse, elementPrefix));

    // remove any blank sections
    return sections.toImmutable().reject(each -> recurse
            && each.getName() == null
            && (StringUtils.isBlank(each.getContent()) || StringUtils.isBlank(CommentRemover.removeComments(each.getContent(), "removing on markup document reader"))  // need comments in a separate clause as CommentRemover returns a "null" string on null; will fix eventually
    ));
}
 
Example #20
Source File: CollectPatternUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenCollect_thenCorrect() {
    Student student1 = new Student("John", "Hopkins");
    Student student2 = new Student("George", "Adams");

    MutableList<Student> students = FastList.newListWith(student1, student2);

    MutableList<String> lastNames = students.collect(Student::getLastName);

    Assertions.assertThat(lastNames).containsExactly("Hopkins", "Adams");
}
 
Example #21
Source File: CachingRegistry.java    From camunda-bpm-reactor with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  registrations.withWriteLockAndDelegate((Procedure<MutableList<Registration<K, ? extends V>>>) regs -> {
    regs.remove(reg);
    threadLocalCache.clear();
  });
}
 
Example #22
Source File: FastListMultimap2.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public boolean keepOnlyOne(K key, V value) {
    MutableList<V> collection = this.map.get(key);
    if (collection == null) {
        return false;
    }
    int originSize = collection.size();
    collection.removeIf(Predicate.isEqual(value));
    collection.add(value);
    this.totalSize = this.totalSize - (originSize - collection.size());
    return true;
}
 
Example #23
Source File: DbChecksumCalculator.java    From obevo with Apache License 2.0 5 votes vote down vote up
private ImmutableCollection<ChecksumEntry> getTableChecksums(DaTable table) {
    MutableList<ChecksumEntry> checksums = Lists.mutable.empty();

    String pkContent = table.getPrimaryKey() != null ? table.getPrimaryKey().toString() : "";
    ChecksumEntry tableChecksum = ChecksumEntry.createFromText(table.getSchema().toPhysicalSchema(), ChangeType.TABLE_STR, table.getName(), "primaryKey", pkContent);
    checksums.add(tableChecksum);

    for (DaColumn column : table.getColumns()) {
        checksums.add(getColumnChecksum(table, column));
    }

    return checksums.toImmutable();
}
 
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: IqLoadFileCreatorTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
private void testLoad(String tableCreationSql, MutableList<FieldToColumnMapping> mappings, String rowDel,
        String colDel) throws Exception {
    conn = dataSource.getConnection();
    this.jdbcTemplate.update(conn, tableCreationSql);

    // setup the data
    MutableList<TestBean> beans = Lists.mutable.empty();
    LocalDateTime timestampJodaVal = new LocalDateTime("2011-01-01T11:11:00");
    LocalDate dateJodaVal = new LocalDate("2011-02-02");
    Timestamp timestampJdkVal = new Timestamp(new GregorianCalendar(2011, 0, 1, 11, 11, 0).getTimeInMillis());
    Date dateJdkVal = new GregorianCalendar(2011, 1, 2).getTime();

    int rowCount = 13;
    for (int i = 0; i < rowCount; i++) {
        beans.add(new TestBean(1, "2", i, dateJdkVal, timestampJdkVal, dateJodaVal, timestampJodaVal));
    }

    // setup IQ loader
    IqLoadFileCreator loadFileCreator = new IqLoadFileCreator(tableName, mappings, this.iqLoadRoot, "loadFile",
            this.iqLoadMode, new BeanDataExtractor());
    loadFileCreator.setRowDel(rowDel);
    loadFileCreator.setColDel(colDel);
    loadFileCreator.openFile();
    System.out.println("Writing the file");
    loadFileCreator.writeToFile(beans);
    loadFileCreator.closeFile();

    System.out.println("Executing the SQL");

    String mysql = loadFileCreator.getIdLoadCommand(this.schema);
    int rowsInserted = this.jdbcTemplate.update(conn, mysql);

    assertEquals(rowCount, rowsInserted);
    // TODO would like a better insertion - possibly on the data too
}
 
Example #26
Source File: IqLoadFileCreatorTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadWithoutDefault() throws Exception {
    StringBuilder sb = new StringBuilder();
    sb.append("DROP TABLE IF EXISTS " + tableName + ";");
    sb.append("CREATE TABLE " + tableName + " (");
    sb.append("intfield integer null,");
    sb.append("stringfield varchar(200) null,");
    sb.append("cm_id bigint not null,");
    sb.append("datefieldjoda date not null,");
    sb.append("datefieldjdk date not null,");
    sb.append("timestampfieldjoda timestamp not null,");
    sb.append("timestampfieldjdk timestamp not null,");
    sb.append("PRIMARY KEY (CM_ID),");
    sb.append(");");
    if (grantEnabled) {
        sb.append("GRANT SELECT ON " + tableName + " TO dbdeploy_ro;");
    }

    MutableList<FieldToColumnMapping> mappings = Lists.mutable.empty();
    mappings.add(new FieldToColumnMapping("myCmId", "CM_ID"));
    mappings.add(new FieldToColumnMapping("myString", "stringfield"));
    mappings.add(new FieldToColumnMapping("myInt", "intfield"));
    mappings.add(new FieldToColumnMapping("dateFieldJoda", "datefieldjoda"));
    mappings.add(new FieldToColumnMapping("timestampFieldJoda", "timestampfieldjoda"));
    mappings.add(new FieldToColumnMapping("dateFieldJdk", "datefieldjdk"));
    mappings.add(new FieldToColumnMapping("timestampFieldJdk", "timestampfieldjdk"));

    this.testLoad(sb.toString(), mappings, "\n", "~"); // single-char
    this.testLoad(sb.toString(), mappings, "\n", "!~!~"); // multi-char
    this.testLoad(sb.toString(), mappings, "####", "~"); // single-char,
    // non-line-break del
    this.testLoad(sb.toString(), mappings, "####", "!~!~"); // multi-char,
    // non-line-break del
}
 
Example #27
Source File: RawDeserializationTest.java    From jackson-datatypes-collections with Apache License 2.0 5 votes vote down vote up
@Test
public void objectList() throws IOException {
    testCollection(Lists.mutable.of("a", Collections.emptyMap(), 1), "[\"a\", {}, 1]",
            new TypeReference<MutableList>() {},
            new TypeReference<ImmutableList>() {},
            new TypeReference<MutableCollection>() {},
            new TypeReference<ImmutableCollection>() {},
            new TypeReference<RichIterable>() {});
    testCollection(Lists.mutable.of("a", Collections.emptyMap(), 1), "[\"a\", {}, 1]",
            MutableList.class,
            ImmutableList.class,
            MutableCollection.class,
            ImmutableCollection.class,
            RichIterable.class);
}
 
Example #28
Source File: FastListMultimap2.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public int getValueCount(K key, V value) {
    MutableList<V> collection = this.map.get(key);
    if (collection == null) {
        return 0;
    }
    return collection.count(v -> v.equals(value));
}
 
Example #29
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 #30
Source File: DbEnvironmentXmlEnricherTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> constructMap(ImmutableNode node) {
        final Map<String, Object> map =
                new HashMap<>(node.getChildren().size());
        map.putAll(node.getAttributes());

        MutableListMultimap<String, ImmutableNode> nodesByName = ListAdapter.adapt(node.getChildren()).groupBy(new Function<ImmutableNode, String>() {
            @Override
            public String valueOf(ImmutableNode immutableNode) {
                return immutableNode.getNodeName();
            }
        });
        nodesByName.forEachKeyMultiValues(new Procedure2<String, Iterable<ImmutableNode>>() {
            @Override
            public void value(String nodeName, Iterable<ImmutableNode> nodeIterable) {
//            System.out.println("At node " + cNode.getNodeName() + " and attrs " + cNode.getAttributes() + " and value " + cNode.getValue() + " and children " + cNode.getChildren());
                MutableList<ImmutableNode> nodes = CollectionAdapter.wrapList(nodeIterable);
                if (nodes.size() > 1) {
                    map.put(nodeName, nodes.collect(new Function<ImmutableNode, Object>() {
                        @Override
                        public Object valueOf(ImmutableNode node1) {
                            return DbEnvironmentXmlEnricherTest.this.getNodeValue(node1);
                        }
                    }));
                } else {
                    map.put(nodeName, DbEnvironmentXmlEnricherTest.this.getNodeValue(nodes.getFirst()));
                }
            }
        });
        return map;
    }