org.eclipse.collections.api.block.procedure.Procedure Java Examples

The following examples show how to use org.eclipse.collections.api.block.procedure.Procedure. 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: CachingRegistry.java    From camunda-bpm-reactor with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public boolean unregister(final K key) {
  final AtomicBoolean modified = new AtomicBoolean(false);
  registrations.withWriteLockAndDelegate((Procedure<MutableList<Registration<K, ? extends V>>>) regs -> {
    Iterator<Registration<K, ? extends V>> registrationIterator = regs.iterator();
    Registration<K, ? extends V> reg;
    while (registrationIterator.hasNext()) {
      reg = registrationIterator.next();
      if (reg.getSelector().matches(key)) {
        registrationIterator.remove();
        modified.compareAndSet(false, true);
      }
    }
    if (useCache && modified.get()) {
      threadLocalCache.clear();
    }
  });
  return modified.get();
}
 
Example #2
Source File: SameSchemaDeployExecutionDao.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Override
public void update(final DeployExecution entry) {
    for (final PhysicalSchema physicalSchema : physicalSchemas) {
        sqlExecutor.executeWithinContext(physicalSchema, new Procedure<Connection>() {
            @Override
            public void value(Connection conn) {
                jdbc.update(conn, "UPDATE " + platform.getSchemaPrefix(physicalSchema) + deployExecutionTableName + " " +
                                "SET " + statusColName + " = ? " +
                                "WHERE " + idColName + " = ? ",
                        String.valueOf(entry.getStatus().getStatusCode()),
                        entry.getId()
                );
            }
        });
    }
}
 
Example #3
Source File: InMemoryXaResource.java    From reladomo with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void rollback(final Xid xid) throws XAException
{
    if (this.currentXid == null || !Arrays.equals(xid.getGlobalTransactionId(), this.currentXid.getGlobalTransactionId()))
    {
        throw new RuntimeException("not implemented");
    }
    callbacks.forEach(new Procedure<InMemoryTopicState>() {
        @Override
        public void value(InMemoryTopicState each)
        {
            each.rollback(xid);
        }
    });
    this.currentXid = null;
    callbacks.clear();
}
 
Example #4
Source File: InMemoryXaResource.java    From reladomo with Apache License 2.0 6 votes vote down vote up
@Override
public void commit(final Xid xid, boolean b) throws XAException
{
    if (this.currentXid == null || !Arrays.equals(xid.getGlobalTransactionId(), this.currentXid.getGlobalTransactionId()))
    {
        throw new RuntimeException("not implemented");
    }
    callbacks.forEach(new Procedure<InMemoryTopicState>() {
        @Override
        public void value(InMemoryTopicState each)
        {
            each.commit(xid);
        }
    });
    this.currentXid = null;
    callbacks.clear();
}
 
Example #5
Source File: AbstractDbChangeTypeBehavior.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Override
public void dropObject(final Change change, final boolean dropForRecreate) {
    sqlExecutor.executeWithinContext(change.getPhysicalSchema(env), new Procedure<Connection>() {
        @Override
        public void value(Connection conn) {
            String dropSql = null;
            try {
                dropSql = getDropSql(conn, change);
                LOG.info("Dropping object with SQL: {}", dropSql);
                for (String drop : MultiLineStringSplitter.createSplitterOnSpaceAndLine("GO").valueOf(dropSql)) {
                    if (!StringUtils.isBlank(drop)) {
                        sqlExecutor.getJdbcTemplate().update(conn, drop);
                    }
                }
            } catch (RuntimeException exc) {
                if (dropForRecreate) {
                    LOG.debug("Change type {} for Object {} is being deployed anew as this sql did not execute: {}", change.getChangeType(), change.getObjectName(), dropSql);
                } else {
                    throw exc;
                }
            }
        }
    });
}
 
Example #6
Source File: ConcurrentIntObjectHashMap.java    From reladomo with Apache License 2.0 6 votes vote down vote up
private void sequentialForEachValue(Procedure<V> block, AtomicReferenceArray currentArray, int start, int end)
{
    for (int i = start; i < end; i++)
    {
        Object o = currentArray.get(i);
        if (o == RESIZED || o == RESIZING)
        {
            throw new ConcurrentModificationException("can't iterate while resizing!");
        }
        Entry<V> e = (Entry<V>) o;
        while (e != null)
        {
            Object value = e.getValue();
            block.value((V) value);
            e = e.getNext();
        }
    }
}
 
Example #7
Source File: Db2PostDeployAction.java    From obevo with Apache License 2.0 6 votes vote down vote up
private void recompileInvalidObjects(RichIterable<PhysicalSchema> physicalSchemas) {
    MutableList<String> warnings = Lists.mutable.empty();
    for (final PhysicalSchema physicalSchema : physicalSchemas) {
        try {
            this.stmtExecutor.executeWithinContext(physicalSchema, new Procedure<Connection>() {
                @Override
                public void value(Connection conn) {
                    stmtExecutor.getJdbcTemplate().update(conn, "CALL SYSPROC.ADMIN_REVALIDATE_DB_OBJECTS(NULL, '" + physicalSchema.getPhysicalName() + "', NULL)");
                }
            });
            LOG.info("Successfully recompiled objects in schema", physicalSchema);
        } catch (DataAccessException e) {
            warnings.add(physicalSchema.getPhysicalName() + ": " + e.getMessage());
            LOG.warn("Failed to recompile objects on schema {}; will not fail the overall deployment due to this", physicalSchema, e);
        }
    }

    if (warnings.notEmpty()) {
        deployMetricsCollector.addMetric(POST_DEPLOY_WARNINGS, "Failures on recompiling invalid objects: " + warnings.makeString("\n"));
    }
}
 
Example #8
Source File: SameSchemaDbChecksumDao.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Override
public void deleteEntry(final ChecksumEntry entry) {
    sqlExecutor.executeWithinContext(entry.getPhysicalSchema(), new Procedure<Connection>() {
        @Override
        public void value(Connection conn) {
            jdbc.update(conn, "DELETE FROM " + platform.getSchemaPrefix(entry.getPhysicalSchema()) + checksumTableName + " " +
                            "WHERE OBJECTTYPE = ? " +
                            "AND OBJECTNAME1 = ? " +
                            "AND OBJECTNAME2 = ?",
                    entry.getObjectType(),
                    entry.getName1(),
                    entry.getName2() != null ? entry.getName2() : ""
            );
        }
    });
}
 
Example #9
Source File: ByteArraySet.java    From reladomo with Apache License 2.0 6 votes vote down vote up
@Override
public String toString()
{
    final StringBuilder builder = new StringBuilder();
    builder.append("[");
    this.forEach(new Procedure<byte[]>()
    {
        public void value(byte[] object)
        {
            builder.append(Arrays.toString(object));
            builder.append(',');
        }
    });
    if (this.size() > 0) builder.deleteCharAt(builder.length() - 1);
    builder.append("]");
    return builder.toString();
}
 
Example #10
Source File: Db2PostDeployAction.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Override
public void value(final DbEnvironment env) {
    // TODO would prefer to avoid this hack w/ the "executeWithinContext" here and picking a schema arbitrarily
    stmtExecutor.executeWithinContext(env.getPhysicalSchemas().getFirst(), new Procedure<Connection>() {
        @Override
        public void value(Connection conn) {
            // TODO refactor these into separate components that can be chained together (GITHUB#5)

            // TODO measure how long each of these takes: GITHUB#6
            if (env.isInvalidObjectCheckEnabled()) {
                checkForInvalidObjects(conn, env.getPhysicalSchemas());
            } else {
                LOG.info("Skipping invalid object check as configured in your environment");
            }

            if (env.isReorgCheckEnabled()) {
                checkForTablesNeedingReorg(conn, env);
            } else {
                LOG.info("Skipping check for tables pending reorg as configured in your environment");
            }
            LOG.info("Done in DB2 post-deploy action:");
        }
    });
}
 
Example #11
Source File: Main.java    From obevo with Apache License 2.0 6 votes vote down vote up
private Pair<String, Procedure<String[]>> getDeployCommand(String[] args, Runnable exitFailureMethod) {
    if (args.length == 0) {
        usage();
        exitFailureMethod.run();
    }

    Procedure<String[]> command = commandMap.get(args[0]);
    if (command == null) {
        System.out.println("No command w/ name " + args[0] + " has been defined in this distribution: " + commandMap.keysView().makeString("[", ", ", "]"));
        System.out.println("See the usage for more details");
        usage();
        exitFailureMethod.run();
    }

    return Tuples.pair(args[0], command);
}
 
Example #12
Source File: TestCrossDatabaseAdhocDeepFetch.java    From reladomo with Apache License 2.0 5 votes vote down vote up
public void testForEachForcesResolve()
{
    ParaPositionList nonOpList = getDeepFetchedNonOpList();
    int count = MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount();
    nonOpList.asEcList().forEach(new Procedure<ParaPosition>()
    {
        @Override
        public void value(ParaPosition paraPosition)
        {
            paraPosition.getAccount();
        }
    });
    // expect 1 extra retrieve for partial cache and 0 for full cache
    assertTrue(MithraManagerProvider.getMithraManager().getDatabaseRetrieveCount() <= count + 1);
}
 
Example #13
Source File: CompoundHashingStrategy.java    From obevo with Apache License 2.0 5 votes vote down vote up
public int computeHashCode(final T object) {
    final HashCodeBuilder hash = new HashCodeBuilder(17, 37);
    this.keyAttrs.forEach(new Procedure<Function<T, ?>>() {
        @Override
        public void value(Function<T, ?> attr) {
            hash.append(attr.valueOf(object));
        }
    });
    return hash.toHashCode();
}
 
Example #14
Source File: ParallelDeployChangeCommand.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(final ChangeTypeBehaviorRegistry changeTypeBehaviorRegistry, final CommandExecutionContext cec) {
    // 2 value -> only fork to parallelism if we have 2 tasks. 1 task will not require thread pool usage
    ParallelIterate.forEach(changes, new Procedure<Change>() {
        @Override
        public void value(Change change) {
            changeTypeBehaviorRegistry.deploy(change, cec);
        }
    }, 2, numThreads);
}
 
Example #15
Source File: ConcurrentIntObjectHashMap.java    From reladomo with Apache License 2.0 5 votes vote down vote up
public void forEach(Procedure<? super V> procedure)
{
    for(Iterator<V> iterator = this.values().iterator(); iterator.hasNext(); )
    {
        procedure.value(iterator.next());
    }
}
 
Example #16
Source File: SameSchemaDeployExecutionDao.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public void init() {
    for (final PhysicalSchema physicalSchema : physicalSchemas) {
        sqlExecutor.executeWithinContext(physicalSchema, new Procedure<Connection>() {
            @Override
            public void value(Connection conn) {
                init(conn, physicalSchema);
            }
        });
    }
}
 
Example #17
Source File: InMemoryTopicState.java    From reladomo with Apache License 2.0 5 votes vote down vote up
public void rollback(Xid xid)
{
    uncommittedMessages.remove(xid);
    consumerStates.forEach(new Procedure<InMemoryConsumerState>()
    {
        @Override
        public void value(InMemoryConsumerState each)
        {
            each.rollback();
        }
    });
}
 
Example #18
Source File: CachingRegistry.java    From camunda-bpm-reactor with Apache License 2.0 5 votes vote down vote up
@Override
public Registration<K, V> register(Selector<K> sel, V obj) {
  RemoveRegistration removeFn = new RemoveRegistration();
  final Registration<K, V> reg = new CachableRegistration<>(sel, obj, removeFn);
  removeFn.reg = reg;

  registrations.withWriteLockAndDelegate((Procedure<MutableList<Registration<K, ? extends V>>>) regs -> regs.add(reg));
  if (useCache) {
    threadLocalCache.clear();
  }

  return reg;
}
 
Example #19
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 #20
Source File: MultiEnvDeployScenarioTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiEnvDeploy() throws Exception {
    DbEnvironmentFactory.getInstance().readFromSourcePath("scenariotests/multiEnvDeploy", "test*").forEach(new Procedure<DbEnvironment>() {
        @Override
        public void value(DbEnvironment dbEnvironment) {
            dbEnvironment.buildAppContext()
                    .setupEnvInfra().cleanEnvironment()
                    .deploy();
        }
    });

    this.validateInstance("MultiEnvTest1", "SCH1");
    this.validateInstance("MultiEnvTest2", "SCH2");
}
 
Example #21
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 #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: SameSchemaDbChecksumDao.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public void persistEntry(final ChecksumEntry entry) {
    sqlExecutor.executeWithinContext(entry.getPhysicalSchema(), new Procedure<Connection>() {
        @Override
        public void value(Connection conn) {
            int numRowsUpdated = updateEntry(conn, entry);
            if (numRowsUpdated == 0) {
                insertEntry(conn, entry);
            }
        }
    });
}
 
Example #24
Source File: SameSchemaDbChecksumDao.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize() {
    for (final PhysicalSchema physicalSchema : physicalSchemas) {
        DaTable checksumTable = getChecksumTable(physicalSchema);
        if (checksumTable == null) {
            final String checksumTableSql = "CREATE TABLE " + platform.getSchemaPrefix(physicalSchema) + checksumTableName + " (" +
                    objectTypeColumnName + " VARCHAR(30) NOT NULL," +
                    objectName1ColumnName + " VARCHAR(128) NOT NULL," +
                    objectName2ColumnName + " VARCHAR(128) NOT NULL," +
                    checksumColumnName + " VARCHAR(32) NOT NULL," +
                    timeUpdatedColumnName + " " + platform.getTimestampType() + " NOT NULL," +
                    "CONSTRAINT SCH_CHKSUM_PK PRIMARY KEY (" + objectTypeColumnName + ", " + objectName1ColumnName + ", " + objectName2ColumnName + ")" +
                    ")" + tableSqlSuffix;

            sqlExecutor.executeWithinContext(physicalSchema, new Procedure<Connection>() {
                @Override
                public void value(Connection conn) {
                    jdbc.execute(conn, checksumTableSql);

                    DbChangeTypeBehavior tableChangeType = (DbChangeTypeBehavior) changeTypeBehaviorRegistry.getChangeTypeBehavior(ChangeType.TABLE_STR);
                    tableChangeType.applyGrants(conn, physicalSchema, checksumTableName, Lists.immutable.with(new Permission("artifacTable",
                            Lists.immutable.with(new Grant(Lists.immutable.with("SELECT"), Multimaps.immutable.list.with(GrantTargetType.PUBLIC, "PUBLIC"))))));
                }
            });
        }
    }
}
 
Example #25
Source File: AbstractDbChangeTypeBehavior.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public void deploy(final Change change, final CommandExecutionContext cec) {
    sqlExecutor.executeWithinContext(change.getPhysicalSchema(env), new Procedure<Connection>() {
        @Override
        public void value(Connection conn) {
            baseArtifactDeployer.deployArtifact(conn, change);
            if (AbstractDbChangeTypeBehavior.this.shouldApplyGrants(change)) {
                AbstractDbChangeTypeBehavior.this.applyGrants(conn, change.getPhysicalSchema(env), change.getObjectName(), env.getPermissions(change), cec);
            }
        }
    });
}
 
Example #26
Source File: IncrementalDbChangeTypeBehavior.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public void undeploy(final Change change) {
    final ChangeIncremental incrementalDeployed = (ChangeIncremental) change;
    if (!incrementalDeployed.isRollbackActivated()) {
        throw new IllegalStateException("Change is intended for rollback, but was not marked as such already; indicates a code issue: " + change);
    }

    getSqlExecutor().executeWithinContext(change.getPhysicalSchema(env), new Procedure<Connection>() {
        @Override
        public void value(Connection conn) {
            getBaseArtifactDeployer().deployArtifact(conn, change);
        }
    });
}
 
Example #27
Source File: DbDeployer.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public void initializeSchema(final DbEnvironment env, PhysicalSchema schema) {
    this.sqlExecutor.executeWithinContext(schema, new Procedure<Connection>() {
        @Override
        public void value(Connection conn) {
            env.getDbTranslationDialect().initSchema(sqlExecutor.getJdbcTemplate(), conn);
        }
    });
}
 
Example #28
Source File: SameSchemaDeployExecutionDao.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public void persistNew(final DeployExecution entry, final PhysicalSchema physicalSchema) {
    sqlExecutor.executeWithinContext(physicalSchema, new Procedure<Connection>() {
        @Override
        public void value(Connection conn) {
            persistNewSameContext(conn, entry, physicalSchema);
        }
    });
}
 
Example #29
Source File: ConcurrentIntObjectHashMap.java    From reladomo with Apache License 2.0 4 votes vote down vote up
public void parallelForEachValue(List<Procedure<V>> blocks, Executor executor)
{
    final AtomicReferenceArray currentArray = this.table;
    int chunks = blocks.size();
    if (chunks > 1)
    {
        FutureTask<?>[] futures = new FutureTask<?>[chunks];
        int chunkSize = currentArray.length() / chunks;
        if (currentArray.length() % chunks != 0)
        {
            chunkSize++;
        }
        for (int i = 0; i < chunks; i++)
        {
            final int start = i * chunkSize;
            final int end = Math.min((i + 1) * chunkSize, currentArray.length() - 1);
            final Procedure<V> block = blocks.get(i);
            futures[i] = new FutureTask(new Runnable()
            {
                public void run()
                {
                    ConcurrentIntObjectHashMap.this.sequentialForEachValue(block, currentArray, start, end);
                }
            }, null);
            executor.execute(futures[i]);
        }
        for (int i = 0; i < chunks; i++)
        {
            try
            {
                futures[i].get();
            }
            catch (Exception e)
            {
                throw new RuntimeException("parallelForEachKeyValue failed", e);
            }
        }
    }
    else
    {
        this.sequentialForEachValue(blocks.get(0), currentArray, 0, currentArray.length());
    }
}
 
Example #30
Source File: Db2ReOrgStatementExecutorIT.java    From obevo with Apache License 2.0 4 votes vote down vote up
private void performReorgExecution(final boolean autoReorgEnabled, final int errorCode, final boolean testBatchUpdate) {
    this.setupExecutor(autoReorgEnabled);
    this.executor.executeWithinContext(physicalSchema, new Procedure<Connection>() {
        @Override
        public void value(Connection conn) {
            try {
                executorJdbc.update(conn, "DROP TABLE a");
            } catch (Exception ignore) {
                // Ignoring the exception, as no clear "DROP TABLE IF EXISTS" is
                // available in DB2
            }

            executorJdbc.update(conn, "create table a (a integer, b integer, c integer, d integer, e integer) ");
            executorJdbc.update(conn, "insert into a (a) values (3)");
            executorJdbc.update(conn, "alter table a drop column b");
            executorJdbc.update(conn, "alter table a drop column c");
            executorJdbc.update(conn, "alter table a drop column d");

            MutableSet<String> expectedColumns = null;
            try {
                Object[][] batchArgs = new Object[][] { new Object[0] };  // need single row of empty args for the batchUpdate calls below
                // this next statement will fire a reorg
                switch (errorCode) {
                case 668:
                    expectedColumns = Sets.mutable.with("A", "E");
                    if (testBatchUpdate) {
                        executorJdbc.batchUpdate(conn, "insert into a (a) values (5)", batchArgs);
                    } else {
                        executorJdbc.update(conn, "insert into a (a) values (5)");
                    }
                    break;
                case 20054:
                    expectedColumns = Sets.mutable.with("A");
                    if (testBatchUpdate) {
                        executorJdbc.batchUpdate(conn, "alter table a drop column e", batchArgs);
                    } else {
                        executorJdbc.update(conn, "alter table a drop column e");
                    }
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported error code for this test: " + errorCode);
                }

                if (!autoReorgEnabled) {
                    fail("Expected an exception here if we do not have autoReorgEnabled");
                }
            } catch (RuntimeException e) {
                if (autoReorgEnabled) {
                    fail("If reorg is enabled, then we should not have thrown an exception here: " + e.getMessage());
                } else {
                    return;
                }
            }

            // Assert the columns which are available in table A
            String columnListSql = "select colname from syscat.COLUMNS where tabschema = '" + physicalSchema.getPhysicalName() + "' AND tabname = 'A'";
            List<String> columnsInTableA = db2JdbcTemplate.query(conn, columnListSql,
                    new ColumnListHandler<String>());
            assertEquals(expectedColumns, Sets.mutable.withAll(columnsInTableA));
        }
    });
}