Skip to content

Instantly share code, notes, and snippets.

@DanyelMorales
Last active August 22, 2018 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanyelMorales/035cbe38ab93ac661750b263f6ea654e to your computer and use it in GitHub Desktop.
Save DanyelMorales/035cbe38ab93ac661750b263f6ea654e to your computer and use it in GitHub Desktop.
JAVA DROPWIZARD 0.7 example for common test utils
package anyp;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Set;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.AfterClass;
import org.junit.Rule;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import io.dropwizard.auth.basic.BasicAuthProvider;
/**
* @author Daniel Vera Morales
*/
abstract public class AbstractCommon extends AbstractSubject implements Observer {
/**
* Sequence restoring
*/
public static SequenceJunitRule sequences = new SequenceJunitRule();
protected final static DAOTestUtil utils = new DAOTestUtil();
@SuppressWarnings("unused")
private static final Properties testProp = utils.getPropertiesFromFile("test.properties");
/**
* Restore the sequences on Class DIE.
*/
@AfterClass
public static void tearDownClass() {
if (sequences.isConfigured() && !sequences.validateOnce()) {
sequences.restoreSequences();
}
}
protected SessionFactory factory = null;
protected Session session = null;
protected Transaction transac = null;
protected String sqlFiles;
/**
* Entity commons
*/
protected AnySequenceHelperForNAmes hibernateDependencies = new AnySequenceHelperForNAmes();
protected EntityDependencyContainer entityCommon = new EntityDependencyContainer();
/**
* MAIN JUNIT RULE ==============================
*/
@Rule
public DAOTestRule daoTestRule = this.getDAOTestRule(Global.URL, Global.DRIVER, Global.USER,
Global.PASSWORD);
/**
* @param s
*/
@SuppressWarnings("unchecked")
public void addAuthProvider(Set<Object> s) {
@SuppressWarnings("rawtypes")
final BasicAuthProvider<SimplePrincipal> authProvider = new BasicAuthProvider(new SimpleAuthenticator(),
"SECRET_REALM");
s.add(authProvider);
}
/**
* SQL IMPORT NAME
*/
protected void addSQLFixtureFile(String... files) {
for (final String file : files) {
final String name = this.getSQLFixturePath() + file + ".sql;";
this.payAttention("REQUIRED THIS SQL FIXTURE :::" + name);
sqlFiles += name;
}
}
/**
* @param path
* @param resources
* @return
*/
public WebResource getAuthResource(String path, ResourcesTestRule2 resources) {
final WebResource cl = getClient(resources).resource(path);
this.setAuthHeader(cl);
return cl;
}
public Client getClient(ResourcesTestRule2 resources) {
return getClient(resources, Global.USERNAME, Global.PASSWORD);
}
/**
* @param resources
* @param user
* @param password
* @return
*/
public Client getClient(ResourcesTestRule2 resources, String user, String password) {
final Client client = resources.client();
client.addFilter(new HTTPBasicAuthFilter(user, password));
return client;
}
/**
* Sequences to save
*/
public ArrayList<String> getCustomSequenceName() {
return null;
}
/**
* DAO TEST RULE
*/
public DAOTestRule getDAOTestRule(String url, String driver, String username, String password) {
return DAOTestRule.newBuilder().setNamingStrategy(new CustomNamingStrategy())
.setImportName(this.getSQLFixtureFile())._registerObserver(this).setUrl(url).setDriver(driver)
.setUsername(username).setHbm2DdlAuto(this.getHibernateDDLMode()).setPassword(password)
.addEntitiesClass(this.registerHBClass()).build();
};
public String getFixtureConcatFile(String base, String separator, String... file) {
final StringBuilder builder = new StringBuilder();
for (final String single : file) {
builder.append(base + single + separator);
}
builder.deleteCharAt(builder.length() - 1);
return builder.toString();
}
/**
* SQL MODE
*
* @return
*/
public String getHibernateDDLMode() {
return "create";
}
/**
* Sequence names
*
* If the method getCustomSequenceName returns null, then is resolved the
* sequence names using the clases suscribed to hibernate.
*/
public ArrayList<String> getSequenceName(DAOTestRule.Builder builder) {
ArrayList<String> sequenceC = this.getCustomSequenceName();
if (sequenceC != null && sequenceC.size() > 0) {
return sequenceC;
}
sequenceC = new ArrayList<>();
for (final Class<?> item : builder.getEntityClass()) {
sequenceC.add(item.getSimpleName());
}
return sequenceC;
}
/**
* SQL IMPORT NAME
*/
protected String getSQLFixtureFile() {
if (sqlFiles != null) {
return sqlFiles;
}
final String name = this.getSQLFixturePath() + this.getClass().getSimpleName() + ".sql";
this.payAttention("REQUIRED THIS SQL FIXTURE :::" + name);
return name;
}
/**
* Path to fixture SQL directory
*/
protected String getSQLFixturePath() {
return "/fixture/sql/";
}
protected String getSQLStrategy() {
return null;
}
/**
* Critical sequence, override this method.
*/
public boolean isSequenceCritial() {
return false;
}
public String objectToStr(Object o) throws JsonGenerationException, JsonMappingException, IOException {
final ObjectMapper om = new ObjectMapper();
return om.writeValueAsString(o);
}
protected void payAttention(String any) {
System.out.println("-------------------------------->>>>>>");
System.out.println("hey!!! " + any);
System.out.println("<<<<<<--------------------------------");
}
/**
* Hibernate Classes
*
* Override this with a new AbstractCommon override
*/
abstract protected ArrayList<Class<?>> registerHBClass();
/**
* Saving every Sequence we'll need to preserve
*/
public void saveSequence(Object data, DAOTestRule.Builder o) {
if (this.isSequenceCritial() && sequences.validateOnce()) {
try {
sequences.setConfiguration((Configuration) data).isOnce(true).setDDLMode(this.getHibernateDDLMode())
.addSequence(this.getSequenceName(o)).before();
} catch (final Throwable e) {
e.printStackTrace();
}
}
}
public WebResource setAuthHeader(WebResource cl) {
cl.header("Authorization", "Basic anybasichere=");
return cl;
}
/**
* START UNIT OF WORK
*/
public void unitOfWork() {
factory = daoTestRule.getSessionFactory();
}
/**
* CONFIGURE UNITOFWORK
*/
public void unitOfWork_step1() {
session = factory.getCurrentSession();
session.clear();
transac = session.beginTransaction();
}
/**
* COMMIT UNITOFWORK
*/
public void unitOfWork_step2() {
transac.commit();
}
/**
* end of UnitOfWork
*/
public void unitOfWork_step3() {
session.close();
factory.close();
}
/**
* Observer Method to control HIBERNATE Operations before HIBERNATE DROP ANY
* TABLE IN DATABASE.
*
* @param data
* must be casted to Configuration type
*/
@Override
public void update(Object data, Subject o) {
// LET'S SAVE THE CRITICAL SEQUENCES
this.saveSequence(data, (Builder) o);
}
}
package util.junit;
import org.hibernate.cfg.ImprovedNamingStrategy;
public class CustomNamingStrategy extends ImprovedNamingStrategy {
@Override
public String columnName(String columnName) {
return columnName;
}
@Override
public String tableName(String tableName) {
return tableName + "_TEST";
}
}
package packages;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.LowLevelAppDescriptor;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.jersey.DropwizardResourceConfig;
import io.dropwizard.jersey.jackson.JacksonMessageBodyProvider;
import io.dropwizard.logging.LoggingFactory;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Map;
import java.util.Set;
public class ResourcesTestRule2 implements TestRule, Observer {
static {
LoggingFactory.bootstrap();
}
private Set<Object> singletons = Sets.newHashSet();
private Set<Class<?>> providers = Sets.newHashSet();
private Map<String, Boolean> features = Maps.newHashMap();
private Map<String, Object> properties = Maps.newHashMap();
private ObjectMapper mapper = Jackson.newObjectMapper();
private Validator validator = Validation.buildDefaultValidatorFactory()
.getValidator();
private JerseyTest test;
private ResourceDataTestProvider resourceProvider;
public ResourcesTestRule2(ResourceDataTestProvider o) {
resourceProvider = o;
}
public ResourcesTestRule2(Set<Object> singletons, Set<Class<?>> providers,
Map<String, Boolean> features, Map<String, Object> properties,
ObjectMapper mapper, Validator validator) {
this.singletons = singletons;
this.providers = providers;
this.features = features;
this.properties = properties;
this.mapper = mapper;
this.validator = validator;
}
public ResourcesTestRule2 setMapper(ObjectMapper mapper) {
this.mapper = mapper;
return this;
}
public ResourcesTestRule2 addResource(Object resource) {
singletons.add(resource);
return this;
}
public ResourcesTestRule2 addProvider(Class<?> klass) {
providers.add(klass);
return this;
}
public ResourcesTestRule2 addProvider(Object provider) {
singletons.add(provider);
return this;
}
public ResourcesTestRule2 addFeature(String feature, Boolean value) {
features.put(feature, value);
return this;
}
public ResourcesTestRule2 addProperty(String property, Object value) {
properties.put(property, value);
return this;
}
public Validator getValidator() {
return validator;
}
public ResourcesTestRule2 setValidator(Validator validator) {
this.validator = validator;
return this;
}
public ObjectMapper getObjectMapper() {
return mapper;
}
public Client client() {
return test.client();
}
public JerseyTest getJerseyTest() {
return test;
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
test = new JerseyTest() {
@Override
protected AppDescriptor configure() {
DropwizardResourceConfig config =
DropwizardResourceConfig
.forTesting(new MetricRegistry());
resourceProvider.configureResource(config);
if (resourceProvider instanceof ProviderProvider) {
config.getProviderSingletons().addAll(
((ProviderProvider) resourceProvider)
.getProvider());
}
for (Class<?> provider : providers) {
config.getClasses().add(provider);
}
for (Map.Entry<String, Boolean> feature : features
.entrySet()) {
config.getFeatures().put(feature.getKey(),
feature.getValue());
}
for (Map.Entry<String, Object> property : properties
.entrySet()) {
config.getProperties().put(property.getKey(),
property.getValue());
}
config.getSingletons()
.add(new JacksonMessageBodyProvider(mapper,
validator));
if (resourceProvider instanceof ResourceProvider) {
config.getSingletons().addAll(
((ResourceProvider) resourceProvider)
.getResource());
}
return new LowLevelAppDescriptor.Builder(config).build();
}
};
test.setUp();
base.evaluate();
} finally {
if (test != null) {
test.tearDown();
}
}
}
};
}
@Override
public void update(Object data, Subject o) {
singletons = (Set<Object>) data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment