Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds support for scriptable datasets via Java scripting api (JSR 233) #47

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ It comes with following features:
* Seeding database using:
* [DBUnit](http://dbunit.sourceforge.net/) with **XML**, **XLS**, **YAML** and **JSON** supported as data sets format.
* Custom SQL scripts.
* Script from [JSR 223](http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/) languages.
* Comparing database state at the end of the test using given data sets (with column exclusion).
* Eviction JPA second level cache between test method invocation, see `@JpaCacheEviction`.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.persistence.core.exception;

public class ScriptableDataSetEngineException extends RuntimeException {

private static final long serialVersionUID = 508713667493794528L;

public ScriptableDataSetEngineException() {
}

public ScriptableDataSetEngineException(String message) {
super(message);
}

public ScriptableDataSetEngineException(Throwable cause) {
super(cause);
}

public ScriptableDataSetEngineException(String message, Throwable cause) {
super(message, cause);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.persistence.core.exception;

public class ScriptableDataSetEvaluationException extends RuntimeException {

private static final long serialVersionUID = 508713667493794528L;

public ScriptableDataSetEvaluationException() {
}

public ScriptableDataSetEvaluationException(String message) {
super(message);
}

public ScriptableDataSetEvaluationException(Throwable cause) {
super(cause);
}

public ScriptableDataSetEvaluationException(String message, Throwable cause) {
super(message, cause);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,9 @@ public void should_insert_special_entities_with_custom_end_line() throws Excepti
verify(connection.createStatement(), times(1)).execute(statementsCaptor.capture());
assertThat(statementsCaptor.getAllValues()).containsSequence(
"insert into useraccount (id, firstname, lastname, username, password)" +
" values (1, 'John', 'Smith & Company', 'doovde;;', '&test©')\nGO"
" values (1, 'John', 'Smith & Company', 'doovde;;', '&test©')" +
System.getProperty("line.separator") +
"GO"
);
}

Expand Down
6 changes: 6 additions & 0 deletions dbunit/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,12 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.6</version>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move the version to the property like for other artifacts?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure

</dependency>

</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import org.jboss.arquillian.persistence.dbunit.configuration.DBUnitConfiguration;
import org.jboss.arquillian.persistence.dbunit.configuration.DBUnitDataSeedStrategyProvider;
import org.jboss.arquillian.persistence.dbunit.dataset.DataSetRegister;
import org.jboss.arquillian.persistence.dbunit.dataset.scriptable.ScriptableDataSet;
import org.jboss.arquillian.persistence.dbunit.event.CompareDBUnitData;
import org.jboss.arquillian.persistence.dbunit.event.PrepareDBUnitData;
import org.jboss.arquillian.persistence.dbunit.exception.DBUnitConnectionException;
Expand Down Expand Up @@ -95,7 +96,11 @@ public void compare(@Observes CompareDBUnitData compareDataEvent) {
if (excludeTables.length != 0) {
currentDataSet = new FilteredDataSet(new ExcludeTableFilter(excludeTables), currentDataSet);
}
final IDataSet expectedDataSet = mergeDataSets(dataSetRegister.get().getExpected());
IDataSet expectedDataSet = mergeDataSets(dataSetRegister.get().getExpected());

if (dbunitConfigurationInstance.get().isScriptableDataSets()) {
expectedDataSet = new ScriptableDataSet(expectedDataSet);
}
final DataSetComparator dataSetComparator = new DataSetComparator(compareDataEvent.getSortByColumns(),
compareDataEvent.getColumnsToExclude(), compareDataEvent.getCustomColumnFilters());
dataSetComparator.compare(currentDataSet, expectedDataSet, assertionErrorCollector.get());
Expand Down Expand Up @@ -143,6 +148,10 @@ private void seedDatabase() throws Exception {
final ITableFilter databaseSequenceFilter = sequenceFilterProvider.provide(connection, initialDataSet.getTableNames());
initialDataSet = new FilteredDataSet(databaseSequenceFilter, initialDataSet);
}

if (dbunitConfigurationInstance.get().isScriptableDataSets()) {
initialDataSet = new ScriptableDataSet(initialDataSet);
}
seedingStrategy().execute(connection, initialDataSet);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@ public class DBUnitConfiguration extends Configuration {

private String customTableFilter;

private boolean scriptableDataSets = false;


public DBUnitConfiguration() {
super("persistence-dbunit", "arquillian.extension.persistence.dbunit.");
}
Expand Down Expand Up @@ -436,4 +439,16 @@ public String getCustomTableFilter() {
public void setCustomTableFilter(String customTableFilter) {
this.customTableFilter = customTableFilter;
}

public boolean isScriptableDataSets() {
return scriptableDataSets;
}

/**
* @param scriptableDataSets Enable or disable usage of script language in datasets.
* Default value is <code>false</code>
*/
public void setScriptableDataSets(boolean scriptableDataSets) {
this.scriptableDataSets = scriptableDataSets;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package org.jboss.arquillian.persistence.dbunit.dataset.scriptable;

import org.dbunit.dataset.AbstractDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITableIterator;

/**
* @author <a href="mailto:[email protected]">Rafael Pestano</a>
*
*/
public class ScriptableDataSet extends AbstractDataSet {

private IDataSet delegate;

public ScriptableDataSet(IDataSet delegate) {
this.delegate = delegate;
}

@Override
protected ITableIterator createIterator(boolean reversed) throws DataSetException {
return new ScriptableDataSetIterator(reversed ? delegate.reverseIterator() : delegate.iterator());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.persistence.dbunit.dataset.scriptable;

import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.ITableIterator;
import org.dbunit.dataset.ITableMetaData;

/**
* @author <a href="mailto:[email protected]">Rafael Pestano</a>
*
*/
public class ScriptableDataSetIterator implements ITableIterator{

private ITableIterator delegate;

public ScriptableDataSetIterator(ITableIterator delegate) {
this.delegate = delegate;
}

@Override
public boolean next() throws DataSetException {
return delegate.next();
}

@Override
public ITableMetaData getTableMetaData() throws DataSetException {
return delegate.getTableMetaData();
}

@Override
public ITable getTable() throws DataSetException {
return new ScriptableTable(delegate.getTable());
}



}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.persistence.dbunit.dataset.scriptable;

import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.ITableMetaData;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.HashMap;
import java.util.Map;
import org.jboss.arquillian.persistence.core.exception.ScriptableDataSetEvaluationException;
import org.jboss.arquillian.persistence.core.exception.ScriptableDataSetEngineException;

import java.util.logging.Logger;
import java.util.regex.Pattern;

/**
* Adds support for script language (JSR 223) in table values.
*
* @author <a href="mailto:[email protected]">Rafael Pestano</a>
*/
public class ScriptableTable implements ITable {

//any non digit char followed by ':' followed by 1 or more chars e.g: js: new Date().toString()
private final Pattern scriptEnginePattern = Pattern.compile("^[a-zA-Z]+:.+");

private static Logger log = Logger.getLogger(ScriptableTable.class.getName());

private Map<String, ScriptEngine> engines;

private ScriptEngineManager manager;

private ITable delegate;


public ScriptableTable(ITable delegate) {
this.delegate = delegate;
engines = new HashMap<String, ScriptEngine>();
manager = new ScriptEngineManager();
}

@Override
public ITableMetaData getTableMetaData() {
return delegate.getTableMetaData();
}

@Override
public int getRowCount() {
return delegate.getRowCount();
}

@Override
public Object getValue(int row, String column) throws DataSetException {
Object value = delegate.getValue(row, column);
if (value != null && scriptEnginePattern.matcher(value.toString()).matches()) {
ScriptEngine engine = getScriptEngine(value.toString().trim());
if (engine != null) {
try {
return getScriptResult(value.toString(), engine);
} catch (Exception e) {
throw new ScriptableDataSetEvaluationException(String.format("Could not evaluate script expression for table '%s', column '%s'.", getTableMetaData().getTableName(), column));
}
}
}
return value;
}


/**
* Parses table cell to get script engine
*
* @param value the table cell
* @return scriptEngine
*/
private ScriptEngine getScriptEngine(String value) {
String engineName = value.substring(0, value.indexOf(":"));
if (engines.containsKey(engineName)) {
return engines.get(engineName);
} else {
ScriptEngine engine = manager.getEngineByName(engineName);
if (engine != null) {
engines.put(engineName, engine);
} else {
throw new ScriptableDataSetEngineException(String.format("Could not find script engine with name %s in classpath", engineName));
}
return engine;
}

}

/**
* Evaluates the script expression
*
* @return script expression result
*/
private Object getScriptResult(String script, ScriptEngine engine) throws ScriptException {
String scriptToExecute = script.substring(script.indexOf(":") + 1);
return engine.eval(scriptToExecute);
}

}
Loading