Search in sources :

Example 6 with DistributedSystem

use of org.apache.geode.distributed.DistributedSystem in project geode by apache.

the class DataSourceJTAJUnitTest method testMultipleXAResourceCommit.

/**
   * This is to test that if commit is issues thencommit happen for all the XA Resources
   * operations...involved in the transaction
   */
@Test
public void testMultipleXAResourceCommit() throws Exception {
    Region currRegion = null;
    Cache cache;
    DistributedSystem ds = null;
    int tblIDFld;
    String tblNameFld;
    String tblName;
    String tableName = null;
    // boolean to_continue = true;
    final int XA_INSERTS = 3;
    // call to init method
    try {
        Properties props = new Properties();
        String path = TestUtil.getResourcePath(CacheUtils.class, "cachejta.xml");
        props.setProperty(CACHE_XML_FILE, path);
        ds = connect(props);
        tableName = CacheUtils.init(ds, "JTATest");
        // System.out.println ("Table name: " + tableName);
        tblName = tableName;
        if (tableName == null || tableName.equals("")) {
            // to_continue = false;
            fail(" table name not created, Aborting test...");
        }
    } catch (Exception e) {
        // to_continue = false;
        fail(" Aborting test at set up...[" + e + "]", e);
    }
    System.out.println("init for testscenario 5 Successful!");
    // test task
    cache = CacheUtils.getCache();
    tblName = tableName;
    currRegion = cache.getRegion("/root");
    tblIDFld = 1;
    tblNameFld = "test5";
    JTAUtils jtaObj = new JTAUtils(cache, currRegion);
    // to delete all rows inserted in creatTable () of CacheUtils class
    // deleteRows method of JTAUtils class is used.
    jtaObj.deleteRows(tblName);
    // initialize cache and get user transaction
    Context ctx = cache.getJNDIContext();
    UserTransaction ta = null;
    Connection xaCon1 = null, xaCon2 = null, xaCon3 = null;
    try {
        ta = (UserTransaction) ctx.lookup("java:/UserTransaction");
    } catch (NamingException e) {
        fail(" fail in user txn lookup ", e);
    }
    try {
        // Begin the user transaction
        ta.begin();
        // Operation with first XA Resource
        DataSource da1 = (DataSource) ctx.lookup("java:/XAPooledDataSource");
        xaCon1 = da1.getConnection();
        Statement stmt1 = xaCon1.createStatement();
        String sqlSTR;
        for (int i = 0; i < XA_INSERTS; i++) {
            tblIDFld = tblIDFld + i;
            sqlSTR = "insert into " + tblName + " values (" + tblIDFld + "," + "'" + tblNameFld + "'" + ")";
            stmt1.executeUpdate(sqlSTR);
        }
        stmt1.close();
        xaCon1.close();
        // Operation with second XA Resource
        DataSource da2 = (DataSource) ctx.lookup("java:/XAPooledDataSource");
        xaCon2 = da2.getConnection();
        Statement stmt2 = xaCon2.createStatement();
        for (int i = 0; i < XA_INSERTS; i++) {
            tblIDFld = tblIDFld + i + 5;
            sqlSTR = "insert into " + tblName + " values (" + tblIDFld + "," + "'" + tblNameFld + "'" + ")";
            stmt2.executeUpdate(sqlSTR);
        }
        stmt2.close();
        xaCon2.close();
        // Operation with third XA Resource
        DataSource da3 = (DataSource) ctx.lookup("java:/XAPooledDataSource");
        xaCon3 = da3.getConnection();
        Statement stmt3 = xaCon3.createStatement();
        for (int i = 0; i < XA_INSERTS; i++) {
            tblIDFld = tblIDFld + 10;
            sqlSTR = "insert into " + tblName + " values (" + tblIDFld + "," + "'" + tblNameFld + "'" + ")";
            stmt3.executeUpdate(sqlSTR);
        }
        stmt3.close();
        xaCon3.close();
        // commit the transaction
        ta.commit();
        System.out.println("Rows are rolled back in the database");
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (Exception e) {
        fail(" failed ", e);
    } finally {
        if (xaCon1 != null || xaCon2 != null || xaCon3 != null) {
            try {
                // close the connections
                xaCon1.close();
                xaCon2.close();
                xaCon3.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    try {
        int num_rows = jtaObj.getRows(tblName);
        System.out.println("\nNumber of rows in Table under tests are: " + num_rows);
        switch(num_rows) {
            case 0:
                System.out.println("Nothing is committed to database");
                break;
            case 3 * XA_INSERTS:
                System.out.println("All inserts successfully are committed to database");
                break;
            default:
                System.out.println("Looks like that things are messed up...look into it");
        }
    } catch (SQLException sqle) {
        sqle.printStackTrace();
    }
    System.out.println("test task for testScenario5 Succeessful");
    // destroying table
    try {
        System.out.println("Destroying table: " + tblName);
        CacheUtils.destroyTable(tblName);
        System.out.println("Closing cache...");
        System.out.println("destroyTable for testscenario 5 Successful!");
    } catch (Exception e) {
        fail(" failed during tear down of this test...", e);
    } finally {
        CacheUtils.closeCache();
        // CacheUtils.ds.disconnect();
        ds.disconnect();
    }
}
Also used : Context(javax.naming.Context) UserTransaction(javax.transaction.UserTransaction) SQLException(java.sql.SQLException) Statement(java.sql.Statement) Connection(java.sql.Connection) ConfigurationProperties(org.apache.geode.distributed.ConfigurationProperties) Properties(java.util.Properties) DistributedSystem(org.apache.geode.distributed.DistributedSystem) InternalDistributedSystem(org.apache.geode.distributed.internal.InternalDistributedSystem) NamingException(javax.naming.NamingException) SQLException(java.sql.SQLException) DataSource(javax.sql.DataSource) Region(org.apache.geode.cache.Region) NamingException(javax.naming.NamingException) Cache(org.apache.geode.cache.Cache) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 7 with DistributedSystem

use of org.apache.geode.distributed.DistributedSystem in project geode by apache.

the class BlockingTimeOutJUnitTest method init.

@SuppressWarnings("deprecation")
private static String init(String className) throws Exception {
    DistributedSystem ds = InternalDistributedSystem.getConnectedInstance();
    if (ds != null) {
        ds.disconnect();
    }
    logger.debug("PATH11 ");
    Properties props = new Properties();
    String path = System.getProperty("CACHEXMLFILE");
    logger.debug("PATH2 " + path);
    int pid = RANDOM;
    path = File.createTempFile("dunit-cachejta_", ".xml").getAbsolutePath();
    logger.debug("PATH " + path);
    /** * Return file as string and then modify the string accordingly ** */
    String file_as_str = readFile(TestUtil.getResourcePath(CacheUtils.class, "cachejta.xml"));
    file_as_str = file_as_str.replaceAll("newDB", "newDB_" + pid);
    String modified_file_str = modifyFile(file_as_str);
    FileOutputStream fos = new FileOutputStream(path);
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(fos));
    wr.write(modified_file_str);
    wr.flush();
    wr.close();
    props.setProperty(CACHE_XML_FILE, path);
    props.setProperty(MCAST_PORT, "0");
    props.setProperty(LOCATORS, "");
    String tableName = "";
    cache = new CacheFactory(props).create();
    if (className != null && !className.equals("")) {
        String time = new Long(System.currentTimeMillis()).toString();
        tableName = className + time;
        createTable(tableName);
    }
    tblName = tableName;
    return tableName;
}
Also used : ConfigurationProperties(org.apache.geode.distributed.ConfigurationProperties) Properties(java.util.Properties) CacheFactory(org.apache.geode.cache.CacheFactory) DistributedSystem(org.apache.geode.distributed.DistributedSystem) InternalDistributedSystem(org.apache.geode.distributed.internal.InternalDistributedSystem)

Example 8 with DistributedSystem

use of org.apache.geode.distributed.DistributedSystem in project geode by apache.

the class AtomicStatsJUnitTest method testConcurrentGets.

/**
   * Test for bug 41340. Do two gets at the same time of a dirty stat, and make sure we get the
   * correct value for the stat.
   * 
   * @throws Throwable
   */
@Test
public void testConcurrentGets() throws Throwable {
    Properties props = new Properties();
    props.setProperty(MCAST_PORT, "0");
    // props.setProperty("statistic-sample-rate", "60000");
    props.setProperty(STATISTIC_SAMPLING_ENABLED, "false");
    DistributedSystem ds = DistributedSystem.connect(props);
    String statName = "TestStats";
    String statDescription = "Tests stats";
    final String statDesc = "blah blah blah";
    StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
    StatisticsType type = f.createType(statName, statDescription, new StatisticDescriptor[] { f.createIntGauge("stat", statDesc, "bottles of beer on the wall") });
    final int statId = type.nameToId("stat");
    try {
        final AtomicReference<Statistics> statsRef = new AtomicReference<Statistics>();
        final CyclicBarrier beforeIncrement = new CyclicBarrier(3);
        final CyclicBarrier afterIncrement = new CyclicBarrier(3);
        Thread thread1 = new Thread("thread1") {

            public void run() {
                try {
                    while (true) {
                        beforeIncrement.await();
                        statsRef.get().incInt(statId, 1);
                        afterIncrement.await();
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        Thread thread3 = new Thread("thread1") {

            public void run() {
                try {
                    while (true) {
                        beforeIncrement.await();
                        afterIncrement.await();
                        statsRef.get().getInt(statId);
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        thread1.start();
        thread3.start();
        for (int i = 0; i < 5000; i++) {
            Statistics stats = ds.createAtomicStatistics(type, "stats");
            statsRef.set(stats);
            beforeIncrement.await();
            afterIncrement.await();
            assertEquals("On loop " + i, 1, stats.getInt(statId));
            stats.close();
        }
    } finally {
        ds.disconnect();
    }
}
Also used : BrokenBarrierException(java.util.concurrent.BrokenBarrierException) StatisticsType(org.apache.geode.StatisticsType) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConfigurationProperties(org.apache.geode.distributed.ConfigurationProperties) Properties(java.util.Properties) DistributedSystem(org.apache.geode.distributed.DistributedSystem) Statistics(org.apache.geode.Statistics) CyclicBarrier(java.util.concurrent.CyclicBarrier) StatisticsTypeFactory(org.apache.geode.StatisticsTypeFactory) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 9 with DistributedSystem

use of org.apache.geode.distributed.DistributedSystem in project geode by apache.

the class ListIndexFunctionJUnitTest method testExecuteThrowsException.

@Test(expected = RuntimeException.class)
public void testExecuteThrowsException() throws Throwable {
    final Cache mockCache = mockContext.mock(Cache.class, "Cache");
    final DistributedSystem mockDistributedSystem = mockContext.mock(DistributedSystem.class, "DistributedSystem");
    final DistributedMember mockDistributedMember = mockContext.mock(DistributedMember.class, "DistributedMember");
    final QueryService mockQueryService = mockContext.mock(QueryService.class, "QueryService");
    final FunctionContext mockFunctionContext = mockContext.mock(FunctionContext.class, "FunctionContext");
    final TestResultSender testResultSender = new TestResultSender();
    mockContext.checking(new Expectations() {

        {
            oneOf(mockCache).getDistributedSystem();
            will(returnValue(mockDistributedSystem));
            oneOf(mockCache).getQueryService();
            will(returnValue(mockQueryService));
            oneOf(mockDistributedSystem).getDistributedMember();
            will(returnValue(mockDistributedMember));
            oneOf(mockQueryService).getIndexes();
            will(throwException(new RuntimeException("expected")));
            oneOf(mockFunctionContext).getResultSender();
            will(returnValue(testResultSender));
        }
    });
    final ListIndexFunction function = createListIndexFunction(mockCache);
    function.execute(mockFunctionContext);
    try {
        testResultSender.getResults();
    } catch (Throwable t) {
        assertTrue(t instanceof RuntimeException);
        assertEquals("expected", t.getMessage());
        throw t;
    }
}
Also used : Expectations(org.jmock.Expectations) QueryService(org.apache.geode.cache.query.QueryService) DistributedMember(org.apache.geode.distributed.DistributedMember) DistributedSystem(org.apache.geode.distributed.DistributedSystem) FunctionContext(org.apache.geode.cache.execute.FunctionContext) Cache(org.apache.geode.cache.Cache) UnitTest(org.apache.geode.test.junit.categories.UnitTest) Test(org.junit.Test)

Example 10 with DistributedSystem

use of org.apache.geode.distributed.DistributedSystem in project geode by apache.

the class EvictionStatsDUnitTest method createCache.

public void createCache() {
    try {
        Properties props = new Properties();
        DistributedSystem ds = getSystem(props);
        assertNotNull(ds);
        ds.disconnect();
        ds = getSystem(props);
        cache = CacheFactory.create(ds);
        assertNotNull(cache);
        LogWriterUtils.getLogWriter().info("cache= " + cache);
        LogWriterUtils.getLogWriter().info("cache closed= " + cache.isClosed());
        cache.getResourceManager().setEvictionHeapPercentage(20);
    } catch (Exception e) {
        Assert.fail("Failed while creating the cache", e);
    }
}
Also used : Properties(java.util.Properties) DistributedSystem(org.apache.geode.distributed.DistributedSystem) CacheException(org.apache.geode.cache.CacheException) IgnoredException(org.apache.geode.test.dunit.IgnoredException)

Aggregations

DistributedSystem (org.apache.geode.distributed.DistributedSystem)250 Properties (java.util.Properties)102 InternalDistributedSystem (org.apache.geode.distributed.internal.InternalDistributedSystem)65 ConfigurationProperties (org.apache.geode.distributed.ConfigurationProperties)61 Test (org.junit.Test)59 Cache (org.apache.geode.cache.Cache)55 AttributesFactory (org.apache.geode.cache.AttributesFactory)34 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)30 Region (org.apache.geode.cache.Region)24 IOException (java.io.IOException)20 CacheServer (org.apache.geode.cache.server.CacheServer)20 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)20 InternalCache (org.apache.geode.internal.cache.InternalCache)16 IgnoredException (org.apache.geode.test.dunit.IgnoredException)16 ArrayList (java.util.ArrayList)15 LogWriter (org.apache.geode.LogWriter)15 DistributedMember (org.apache.geode.distributed.DistributedMember)15 LocalRegion (org.apache.geode.internal.cache.LocalRegion)15 RegionAttributes (org.apache.geode.cache.RegionAttributes)14 Pool (org.apache.geode.cache.client.Pool)14