Best Citrus code snippet using com.consol.citrus.jdbc.server.JdbcEndpointAdapterController.AtomicInteger
Source:JdbcEndpointAdapterController.java
...28import org.springframework.util.StringUtils;29import org.springframework.xml.transform.StringResult;30import org.springframework.xml.transform.StringSource;31import java.util.*;32import java.util.concurrent.atomic.AtomicInteger;33import java.util.regex.Pattern;34import java.util.stream.Collectors;35/**36 * @author Christoph Deppisch37 * @since 2.7.338 */39public class JdbcEndpointAdapterController implements JdbcController, EndpointAdapter {40 /** Logger */41 private static Logger log = LoggerFactory.getLogger(JdbcEndpointAdapterController.class);42 private final JdbcEndpointConfiguration endpointConfiguration;43 private final EndpointAdapter delegate;44 private final DataSetCreator dataSetCreator;45 private AtomicInteger connections = new AtomicInteger(0);46 private boolean transactionState;47 protected static final String AUTO_HANDLE_QUERY_PROPERTY = "citrus.jdbc.auto.handle.query";48 protected static final String AUTO_HANDLE_QUERY_ENV = "CITRUS_JDBC_AUTO_HANDLE_QUERY";49 private Pattern autoHandleQueryPattern;50 /**51 * Default constructor using fields.52 * @param endpointConfiguration The endpoint config for the server53 * @param delegate The endpoint adapter to delegate to54 */55 JdbcEndpointAdapterController(56 JdbcEndpointConfiguration endpointConfiguration,57 EndpointAdapter delegate) {58 this(endpointConfiguration, delegate, new DataSetCreator());59 }60 /**61 * Currently just a constructor for testing purposes62 * @param endpointConfiguration he endpoint config for the server63 * @param delegate The endpoint adapter to delegate to64 * @param dataSetCreator The DataSetCreator to use for DataSetGeneration65 */66 JdbcEndpointAdapterController(67 JdbcEndpointConfiguration endpointConfiguration,68 EndpointAdapter delegate,69 DataSetCreator dataSetCreator) {70 this.endpointConfiguration = endpointConfiguration;71 this.delegate = delegate;72 this.dataSetCreator = dataSetCreator;73 String autoHandleQueries = System.getProperty(AUTO_HANDLE_QUERY_PROPERTY, System.getenv(AUTO_HANDLE_QUERY_ENV) != null ?74 System.getenv(AUTO_HANDLE_QUERY_ENV) : StringUtils.arrayToDelimitedString(endpointConfiguration.getAutoHandleQueries(), ";"));75 List<String> autoQueryPatterns = Arrays.stream(autoHandleQueries.split(";"))76 .map(String::trim)77 .filter(validationQuery -> !StringUtils.isEmpty(validationQuery))78 .map(validationQueryPattern -> "(?i)\\A" + validationQueryPattern + "\\Z")79 .collect(Collectors.toList());80 autoHandleQueryPattern = Pattern.compile(String.join("|", autoQueryPatterns));81 }82 @Override83 public Message handleMessage(Message request) {84 if (request.getPayload() instanceof Operation) {85 StringResult result = new StringResult();86 endpointConfiguration.getMarshaller().marshal(request.getPayload(Operation.class), result);87 request.setPayload(result.toString());88 }89 if (log.isDebugEnabled()) {90 log.debug(String.format("Received request on server: '%s':%n%s",91 endpointConfiguration.getServerConfiguration().getDatabaseName(),92 request.getPayload(String.class)));93 }94 if (request.getPayload(Operation.class) != null) {95 String sqlQuery = Optional.ofNullable(request.getPayload(Operation.class).getExecute())96 .map(Execute::getStatement)97 .map(Execute.Statement::getSql)98 .orElse("");99 if (autoHandleQueryPattern.matcher(sqlQuery).find()) {100 log.debug(String.format("Auto handle query '%s' with positive response", sqlQuery));101 JdbcMessage defaultResponse = JdbcMessage.success().rowsUpdated(0);102 defaultResponse.setHeader(MessageHeaders.MESSAGE_TYPE, MessageType.XML.name());103 return defaultResponse;104 }105 }106 return Optional.ofNullable(delegate.handleMessage(request))107 .orElse(JdbcMessage.success());108 }109 /**110 * Opens the connection with the given properties111 * @param properties The properties to open the connection with112 * @throws JdbcServerException In case that the maximum connections have been reached113 */114 @Override115 public void openConnection(Map<String, String> properties) throws JdbcServerException {116 if (!endpointConfiguration.isAutoConnect()) {117 List<OpenConnection.Property> propertyList = convertToPropertyList(properties);118 handleMessageAndCheckResponse(JdbcMessage.openConnection(propertyList));119 }120 if (connections.get() == endpointConfiguration.getServerConfiguration().getMaxConnections()) {121 throw new JdbcServerException(String.format("Maximum number of connections (%s) reached",122 endpointConfiguration.getServerConfiguration().getMaxConnections()));123 }124 connections.incrementAndGet();125 }126 /**127 * Closes the connection128 * @throws JdbcServerException In case that the connection could not be closed129 */130 @Override131 public void closeConnection() throws JdbcServerException {132 if (!endpointConfiguration.isAutoConnect()) {133 handleMessageAndCheckResponse(JdbcMessage.closeConnection());134 }135 if (connections.decrementAndGet() < 0) {136 connections.set(0);137 }138 }139 /**140 * Creates a prepared statement141 * @param stmt The statement to create142 * @throws JdbcServerException In case that the statement was not successful143 */144 @Override145 public void createPreparedStatement(String stmt) throws JdbcServerException {146 if (!endpointConfiguration.isAutoCreateStatement()) {147 handleMessageAndCheckResponse(JdbcMessage.createPreparedStatement(stmt));148 }149 }150 /**151 * Creates a statement152 * @throws JdbcServerException In case that the statement was not successfully created153 */154 @Override155 public void createStatement() throws JdbcServerException {156 if (!endpointConfiguration.isAutoCreateStatement()) {157 handleMessageAndCheckResponse(JdbcMessage.createStatement());158 }159 }160 /**161 * Executes a given query and returns the mapped result162 * @param query The query to execute163 * @return The DataSet containing the query result164 * @throws JdbcServerException In case that the query was not successful165 */166 @Override167 public DataSet executeQuery(String query) throws JdbcServerException {168 log.info("Received execute query request: " + query);169 Message response = handleMessageAndCheckResponse(JdbcMessage.execute(query));170 return dataSetCreator.createDataSet(response, getMessageType(response));171 }172 /**173 * Executes the given statement174 * @param stmt The statement to be executed175 * @throws JdbcServerException In case that the execution was not successful176 */177 @Override178 public DataSet executeStatement(String stmt) throws JdbcServerException {179 log.info("Received execute statement request: " + stmt);180 Message response = handleMessageAndCheckResponse(JdbcMessage.execute(stmt));181 return dataSetCreator.createDataSet(response, getMessageType(response));182 }183 /**184 * Executes the given update185 * @param updateSql The update statement to be executed186 * @throws JdbcServerException In case that the execution was not successful187 */188 @Override189 public int executeUpdate(String updateSql) throws JdbcServerException {190 log.info("Received execute update request: " + updateSql);191 Message response = handleMessageAndCheckResponse(JdbcMessage.execute(updateSql));192 return Optional.ofNullable(193 response.getHeader(JdbcMessageHeaders.JDBC_ROWS_UPDATED))194 .map(Object::toString).map(Integer::valueOf)195 .orElse(0);196 }197 /**198 * Closes the connection199 * @throws JdbcServerException In case that the connection could not be closed200 */201 @Override202 public void closeStatement() throws JdbcServerException {203 if (!endpointConfiguration.isAutoCreateStatement()) {204 handleMessageAndCheckResponse(JdbcMessage.closeStatement());205 }206 }207 /**208 * Sets the transaction state of the database connection209 * @param transactionState The boolean value whether the server is in transaction state.210 */211 @Override212 public void setTransactionState(boolean transactionState) {213 if (log.isDebugEnabled()) {214 log.debug(String.format("Received transaction state change: '%s':%n%s",215 endpointConfiguration.getServerConfiguration().getDatabaseName(),216 String.valueOf(transactionState)));217 }218 this.transactionState = transactionState;219 if(!endpointConfiguration.isAutoTransactionHandling() && transactionState){220 handleMessageAndCheckResponse(JdbcMessage.startTransaction());221 }222 }223 /**224 * Returns the transaction state225 * @return The transaction state of the connection226 */227 @Override228 public boolean getTransactionState() {229 return this.transactionState;230 }231 /**232 * Commits the transaction statements233 */234 @Override235 public void commitStatements() {236 if (log.isDebugEnabled()) {237 log.debug(String.format("Received transaction commit: '%s':%n",238 endpointConfiguration.getServerConfiguration().getDatabaseName()));239 }240 if(!endpointConfiguration.isAutoTransactionHandling()){241 handleMessageAndCheckResponse(JdbcMessage.commitTransaction());242 }243 }244 /**245 * Performs a rollback on the current transaction246 */247 @Override248 public void rollbackStatements() {249 if (log.isDebugEnabled()) {250 log.debug(String.format("Received transaction rollback: '%s':%n",251 endpointConfiguration.getServerConfiguration().getDatabaseName()));252 }253 if(!endpointConfiguration.isAutoTransactionHandling()){254 handleMessageAndCheckResponse(JdbcMessage.rollbackTransaction());255 }256 }257 /**258 * Creates a callable statement259 */260 @Override261 public void createCallableStatement(String sql) {262 if (!endpointConfiguration.isAutoCreateStatement()) {263 handleMessageAndCheckResponse(JdbcMessage.createCallableStatement(sql));264 }265 }266 /**267 * Determines the MessageType of the given response268 * @param response The response to get the message type from269 * @return The MessageType of the response270 */271 private MessageType getMessageType(Message response) {272 String messageTypeString = (String) response.getHeader(MessageHeaders.MESSAGE_TYPE);273 if (MessageType.knows(messageTypeString)){274 return MessageType.valueOf(messageTypeString.toUpperCase());275 }276 return null;277 }278 /**279 * Converts a property map propertyKey -> propertyValue to a list of OpenConnection.Properties280 * @param properties The map to convert281 * @return A list of Properties282 */283 private List<OpenConnection.Property> convertToPropertyList(Map<String, String> properties) {284 return properties.entrySet()285 .stream()286 .map(this::convertToProperty)287 .sorted(Comparator.comparingInt(OpenConnection.Property::hashCode))288 .collect(Collectors.toList());289 }290 /**291 * Converts a Map entry into a OpenConnection.Property292 * @param entry The entry to convert293 * @return the OpenConnection.Property representation294 */295 private OpenConnection.Property convertToProperty(Map.Entry<String, String> entry) {296 OpenConnection.Property property = new OpenConnection.Property();297 property.setName(entry.getKey());298 property.setValue(entry.getValue());299 return property;300 }301 /**302 * Handle request message and check response is successful.303 * @param request The request message to handle304 * @return The response Message305 * @throws JdbcServerException Thrown when the response has some exception header.306 */307 private Message handleMessageAndCheckResponse(Message request) throws JdbcServerException {308 Message response = handleMessage(request);309 checkSuccess(response);310 return response;311 }312 /**313 * Check that response is not having an exception message.314 * @param response The response message to check315 * @throws JdbcServerException In case the message contains a error.316 */317 private void checkSuccess(Message response) throws JdbcServerException {318 OperationResult operationResult = null;319 if (response instanceof JdbcMessage || response.getPayload() instanceof OperationResult) {320 operationResult = response.getPayload(OperationResult.class);321 } else if (response.getPayload() != null && StringUtils.hasText(response.getPayload(String.class))) {322 operationResult = (OperationResult) endpointConfiguration.getMarshaller().unmarshal(new StringSource(response.getPayload(String.class)));323 }324 if (!success(response, operationResult)) {325 throw new JdbcServerException(getExceptionMessage(response, operationResult));326 }327 }328 private String getExceptionMessage(Message response, OperationResult operationResult) {329 return Optional.ofNullable(response.getHeader(JdbcMessageHeaders.JDBC_SERVER_EXCEPTION))330 .map(Object::toString)331 .orElse(Optional.ofNullable(operationResult).map(OperationResult::getException).orElse(""));332 }333 private boolean success(Message response, OperationResult result) {334 return Optional.ofNullable(response.getHeader(JdbcMessageHeaders.JDBC_SERVER_SUCCESS))335 .map(Object::toString)336 .map(Boolean::valueOf)337 .orElse(Optional.ofNullable(result).map(OperationResult::isSuccess).orElse(true));338 }339 @Override340 public Endpoint getEndpoint() {341 return delegate.getEndpoint();342 }343 @Override344 public EndpointConfiguration getEndpointConfiguration() {345 return delegate.getEndpointConfiguration();346 }347 AtomicInteger getConnections() {348 return connections;349 }350}...
AtomicInteger
Using AI Code Generation
1import com.consol.citrus.annotations.CitrusTest2import com.consol.citrus.dsl.junit.JUnit4CitrusTestDesigner3import com.consol.citrus.dsl.junit.JUnit4CitrusTestRunner4import com.consol.citrus.jdbc.server.JdbcEndpointAdapterController5import com.consol.citrus.message.MessageType6import org.junit.runner.RunWith7import java.util.concurrent.atomic.AtomicInteger8@RunWith(JUnit4CitrusTestRunner.class)9class JdbcAutoIncrementTest extends JUnit4CitrusTestDesigner {10 void test() {11 variable("autoIncrement", new AtomicInteger(1))12 endpoint("jdbcServer")13 .adapter()14 .controller(JdbcEndpointAdapterController.class)15 .autoIncrement("person_id", "${autoIncrement}")16 sql(17 statement("INSERT INTO PERSON (FIRST_NAME, LAST_NAME, AGE) VALUES ('John', 'Doe', 42)")18 receive(19 endpoint("jdbcServer")20 .messageType(MessageType.PLAINTEXT)21 .timeout(5000)22 send(23 endpoint("jdbcServer")24 .messageType(MessageType.PLAINTEXT)25 .payload("1")26 }27}
AtomicInteger
Using AI Code Generation
1import com.consol.citrus.dsl.design.TestDesigner;2import com.consol.citrus.dsl.design.TestDesignerBeforeSuiteSupport;3import com.consol.citrus.jdbc.message.JdbcMessage;4import org.springframework.beans.factory.annotation.Autowired;5import org.springframework.jdbc.core.JdbcTemplate;6import org.springframework.jdbc.core.RowMapper;7import org.springframework.stereotype.Component;8import javax.sql.DataSource;9import java.sql.ResultSet;10import java.sql.SQLException;11import java.util.List;12public class JdbcEndpointAdapterControllerTest extends TestDesignerBeforeSuiteSupport {13 private JdbcTemplate jdbcTemplate;14 private DataSource dataSource;15 public void configure(TestDesigner testDesigner) {16 .sql(dataSource)17 .statement("SELECT * FROM CITRUS_USER WHERE ID = 1")18 .validate("ID", "1")19 .validate("FIRST_NAME", "John")20 .validate("LAST_NAME", "Doe");21 .sql(dataSource)22 .statement("UPDATE CITRUS_USER SET LAST_NAME = 'Citrus' WHERE ID = 1")23 .extract("ID", "id");24 .sql(dataSource)25 .statement("SELECT * FROM CITRUS_USER WHERE ID = 1")26 .validate("ID", "1")27 .validate("FIRST_NAME", "John")28 .validate("LAST_NAME", "Citrus");29 .sql(dataSource)30 .statement("UPDATE CITRUS_USER SET LAST_NAME = 'Doe' WHERE ID = 1")31 .extract("ID", "id");32 .sql(dataSource)33 .statement("SELECT * FROM CITRUS_USER WHERE ID = 1")34 .validate("ID", "1")35 .validate("FIRST_NAME", "John")36 .validate("LAST_NAME", "Doe");37 .sql(dataSource)38 .statement("UPDATE CITRUS_USER SET LAST_NAME = 'Citrus' WHERE ID = 1")39 .extract("ID", "id");
AtomicInteger
Using AI Code Generation
1package com.consol.citrus.samples.jdbc;2import com.consol.citrus.annotations.CitrusTest;3import com.consol.citrus.annotations.CitrusXmlTest;4import com.consol.citrus.jdbc.message.JdbcMessage;5import com.consol.citrus.testng.spring.TestNGCitrusSpringSupport;6import org.springframework.beans.factory.annotation.Autowired;7import org.springframework.jdbc.core.JdbcTemplate;8import org.testng.annotations.Test;9import javax.sql.DataSource;10import static org.testng.Assert.assertEquals;11public class JdbcServerSampleIT extends TestNGCitrusSpringSupport {12 private DataSource dataSource;13 @CitrusXmlTest(name = "JdbcServerSampleIT")14 public void testJdbcServer() {15 }16 public void testJdbcEndpointAdapter() {17 JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);18 jdbcTemplate.update("INSERT INTO CUSTOMERS (ID, FIRSTNAME, LASTNAME) VALUES (1, 'John', 'Doe')");19 JdbcMessage request = JdbcMessage.execute("SELECT * FROM CUSTOMERS WHERE ID = 1");20 JdbcMessage response = JdbcMessage.resultSet()21 .column("ID", "1")22 .column("FIRSTNAME", "John")23 .column("LASTNAME", "Doe");24 send(request);25 receive(response);26 }27}
AtomicInteger
Using AI Code Generation
1package com.consol.citrus;2import com.consol.citrus.dsl.endpoint.CitrusEndpoints;3import com.consol.citrus.dsl.junit.JUnit4CitrusTestDesigner;4import com.consol.citrus.jdbc.server.JdbcEndpointAdapterController;5import com.consol.citrus.message.MessageType;6import org.junit.Test;7import org.springframework.jdbc.core.JdbcTemplate;8import org.springframework.jdbc.datasource.DriverManagerDataSource;9import javax.sql.DataSource;10public class JdbcServerIT extends JUnit4CitrusTestDesigner {11 public void test() {12 DataSource dataSource = new DriverManagerDataSource("jdbc:h2:mem:testdb", "sa", "");13 JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);14 jdbcTemplate.execute("create table COUNTERS (ID INTEGER, VALUE INTEGER)");15 jdbcTemplate.update("insert into COUNTERS (ID, VALUE) values (1, 0)");16 JdbcEndpointAdapterController controller = new JdbcEndpointAdapterController();17 controller.setDataSource(dataSource);18 controller.setTableName("COUNTERS");19 controller.setKeyColumn("ID");20 controller.setKeyColumnValue(1);21 controller.setValueColumn("VALUE");22 controller.setAtomicInteger(true);23 variable("counter", CitrusEndpoints.jdbc()24 .server("jdbcServer")25 .controller(controller)26 .query("select VALUE from COUNTERS where ID=1")27 .build());28 echo("Counter value: ${counter}");29 echo("Increment counter value");30 variable("counter", CitrusEndpoints.jdbc()31 .server("jdbcServer")32 .controller(controller)33 .query("select VALUE from COUNTERS where ID=1")34 .build());35 echo("Counter value: ${counter}");36 }37}
AtomicInteger
Using AI Code Generation
1public class JdbcEndpointAdapterControllerTestIT extends AbstractTestNGCitrusTest {2 public void testGetNextSequence() {3 variable("seqName", "SEQ_ID");4 variable("seqValue", "1");5 variable("seqNextValue", "2");6 http()7 .client("httpClient")8 .send()9 .post("/jdbc")10 .contentType(MediaType.APPLICATION_JSON_VALUE)11 .payload("{ \"operation\": \"getNextSequence\", \"sequenceName\": \"${seqName}\" }");12 http()13 .client("httpClient")14 .receive()15 .response(HttpStatus.OK)16 .payload("{ \"sequenceValue\": \"${seqValue}\" }");17 http()18 .client("httpClient")19 .send()20 .post("/jdbc")21 .contentType(MediaType.APPLICATION_JSON_VALUE)22 .payload("{ \"operation\": \"getNextSequence\", \"sequenceName\": \"${seqName}\" }");23 http()24 .client("httpClient")25 .receive()26 .response(HttpStatus.OK)27 .payload("{ \"sequenceValue\": \"${seqNextValue}\" }");28 }29}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!