Search in sources :

Example 6 with LRAData

use of io.narayana.lra.LRAData in project narayana by jbosstm.

the class LRAParticipantRecord method tryLocalEndInvocation.

private int tryLocalEndInvocation(URI endPath) {
    URI cId = extractParentLRA(endPath);
    if (cId != null) {
        String[] segments = endPath.getPath().split("/");
        int pCnt = segments.length;
        // this is a call from a parent LRA to end the nested LRA:
        boolean isCompensate = COMPENSATE_REL.equals(segments[pCnt - 1]);
        boolean isComplete = COMPLETE_REL.equals(segments[pCnt - 1]);
        int httpStatus;
        if (!isCompensate && !isComplete) {
            if (LRALogger.logger.isInfoEnabled()) {
                LRALogger.logger.infof("LRAParticipantRecord.doEnd invalid nested participant url %s" + "(should be compensate or complete)", endPath);
            }
            httpStatus = BAD_REQUEST.getStatusCode();
        } else {
            LRAData inVMStatus = lraService.endLRA(cId, isCompensate, true);
            httpStatus = inVMStatus.getHttpStatus();
        }
        return httpStatus;
    }
    return -1;
}
Also used : URI(java.net.URI) LRAData(io.narayana.lra.LRAData)

Example 7 with LRAData

use of io.narayana.lra.LRAData in project narayana by jbosstm.

the class JDBCObjectStoreTest method jdbcStoreTest.

/**
 * This test checks that a new LRA transaction can be created when
 * Narayana is configured to use a JDBC Object Store. This test fails
 * if the Object Store is not set to JDBCStore
 */
@Test
public void jdbcStoreTest() {
    String objectStoreType = BeanPopulator.getDefaultInstance(ObjectStoreEnvironmentBean.class).getObjectStoreType();
    // This test fails if the Object Store is not set to JDBCStore
    assertEquals("The Object Store type should have been set to JDBCStore", JDBCStore.class.getName(), objectStoreType);
    LRALogger.logger.infof("%s: the Object Store type is set to: %s", testName.getMethodName(), objectStoreType);
    // Starts a new LRA
    URI lraIdUri = lraClient.startLRA(testName.getMethodName() + "#newLRA");
    // Checks that the LRA transaction has been created
    assertNotNull("An LRA should have been added to the object store", lraIdUri);
    // Using NarayanaLRAClient, the following statement checks that the status of the new LRA is active
    assertEquals("Expected Active", LRAStatus.Active, getStatus(lraIdUri));
    // Extracts the id from the URI
    String lraId = convertLraUriToString(lraIdUri).replace('_', ':');
    LRAData lraData = getLastCreatedLRA();
    assertEquals("Expected that the LRA transaction just started matches the LRA transaction fetched through the Narayana LRA client", lraData.getLraId(), lraIdUri);
    // Connecting to the database to double check that everything is fine
    String jdbcAccess = BeanPopulator.getDefaultInstance(ObjectStoreEnvironmentBean.class).getJdbcAccess();
    Pattern pattern = Pattern.compile(".*URL=(.*);User=(.*);Password=(.*).*");
    Matcher matcher = pattern.matcher(jdbcAccess);
    // In case the RegEx pattern does not work
    Assert.assertTrue(String.format("The Arjuna's JDBCAccess string:\n %s\n is not formatted as it should", jdbcAccess), matcher.find());
    try (Connection conn = DriverManager.getConnection(matcher.group(1), matcher.group(2), matcher.group(3))) {
        String tablePrefix = BeanPopulator.getDefaultInstance(ObjectStoreEnvironmentBean.class).getTablePrefix();
        Statement st = conn.createStatement();
        // Simple SQL statement to fetch all data from the (PREFIX)JBOSSTSTXTABLE
        ResultSet resultSet = st.executeQuery("SELECT * FROM " + (Objects.isNull(tablePrefix) ? "" : tablePrefix) + "JBOSSTSTXTABLE");
        // Fetches all info from the first row of the ResultSet
        resultSet.first();
        int dbLraStatus = resultSet.getInt(2);
        String dbLraType = resultSet.getString(3);
        // Column where the LRA ID is
        String dbLraId = resultSet.getString(4);
        // Checks that the status of the LRA found in the database is ACTIVE
        assertTrue("Expected that the database holds a Long Running Action transaction", dbLraType.contains("LongRunningAction"));
        // Checks that the ID of the LRA created previously is equal to the ID of the LRA found in the database
        assertEquals(String.format("Expected that the database holds an LRA with ID %s", lraId), dbLraId, lraId);
        // Checks that the status of the LRA found in the database is ACTIVE
        assertEquals("Expected that the database holds an active LRA", LRAStatus.Active.ordinal(), dbLraStatus);
    } catch (SQLException sqlException) {
        LRALogger.logger.errorf("%s: %s", testName.getMethodName(), sqlException.getMessage());
        fail(sqlException.getMessage());
    }
}
Also used : ObjectStoreEnvironmentBean(com.arjuna.ats.arjuna.common.ObjectStoreEnvironmentBean) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) SQLException(java.sql.SQLException) JDBCStore(com.arjuna.ats.internal.arjuna.objectstore.jdbc.JDBCStore) Statement(java.sql.Statement) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) URI(java.net.URI) LRAData(io.narayana.lra.LRAData) Test(org.junit.Test)

Example 8 with LRAData

use of io.narayana.lra.LRAData in project narayana by jbosstm.

the class VolatileObjectStoreTest method volatileStoreTest.

/**
 * This test checks that a new LRA transaction can be created when
 * Narayana is configured to use a Volatile Object Store. This test
 * fails if the Object Store is not set to VolatileStore
 */
@Test
public void volatileStoreTest() {
    String objectStoreType = BeanPopulator.getDefaultInstance(ObjectStoreEnvironmentBean.class).getObjectStoreType();
    // This test fails if the Object Store is not set to Volatile
    assertEquals("The Object Store type should have been set to VolatileStore", VolatileStore.class.getName(), objectStoreType);
    LRALogger.logger.infof("%s: the Object Store type is set to: %s", testName.getMethodName(), objectStoreType);
    // Starts a new LRA
    URI lraIdUri = lraClient.startLRA(testName.getMethodName() + "#newLRA");
    // Checks that the LRA transaction has been created
    assertNotNull("An LRA should have been added to the object store", lraIdUri);
    // Using NarayanaLRAClient, the following statement checks that the status of the new LRA is active
    assertEquals("Expected Active", LRAStatus.Active, getStatus(lraIdUri));
    // Extracts the id from the URI
    String lraId = convertLraUriToString(lraIdUri).replace('_', ':');
    LRAData lraData = getLastCreatedLRA();
    assertEquals("Expected that the LRA transaction just started matches the LRA transaction fetched through the Narayana LRA client", lraData.getLraId(), lraIdUri);
}
Also used : ObjectStoreEnvironmentBean(com.arjuna.ats.arjuna.common.ObjectStoreEnvironmentBean) URI(java.net.URI) LRAData(io.narayana.lra.LRAData) VolatileStore(com.arjuna.ats.internal.arjuna.objectstore.VolatileStore) Test(org.junit.Test)

Example 9 with LRAData

use of io.narayana.lra.LRAData in project narayana by jbosstm.

the class CoordinatorApiIT method startCancelLRA.

/**
 * POST - /start?ClientID=...
 * PUT - /{lraId}/cancel
 * Starting and canceling an LRA.
 */
@Test
public void startCancelLRA() throws UnsupportedEncodingException {
    URI lraId;
    try (Response response = client.target(coordinatorUrl).path("start").queryParam(CLIENT_ID_PARAM_NAME, testRule.getMethodName()).request().post(null)) {
        Assert.assertEquals("Creating top-level LRA should be successful, POST/201 is expected.", Status.CREATED.getStatusCode(), response.getStatus());
        lraId = URI.create(response.readEntity(String.class));
        Assert.assertNotNull("Expected non null LRA id to be returned from start call", lraId);
        lrasToAfterFinish.add(lraId);
        Assert.assertTrue("API version header is expected on response despite no API version header was provided on request", response.getHeaders().containsKey(LRA_API_VERSION_HEADER_NAME));
    }
    Collection<URI> returnedLraIds = lraClient.getAllLRAs().stream().map(LRAData::getLraId).collect(Collectors.toList());
    MatcherAssert.assertThat("Expected the coordinator knows about the LRA", returnedLraIds, hasItem(lraId));
    try (Response response = client.target(coordinatorUrl).path(URLEncoder.encode(lraId.toString(), StandardCharsets.UTF_8.name()) + "/cancel").request().put(null)) {
        // we've closed the LRA manually just now, skipping the @After
        lrasToAfterFinish.clear();
        Assert.assertEquals("Closing LRA should be successful, PUT/200 is expected.", Status.OK.getStatusCode(), response.getStatus());
        Assert.assertEquals("Canceling top-level LRA should return the right status.", LRAStatus.Cancelled.name(), response.readEntity(String.class));
        Assert.assertTrue("API version header is expected on response despite no API header parameter was provided on request", response.getHeaders().containsKey(LRA_API_VERSION_HEADER_NAME));
    }
    Collection<LRAData> activeLRAsAfterClosing = lraClient.getAllLRAs().stream().filter(data -> data.getLraId().equals(lraId)).collect(Collectors.toList());
    MatcherAssert.assertThat("Expecting the started LRA is no more active after closing it", activeLRAsAfterClosing, emptyCollectionOf(LRAData.class));
}
Also used : Response(javax.ws.rs.core.Response) Arrays(java.util.Arrays) URLDecoder(java.net.URLDecoder) Logger(org.jboss.logging.Logger) RunWith(org.junit.runner.RunWith) TestBase(io.narayana.lra.arquillian.TestBase) RunAsClient(org.jboss.arquillian.container.test.api.RunAsClient) IsCollectionContaining.hasItem(org.hamcrest.core.IsCollectionContaining.hasItem) LRAData(io.narayana.lra.LRAData) LRAConstants(io.narayana.lra.LRAConstants) Matchers.lessThan(org.hamcrest.Matchers.lessThan) Matchers.emptyCollectionOf(org.hamcrest.Matchers.emptyCollectionOf) URI(java.net.URI) Status(javax.ws.rs.core.Response.Status) Parameterized(org.junit.runners.Parameterized) IsNot.not(org.hamcrest.core.IsNot.not) ArquillianParametrized(io.narayana.lra.arquillian.ArquillianParametrized) Collection(java.util.Collection) Test(org.junit.Test) Instant(java.time.Instant) Entity(javax.ws.rs.client.Entity) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) GenericType(javax.ws.rs.core.GenericType) URLEncoder(java.net.URLEncoder) List(java.util.List) LRAStatus(org.eclipse.microprofile.lra.annotation.LRAStatus) MatcherAssert(org.hamcrest.MatcherAssert) Rule(org.junit.Rule) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) IsCollectionContaining.hasItems(org.hamcrest.core.IsCollectionContaining.hasItems) Optional(java.util.Optional) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Assert(org.junit.Assert) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Matchers.containsString(org.hamcrest.Matchers.containsString) Link(javax.ws.rs.core.Link) Matchers.containsString(org.hamcrest.Matchers.containsString) URI(java.net.URI) LRAData(io.narayana.lra.LRAData) Test(org.junit.Test)

Example 10 with LRAData

use of io.narayana.lra.LRAData in project narayana by jbosstm.

the class CoordinatorApiIT method getAllLRAsStatusFilter.

/**
 * GET - /?Status=Active
 * To gets active LRAs with status.
 */
@Test
public void getAllLRAsStatusFilter() {
    String clientId1 = testRule.getMethodName() + "_1";
    String clientId2 = testRule.getMethodName() + "_2";
    URI lraId1 = lraClient.startLRA(clientId1);
    URI lraId2 = lraClient.startLRA(lraId1, clientId2, 0L, null);
    lrasToAfterFinish.add(lraId1);
    lraClient.closeLRA(lraId2);
    try (Response response = client.target(coordinatorUrl).request().header(LRA_API_VERSION_HEADER_NAME, version).get()) {
        Assert.assertEquals("Expected that the call succeeds, GET/200.", Status.OK.getStatusCode(), response.getStatus());
        List<LRAData> data = response.readEntity(new GenericType<List<LRAData>>() {
        });
        Assert.assertEquals("Expected API header to be returned with the version provided in request", version, response.getHeaderString(LRA_API_VERSION_HEADER_NAME));
        Collection<URI> returnedLraIds = data.stream().map(LRAData::getLraId).collect(Collectors.toList());
        MatcherAssert.assertThat("Expected the coordinator returns the first started and second closed LRA", returnedLraIds, hasItems(lraId1, lraId2));
    }
    try (Response response = client.target(coordinatorUrl).queryParam(STATUS_PARAM_NAME, "Active").request().get()) {
        Assert.assertEquals("Expected that the call succeeds, GET/200.", Status.OK.getStatusCode(), response.getStatus());
        List<LRAData> data = response.readEntity(new GenericType<List<LRAData>>() {
        });
        Collection<URI> returnedLraIds = data.stream().map(LRAData::getLraId).collect(Collectors.toList());
        MatcherAssert.assertThat("Expected the coordinator returns the first started top-level LRA", returnedLraIds, hasItem(lraId1));
        MatcherAssert.assertThat("Expected the coordinator filtered out the non-active nested LRA", returnedLraIds, not(hasItem(lraId2)));
    }
}
Also used : Response(javax.ws.rs.core.Response) List(java.util.List) Matchers.containsString(org.hamcrest.Matchers.containsString) URI(java.net.URI) LRAData(io.narayana.lra.LRAData) Test(org.junit.Test)

Aggregations

LRAData (io.narayana.lra.LRAData)13 URI (java.net.URI)12 Test (org.junit.Test)9 List (java.util.List)6 Response (javax.ws.rs.core.Response)6 LRAStatus (org.eclipse.microprofile.lra.annotation.LRAStatus)6 Matchers.containsString (org.hamcrest.Matchers.containsString)6 TestBase (io.narayana.lra.arquillian.TestBase)5 Logger (org.jboss.logging.Logger)5 Assert (org.junit.Assert)5 Rule (org.junit.Rule)5 LRAConstants (io.narayana.lra.LRAConstants)4 ArquillianParametrized (io.narayana.lra.arquillian.ArquillianParametrized)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 URLDecoder (java.net.URLDecoder)4 URLEncoder (java.net.URLEncoder)4 StandardCharsets (java.nio.charset.StandardCharsets)4 Instant (java.time.Instant)4 Arrays (java.util.Arrays)4 Collection (java.util.Collection)4