Search in sources :

Example 1 with Flushable

use of java.io.Flushable in project neo4j by neo4j.

the class BatchingTransactionAppenderTest method shouldBeAbleToWriteACheckPoint.

@Test
public void shouldBeAbleToWriteACheckPoint() throws Throwable {
    // Given
    FlushablePositionAwareChannel channel = mock(FlushablePositionAwareChannel.class, RETURNS_MOCKS);
    Flushable flushable = mock(Flushable.class);
    when(channel.prepareForFlush()).thenReturn(flushable);
    when(channel.putLong(anyLong())).thenReturn(channel);
    when(logFile.getWriter()).thenReturn(channel);
    BatchingTransactionAppender appender = life.add(new BatchingTransactionAppender(logFile, NO_ROTATION, positionCache, transactionIdStore, BYPASS, databaseHealth));
    // When
    appender.checkPoint(new LogPosition(1L, 2L), LogCheckPointEvent.NULL);
    // Then
    verify(channel, times(1)).putLong(1L);
    verify(channel, times(1)).putLong(2L);
    verify(channel, times(1)).prepareForFlush();
    verify(flushable, times(1)).flush();
    verifyZeroInteractions(databaseHealth);
}
Also used : Flushable(java.io.Flushable) Test(org.junit.Test)

Example 2 with Flushable

use of java.io.Flushable in project tomee by apache.

the class MdbInstanceManager method deploy.

public void deploy(final BeanContext beanContext, final ActivationSpec activationSpec, final EndpointFactory endpointFactory) throws OpenEJBException {
    if (inboundRecovery != null) {
        inboundRecovery.recover(resourceAdapter, activationSpec, containerID.toString());
    }
    final ObjectRecipe recipe = PassthroughFactory.recipe(new Pool.Builder(poolBuilder));
    recipe.allow(Option.CASE_INSENSITIVE_FACTORY);
    recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
    recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
    recipe.setAllProperties(beanContext.getProperties());
    final Pool.Builder builder = (Pool.Builder) recipe.create();
    setDefault(builder.getMaxAge(), TimeUnit.HOURS);
    setDefault(builder.getIdleTimeout(), TimeUnit.MINUTES);
    setDefault(builder.getInterval(), TimeUnit.MINUTES);
    final InstanceSupplier supplier = new InstanceSupplier(beanContext);
    builder.setSupplier(supplier);
    builder.setExecutor(executor);
    builder.setScheduledExecutor(scheduledExecutor);
    final int min = builder.getMin();
    final long maxAge = builder.getMaxAge().getTime(TimeUnit.MILLISECONDS);
    final double maxAgeOffset = builder.getMaxAgeOffset();
    final Data data = new Data(builder.build(), accessTimeout, closeTimeout);
    MdbContext mdbContext = new MdbContext(securityService, new Flushable() {

        @Override
        public void flush() throws IOException {
            data.flush();
        }
    });
    data.setBaseContext(mdbContext);
    beanContext.setContainerData(data);
    final MBeanServer server = LocalMBeanServer.get();
    final ObjectNameBuilder jmxName = new ObjectNameBuilder("openejb.management");
    jmxName.set("J2EEServer", "openejb");
    jmxName.set("J2EEApplication", null);
    jmxName.set("EJBModule", beanContext.getModuleID());
    jmxName.set("MessageDrivenBean", beanContext.getEjbName());
    jmxName.set("j2eeType", "");
    jmxName.set("name", beanContext.getEjbName());
    // Create stats interceptor
    if (StatsInterceptor.isStatsActivated()) {
        final StatsInterceptor stats = new StatsInterceptor(beanContext.getBeanClass());
        beanContext.addFirstSystemInterceptor(stats);
        // register the invocation stats interceptor
        try {
            final ObjectName objectName = jmxName.set("j2eeType", "Invocations").build();
            if (server.isRegistered(objectName)) {
                server.unregisterMBean(objectName);
            }
            server.registerMBean(new ManagedMBean(stats), objectName);
            jmxNames.add(objectName);
        } catch (final Exception e) {
            logger.error("Unable to register MBean ", e);
        }
    }
    // activate the endpoint
    try {
        final MdbPoolContainer.MdbActivationContext activationContext = new MdbPoolContainer.MdbActivationContext(Thread.currentThread().getContextClassLoader(), beanContext, resourceAdapter, endpointFactory, activationSpec);
        activationContexts.put(beanContext, activationContext);
        boolean activeOnStartup = true;
        String activeOnStartupSetting = beanContext.getActivationProperties().get("MdbActiveOnStartup");
        if (activeOnStartupSetting == null) {
            activeOnStartupSetting = beanContext.getActivationProperties().get("DeliveryActive");
        }
        if (activeOnStartupSetting != null) {
            activeOnStartup = Boolean.parseBoolean(activeOnStartupSetting);
        }
        if (activeOnStartup) {
            activationContext.start();
        } else {
            logger.info("Not auto-activating endpoint for " + beanContext.getDeploymentID());
        }
        String jmxControlName = beanContext.getActivationProperties().get("MdbJMXControl");
        if (jmxControlName == null) {
            jmxControlName = "true";
        }
        addJMxControl(beanContext, jmxControlName, activationContext);
    } catch (final ResourceException e) {
        throw new OpenEJBException(e);
    }
    final Options options = new Options(beanContext.getProperties());
    // Finally, fill the pool and start it
    if (!options.get("BackgroundStartup", false) && min > 0) {
        final ExecutorService es = Executors.newFixedThreadPool(min);
        for (int i = 0; i < min; i++) {
            es.submit(new InstanceCreatorRunnable(maxAge, i, min, maxAgeOffset, data, supplier));
        }
        es.shutdown();
        try {
            es.awaitTermination(5, TimeUnit.MINUTES);
        } catch (final InterruptedException e) {
            logger.error("can't fill the message driven bean pool", e);
        }
    }
    // register the pool
    try {
        final ObjectName objectName = jmxName.set("j2eeType", "Pool").build();
        if (server.isRegistered(objectName)) {
            server.unregisterMBean(objectName);
        }
        server.registerMBean(new ManagedMBean(data.pool), objectName);
        data.add(objectName);
    } catch (final Exception e) {
        logger.error("Unable to register MBean ", e);
    }
    data.getPool().start();
}
Also used : OpenEJBException(org.apache.openejb.OpenEJBException) Options(org.apache.openejb.loader.Options) ObjectNameBuilder(org.apache.openejb.monitoring.ObjectNameBuilder) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) Pool(org.apache.openejb.util.Pool) ResourceException(javax.resource.ResourceException) MBeanServer(javax.management.MBeanServer) LocalMBeanServer(org.apache.openejb.monitoring.LocalMBeanServer) StatsInterceptor(org.apache.openejb.monitoring.StatsInterceptor) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData) IOException(java.io.IOException) Flushable(java.io.Flushable) ResourceException(javax.resource.ResourceException) TimeoutException(java.util.concurrent.TimeoutException) ReflectionException(javax.management.ReflectionException) ConcurrentAccessTimeoutException(javax.ejb.ConcurrentAccessTimeoutException) OpenEJBException(org.apache.openejb.OpenEJBException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(java.rmi.RemoteException) MalformedObjectNameException(javax.management.MalformedObjectNameException) SystemException(org.apache.openejb.SystemException) AttributeNotFoundException(javax.management.AttributeNotFoundException) ApplicationException(org.apache.openejb.ApplicationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) IOException(java.io.IOException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) MBeanException(javax.management.MBeanException) ObjectName(javax.management.ObjectName) ObjectNameBuilder(org.apache.openejb.monitoring.ObjectNameBuilder) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) ManagedMBean(org.apache.openejb.monitoring.ManagedMBean)

Example 3 with Flushable

use of java.io.Flushable in project closure-templates by google.

the class CountingFlushableAppendableTest method testAppendAndFlush.

@Test
public void testAppendAndFlush() throws Exception {
    final StringBuilder progress = new StringBuilder();
    Flushable flushable = new Flushable() {

        @Override
        public void flush() {
            progress.append("F");
        }
    };
    CountingFlushableAppendable c = new CountingFlushableAppendable(progress, flushable);
    assertThat(c.getAppendedCountSinceLastFlush()).isEqualTo(0);
    c.append("12");
    assertThat(c.getAppendedCountSinceLastFlush()).isEqualTo(2);
    c.append("3");
    assertThat(c.getAppendedCountSinceLastFlush()).isEqualTo(3);
    c.flush();
    assertThat(c.getAppendedCountSinceLastFlush()).isEqualTo(0);
    c.append('c');
    assertThat(c.getAppendedCountSinceLastFlush()).isEqualTo(1);
    c.append("123", 1, 2);
    assertThat(progress.toString()).isEqualTo("123Fc2");
}
Also used : Flushable(java.io.Flushable) Test(org.junit.Test)

Example 4 with Flushable

use of java.io.Flushable in project spring-integration by spring-projects.

the class PersistentAcceptOnceFileListFilterTests method testFlush.

@Test
public /*
	 * INT-3721: Test all operations that can cause the metadata to be flushed.
	 */
void testFlush() throws Exception {
    final AtomicInteger flushes = new AtomicInteger();
    final AtomicBoolean replaced = new AtomicBoolean();
    class MS extends SimpleMetadataStore implements Flushable, Closeable {

        @Override
        public void flush() throws IOException {
            flushes.incrementAndGet();
        }

        @Override
        public void close() throws IOException {
            flush();
        }

        @Override
        public boolean replace(String key, String oldValue, String newValue) {
            replaced.set(true);
            return super.replace(key, oldValue, newValue);
        }
    }
    MS store = new MS();
    String prefix = "flush:";
    FileSystemPersistentAcceptOnceFileListFilter filter = new FileSystemPersistentAcceptOnceFileListFilter(store, prefix);
    final File file = File.createTempFile("foo", ".txt");
    File[] files = new File[] { file };
    List<File> passed = filter.filterFiles(files);
    assertTrue(Arrays.equals(files, passed.toArray()));
    filter.rollback(passed.get(0), passed);
    assertEquals(0, flushes.get());
    filter.setFlushOnUpdate(true);
    passed = filter.filterFiles(files);
    assertTrue(Arrays.equals(files, passed.toArray()));
    assertEquals(1, flushes.get());
    filter.rollback(passed.get(0), passed);
    assertEquals(2, flushes.get());
    passed = filter.filterFiles(files);
    assertTrue(Arrays.equals(files, passed.toArray()));
    assertEquals(3, flushes.get());
    passed = filter.filterFiles(files);
    assertEquals(0, passed.size());
    assertEquals(3, flushes.get());
    assertFalse(replaced.get());
    store.put(prefix + file.getAbsolutePath(), "1");
    passed = filter.filterFiles(files);
    assertTrue(Arrays.equals(files, passed.toArray()));
    assertEquals(4, flushes.get());
    assertTrue(replaced.get());
    file.delete();
    filter.close();
    assertEquals(5, flushes.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Closeable(java.io.Closeable) SimpleMetadataStore(org.springframework.integration.metadata.SimpleMetadataStore) Flushable(java.io.Flushable) File(java.io.File) Test(org.junit.Test)

Example 5 with Flushable

use of java.io.Flushable in project neo4j by neo4j.

the class BatchingTransactionAppenderTest method shouldNotCallTransactionClosedOnFailedForceLogToDisk.

@Test
void shouldNotCallTransactionClosedOnFailedForceLogToDisk() throws Exception {
    // GIVEN
    long txId = 3;
    String failureMessage = "Forces a failure";
    FlushablePositionAwareChecksumChannel channel = spy(new InMemoryClosableChannel());
    IOException failure = new IOException(failureMessage);
    final Flushable flushable = mock(Flushable.class);
    doAnswer(invocation -> {
        invocation.callRealMethod();
        return flushable;
    }).when(channel).prepareForFlush();
    when(logFile.forceAfterAppend(any())).thenThrow(failure);
    when(logFile.getTransactionLogWriter()).thenReturn(new TransactionLogWriter(channel, new DbmsLogEntryWriterFactory(() -> LATEST)));
    TransactionMetadataCache metadataCache = new TransactionMetadataCache();
    TransactionIdStore transactionIdStore = mock(TransactionIdStore.class);
    when(transactionIdStore.nextCommittingTransactionId()).thenReturn(txId);
    when(transactionIdStore.getLastCommittedTransaction()).thenReturn(new TransactionId(txId, BASE_TX_CHECKSUM, BASE_TX_COMMIT_TIMESTAMP));
    TransactionAppender appender = life.add(new BatchingTransactionAppender(logFiles, NO_ROTATION, metadataCache, transactionIdStore, databaseHealth));
    // WHEN
    TransactionRepresentation transaction = mock(TransactionRepresentation.class);
    when(transaction.additionalHeader()).thenReturn(new byte[0]);
    var e = assertThrows(IOException.class, () -> appender.append(new TransactionToApply(transaction, NULL), logAppendEvent));
    assertSame(failure, e);
    verify(transactionIdStore).nextCommittingTransactionId();
    verify(transactionIdStore, never()).transactionClosed(eq(txId), anyLong(), anyLong(), any(CursorContext.class));
}
Also used : TransactionToApply(org.neo4j.kernel.impl.api.TransactionToApply) TransactionIdStore(org.neo4j.storageengine.api.TransactionIdStore) CommittedTransactionRepresentation(org.neo4j.kernel.impl.transaction.CommittedTransactionRepresentation) TransactionRepresentation(org.neo4j.kernel.impl.transaction.TransactionRepresentation) IOException(java.io.IOException) CursorContext(org.neo4j.io.pagecache.context.CursorContext) Flushable(java.io.Flushable) TransactionId(org.neo4j.storageengine.api.TransactionId) DbmsLogEntryWriterFactory(org.neo4j.kernel.database.DbmsLogEntryWriterFactory) Test(org.junit.jupiter.api.Test)

Aggregations

Flushable (java.io.Flushable)12 Test (org.junit.Test)4 IOException (java.io.IOException)3 Test (org.junit.jupiter.api.Test)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Path (java.nio.file.Path)2 RepeatedTest (org.junit.jupiter.api.RepeatedTest)2 MajorFlushEvent (org.neo4j.io.pagecache.tracing.MajorFlushEvent)2 BinaryLatch (org.neo4j.util.concurrent.BinaryLatch)2 SoyDict (com.google.template.soy.data.SoyDict)1 SoyRecord (com.google.template.soy.data.SoyRecord)1 TemplateRegistry (com.google.template.soy.soytree.TemplateRegistry)1 Closeable (java.io.Closeable)1 File (java.io.File)1 ClosedChannelException (java.nio.channels.ClosedChannelException)1 RemoteException (java.rmi.RemoteException)1 Formatter (java.util.Formatter)1 FormatterClosedException (java.util.FormatterClosedException)1 ExecutorService (java.util.concurrent.ExecutorService)1 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)1