net.sf.aguacate.context.spi.sql.ContextProcessorSql Maven / Gradle / Ivy
package net.sf.aguacate.context.spi.sql;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.sf.aguacate.context.ContextProcessor;
import net.sf.aguacate.util.config.database.DatabaseBridge;
public class ContextProcessorSql implements ContextProcessor {
private static final Logger LOGGER = LogManager.getLogger(ContextProcessorSql.class);
private final DatabaseBridge databaseBridge;
private final SentenceSql[] sentences;
public ContextProcessorSql(DatabaseBridge databaseBridge, Collection sentences) {
this.databaseBridge = databaseBridge;
this.sentences = sentences.toArray(new SentenceSql[sentences.size()]);
}
@Override
public Object process(String method, Map context) {
try {
Connection connection = databaseBridge.getDataSource().getConnection();
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.warn("using url: {}", connection.getMetaData().getURL());
}
connection.setAutoCommit(false);
return process(method, context, connection);
} finally {
try {
connection.close();
} catch (SQLException e) {
LOGGER.error("on connection close: " + connection.getMetaData().getURL(), e);
}
}
} catch (SQLException e) {
LOGGER.error("on execution", e);
return null;
}
}
private Object process(String method, Map context, Connection connection) throws SQLException {
SentenceExecutionResult last = null;
for (SentenceSql sentence : sentences) {
String name = sentence.getName();
if (sentence.validFor(method)) {
LOGGER.trace("trying to execute {} with: {}", name, context);
SentenceExecutionResult sentenceResult = sentence.execute(databaseBridge.getDatabaseInterface(),
connection, context);
if (sentenceResult.isSuccess()) {
LOGGER.debug("succesful execution of {}", name);
String outputName = sentence.outputName();
if (outputName != null) {
context.put(outputName, sentenceResult.getData());
}
last = sentenceResult;
} else {
LOGGER.warn("unsuccesful execution of {}. stopping ...", name);
if (!connection.getAutoCommit()) {
connection.rollback();
}
return null;
}
} else {
LOGGER.trace("avoid execution: {}", name);
}
}
if (last == null) {
return null;
} else {
if (!connection.getAutoCommit()) {
connection.commit();
}
return last.getData();
}
}
}