Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
- added DataSetScriptReplacer
- Travis badget
  • Loading branch information
rmpestano committed Apr 29, 2016
1 parent a3b43d5 commit cf9f93c
Show file tree
Hide file tree
Showing 7 changed files with 196 additions and 3 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
## Arquillian Persistence Extension

[![Build Status](https://travis-ci.org/rmpestano/arquillian-extension-persistence.png)](https://travis-ci.org/rmpestano/arquillian-extension-persistence)


### What is this?

**Arquillian Persistence Extension** was created to help you writing tests where persistence layer is involved.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ 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©')\r\nGO"
);
}

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

<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.6</version>
<scope>test</scope>
</dependency>

</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* 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.data.replacement;

import org.dbunit.dataset.*;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

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

//any non digit char followed by ':' followed by 1 or more chars e.g: js: new Date().toString()
private final Pattern scriptEnginePattern = Pattern.compile(".*\\D.*:.+");

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

private Map<String, ScriptEngine> engines;

private ScriptEngineManager manager;

public DataSetScriptReplacer() {
engines = new HashMap<String, ScriptEngine>();
manager = new ScriptEngineManager();
}

public IDataSet replace(IDataSet dataset) {
ReplacementDataSet replacementDataSet = new ReplacementDataSet(dataset);
try {
replaceScripts(replacementDataSet);
} catch (DataSetException e) {
log.log(Level.WARNING, "Could not replace dataset: " + dataset, e);
}
return replacementDataSet;
}

private void replaceScripts(ReplacementDataSet dataSet) throws DataSetException {
ITableIterator iterator = dataSet.iterator();
while (iterator.next()) {
ITable table = iterator.getTable();
for (Column column : table.getTableMetaData().getColumns()) {
for (int i = 0; i < table.getRowCount(); i++) {
Object value = table.getValue(i, column.getColumnName());
if(value != null){
if (scriptEnginePattern.matcher(value.toString()).matches()) {
ScriptEngine engine = getScriptEngine(value.toString().trim());
if (engine != null) {
Object scriptResult = getScriptResult(value.toString(), engine);
if (scriptResult != null) {
dataSet.addReplacementObject(value, scriptResult);
} else {
throw new RuntimeException(String.format("Could not perform script replacement for table '%s', column '%s'.", table.getTableMetaData().getTableName(), column.getColumnName()));
}
}
}
}
}
}
}
}

/**
* 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 {
log.warning(String.format("Could not find script engine with name %s in classpath", engineName));
}
return engine;
}

}

private Object getScriptResult(String script, ScriptEngine engine) {
String scriptToExecute = script.substring(script.indexOf(":") + 1);
try {
return engine.eval(scriptToExecute);
} catch (Exception e) {
log.log(Level.WARNING, "Could not perform replacement for script: " + script, e);
return null;
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* 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.replacer;

import org.dbunit.dataset.IDataSet;
import org.jboss.arquillian.persistence.dbunit.data.replacement.DataSetScriptReplacer;
import org.jboss.arquillian.persistence.dbunit.dataset.yaml.YamlDataSet;
import org.jboss.arquillian.persistence.testutils.FileLoader;
import org.jboss.arquillian.persistence.testutils.TableAssert;
import org.junit.After;
import org.junit.Test;

import java.io.InputStream;
import java.util.Date;

public class ScriptReplacerTest {

InputStream input;

@After
public void closeStream() {
FileLoader.close(input);
}

@Test
public void should_load_all_rows_with_content_for_table_from_yaml_file() throws Exception {
// given
input = FileLoader.load("scriptable.yml");

// when
IDataSet yamlDataSet = new YamlDataSet(input);
yamlDataSet = new DataSetScriptReplacer().replace(yamlDataSet);

// then
TableAssert.assertThat(yamlDataSet.getTable("useraccount"))
.hasRow("id: 1", "firstname: John", "lastname: Smith", "username: doovde", "password: password", "age: 42.0")
.hasRow("id: 2", "firstname: Clark", "lastname: Kent", "username: superman", "password: kryptonite", "email: [email protected]", "birthdate: "+new Date());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,9 @@ private List<Row> extractRows() {
private Map<String, String> extractRow(int rowIndex, final List<String> columnNames) throws DataSetException {
final Map<String, String> cells = new HashMap<String, String>();
for (String columnName : columnNames) {
String value = (String) actual.getValue(rowIndex, columnName);
Object value = actual.getValue(rowIndex, columnName);
if (value != null) {
cells.put(columnName, value);
cells.put(columnName, value.toString());
}
}
return cells;
Expand Down
14 changes: 14 additions & 0 deletions dbunit/src/test/resources/scriptable.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
useraccount:
- id: 1
firstname: John
lastname: Smith
username: doovde
password: password
age: "js:var a=1;var b=1; 40 + a + b"
- id: 2
firstname: Clark
lastname: Kent
username: superman
password: kryptonite
email: [email protected]
birthdate: "groovy: new Date()"

0 comments on commit cf9f93c

Please sign in to comment.