DbSetup populate the database - database

I tried to use to DbSetup to populate the database, but it did not work
class CommonOperations {
public static final Operation DELETE_ALL =
deleteAllFrom("ACH_GROUP");
public static final Operation INSERT_REFERENCE_DATA =
sequenceOf(
insertInto("ACH_GROUP")
.columns("ID", "CLOSED", "NAME", "OPENED", "COMPETENCE_ID", "LASTMODIFIEDDATE", "uuid")
.values(1, "", "JAVA", "", 1, "", "")
.build());
}
public class CompetenceDaoImplementationTest {
private static String username = "sa";
private static String password = "12345";
private static String URL = "jdbc:sqlserver://localhost:1433;databaseName=DB_Achi";
// the tracker is static because JUnit uses a separate Test instance for every test method.
private static DbSetupTracker dbSetupTracker = new DbSetupTracker();
#Before
public void prepare() throws Exception {
Operation operation =
sequenceOf(
CommonOperations.DELETE_ALL,
CommonOperations.INSERT_REFERENCE_DATA);
// without DataSource
DbSetup dbSetup = new DbSetup(new DriverManagerDestination(URL, username, password), operation);
// use the tracker to launch the DbSetup.
dbSetupTracker.launchIfNecessary(dbSetup);
}
#Test
public void testShowGroups() {
dbSetupTracker.skipNextLaunch();
}

Related

Cant access nested list in Json response

Im trying to access some list items from a json response using retrofit but cant seem to be able to access using get method. The ListQuotes seems to be saying null
#JsonPropertyOrder({
"page",
"last_page",
"quotes"
})
public class ListQuoteResponse {
#JsonProperty("quotes")
private List<Quote> quotes = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public ListQuoteResponse() {
}
#JsonProperty("quotes")
public List<Quote> getQuotes() {
return quotes;
}
#JsonProperty("quotes")
public void setQuotes(List<Quote> quotes) {
this.quotes = quotes;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
But when I open the Quote class I am unable to access any of the properties
public class Quote {
#JsonProperty("id")
private Integer id;
#JsonProperty("dialogue")
private Boolean dialogue;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public Quote() {
}
#JsonProperty("id")
public Integer getId() {
return id;
}
#JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
#JsonProperty("dialogue")
public Boolean getDialogue() {
return dialogue;
}
#JsonProperty("dialogue")
public void setDialogue(Boolean dialogue) {
this.dialogue = dialogue;
}
I tried using
listQuoteBodyResponse.body().getQuotes() but that only returned random numbers and when I tried using the Quote class for the response directly like
QuoteResponse.body.getDialogue() its just returning null

Identity Server 4 AddOidcStateDataFormatterCache Configure TimeToLive

I am using the extension:
services.AddOidcStateDataFormatterCache();
in Asp.Net Core, to store the state in the distributed cache which is implemented using Redis:
services.AddStackExchangeRedisCache(options => {
options.Configuration = Configuration[RedisConnection];
});
but it seems that the entries in the Redis cache are not set with TTL:
Is there a setting to control the TTL of the keys that get created in the cache?
Already reported. Waiting for response. (Please, mention that you need this, there too!)
For the moment we use an ugly inheritor. Ugly because the base has no virtual methods and in addition requires a helper internal class ConfigureOpenIdConnectOptionsTTL : IPostConfigureOptions<OpenIdConnectOptions> (mostly copy&paste again) but at least it fixed "slow redis in production".
public class DistributedCacheStateDataFormatterTTL:
DistributedCacheStateDataFormatter, ISecureDataFormat<AuthenticationProperties>
{
public static readonly TimeSpan DefaultCacheDuration = TimeSpan.FromMinutes(5);
private readonly IHttpContextAccessor _httpContext;
private readonly string _name;
public DistributedCacheStateDataFormatterTTL(
IHttpContextAccessor httpContext, string name) : base(httpContext, name)
{
_httpContext = httpContext;
_name = name;
}
private string CacheKeyPrefix => "DistributedCacheStateDataFormatter";
private IDistributedCache Cache =>
_httpContext.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
private IDataProtector Protector =>
_httpContext.HttpContext.RequestServices
.GetRequiredService<IDataProtectionProvider>()
.CreateProtector(CacheKeyPrefix, _name);
string ISecureDataFormat<AuthenticationProperties>
.Protect(AuthenticationProperties data)
{
return ((ISecureDataFormat<AuthenticationProperties>)this).
Protect(data, string.Empty);
}
string ISecureDataFormat<AuthenticationProperties>
.Protect(AuthenticationProperties data, string purpose)
{
var key = Guid.NewGuid().ToString();
var cacheKey = $"{CacheKeyPrefix}-{purpose}-{key}";
var json = JsonConvert.SerializeObject(data, new JsonSerializerSettings()
{
DefaultValueHandling = DefaultValueHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
});
var options = new DistributedCacheEntryOptions();
if (data.ExpiresUtc.HasValue)
options.SetAbsoluteExpiration(data.ExpiresUtc.Value);
else
options.SetSlidingExpiration(DefaultCacheDuration);
// Rather than encrypt the full AuthenticationProperties
// cache the data and encrypt the key that points to the data
Cache.SetString(cacheKey, json, options);
return Protector.Protect(key);
}
}
internal class ConfigureOpenIdConnectOptionsTTL : IPostConfigureOptions<OpenIdConnectOptions>
{
private string[] _schemes;
private readonly IHttpContextAccessor _httpContextAccessor;
public ConfigureOpenIdConnectOptionsTTL(string[] schemes, IHttpContextAccessor httpContextAccessor)
{
_schemes = schemes ?? throw new ArgumentNullException(nameof(schemes));
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
public void PostConfigure(string name, OpenIdConnectOptions options)
{
// no schemes means configure them all
if (_schemes.Length == 0 || _schemes.Contains(name))
{
options.StateDataFormat = new DistributedCacheStateDataFormatterTTL(_httpContextAccessor, name);
}
}
public static IServiceCollection AddOidcStateDataFormatterCache(
IServiceCollection services,
params string[] schemes)
{
services.RemoveAll<IPostConfigureOptions<OpenIdConnectOptions>>();
services.AddSingleton<IPostConfigureOptions<OpenIdConnectOptions>>(
svcs => new ConfigureOpenIdConnectOptionsTTL(
schemes,
svcs.GetRequiredService<IHttpContextAccessor>())
);
return services;
}
}

Store to JSON a PropertyBusinessObject containing a ListProperty

I have difficult to store to JSON a PropertyBusinessObject containing a ListProperty. I created the following test case, that works fine on the first execution, but fails on the second. Is my code wrong?
My test case if composed by four classes:
TestCaseJSON
public void init(Object context) {
[...]
DB.initPersistenceDB();
}
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("Hi World", BoxLayout.y());
hi.add(new Label("Hi World"));
hi.show();
DB.userDB.uniqueID.set("1");
DB.userDB.authToken.set("myToken");
InjuryDAO newInjury = new InjuryDAO();
DB.userDB.injuries.add(newInjury);
DB.saveDB();
}
DB
public class DB {
// User Database
public static UserDB userDB = new UserDB();
/**
* Call this method in the init(), it allows the database persistence and
* automatically restores the saved DB.
*/
public static void initPersistenceDB() {
Log.p("DB.initPersistenceDB executing", Log.DEBUG);
restoreDB();
}
/**
* Saves the UserDB to the Storage
*/
public static void saveDB() {
Log.p("DB.saveUserDB executing", Log.INFO);
userDB.getPropertyIndex().storeJSON("UserDB");
}
/**
* Restore the UserDB from the Storage, if it was previously saved to; this
* method is called by initPersistenceDB()
*/
private static void restoreDB() {
Log.p("DB.restoreUserDB executing", Log.INFO);
if (Storage.getInstance().exists("UserDB")) {
userDB.getPropertyIndex().loadJSON("UserDB");
}
}
}
UserDB
public class UserDB implements PropertyBusinessObject {
public final Property<String, UserDB> uniqueID = new Property<>("uniqueID", null);
public final Property<String, UserDB> authToken = new Property<>("authToken", null);
public final ListProperty<InjuryDAO, UserDB> injuries = new ListProperty<>("injuries");
public final PropertyIndex idx = new PropertyIndex(this, "UserDB",
uniqueID, authToken,
injuries
);
#Override
public PropertyIndex getPropertyIndex() {
return idx;
}
}
InjuryDAO
public class InjuryDAO implements PropertyBusinessObject {
// extra info
public final LongProperty<InjuryDAO> injuryCreationTime = new LongProperty<>("injuryCreationTime", System.currentTimeMillis());
// mandatory info
public final Property<Date, InjuryDAO> dateInjury = new Property<>("dateInjury", Date.class);
private final PropertyIndex idx = new PropertyIndex(this, "InjuryDAO",
injuryCreationTime, dateInjury
);
#Override
public PropertyIndex getPropertyIndex() {
return idx;
}
}
Before executing in the Simulator, I cleared the .cn1 directory (that is equivalent to Simulator, Clean Storage).
After the first execution, this is the log:
[EDT] 0:0:0,110 - DB.initPersistenceDB executing
[EDT] 0:0:0,110 - DB.restoreUserDB executing
[EDT] 0:0:0,178 - DB.saveUserDB executing
and this is the content of the UserDB file inside the .cn1 directory:
{
"injuries": [{"injuryCreationTime": 1558202520667}],
"authToken": "myToken",
"uniqueID": "1"
}
That's correct.
After the second execution, the log is identical to the previous one, but this is the wrong content of the UserDB file (note that the previous time stamp is lost):
{
"injuries": [
{"injuries": []},
{"injuryCreationTime": 1558202625655}
],
"authToken": "myToken",
"uniqueID": "1"
}
The expected correct result should be:
{
"injuries": [
{"injuryCreationTime": 1558202520667},
{"injuryCreationTime": 1558202625655}
],
"authToken": "myToken",
"uniqueID": "1"
}
Thank you for your support.
I think this:
public final ListProperty<InjuryDAO, UserDB> injuries = new ListProperty<>("injuries");
Should be changed to:
public final ListProperty<InjuryDAO, UserDB> injuries = new ListProperty<>("injuries", InjuryDAO.class);
If this doesn't work try:
public final ListProperty<InjuryDAO, UserDB> injuries = new ListProperty<>("injuries", InjuryDAO.class, null);

Spring-boot & multiple database connections: autowire service does not work

I'm writing an Spring-boot application that needs to connect to at least 2 databases.
I have 1 project per database in order to define their domains, 1 project per database in order to define their services and 1 Vaadin project for the UI.
- a business domain entity sample
#Entity
#Table(name="T_PARAMETER")
public class Parameter extends BaseIdEntity implements Serializable {
#Column(name="par_cls")
#NotNull
private String parameterClass;
#Column(name="par_cd")
#NotNull
private String parameterCode;
#Column(name="par_lan")
#NotNull
private String language;
#Column(name="par_sht_val")
#NotNull
private String parameterValueShort;
#Column(name="par_lng_val")
#NotNull
private String parameterValueLong;
- a authentication domain entity sample
#Entity
#Table(name="t_user", schema="authenticate")
public class User extends BaseIdEntity implements Serializable {
#Id
#Column(name="user_cd")
private String userCode;
#Column(name="pwd")
#NotNull
private String password;
#Column(name="new_pwd_req")
#NotNull
private boolean passwordRequired;
#Column(name="acc_lck")
#NotNull
private boolean accountLocked;
There are repositories onto these 2 entities beans, they just extends the JpaRepository as hereunder:
public interface ParameterRepository extends JpaRepository<Parameter,Integer>{}
the services are defined as hereunder:
#Service
#Transactional(transactionManager="authenticateTransactionManager")
public class ServiceParameterImpl implements ServiceParameter {
private final static Logger log = LoggerFactory.getLogger(ServiceParameterImpl.class);
#Autowired
private ParameterRepository parameterRepository;
#Override
#Transactional(readOnly=true,transactionManager="authenticateTransactionManager")
public List<Parameter> findParameterHeader(String filter) {
.../...
The client application as:
#SpringBootApplication
#Configuration
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class
, HibernateJpaAutoConfiguration.class
, DataSourceTransactionManagerAutoConfiguration.class })
#ComponentScan(
basePackages= {
"org.associative.ui"
,"org.associative.service"
})
#Import({AssociativityConfiguration.class, AuthenticateConfiguration.class})
public class Application {
private final static Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and configurations:
#Configuration
#EnableTransactionManagement
#EntityScan(basePackages= "org.associative.domain.associativity")
#EnableJpaRepositories(
basePackages = "org.associative.domain.associativity.repository"
, entityManagerFactoryRef = "associativityEntityManager"
, transactionManagerRef = "associativityTransactionManager"
)
#ConfigurationProperties(prefix = "db.associativity")
public class AssociativityConfiguration {
private final static Logger log = LoggerFactory.getLogger(AssociativityConfiguration.class);
#Autowired
private Environment env;
private final static String ASSOCIATIVITY_DRIVER_CLASS_NAME = "db.associativity.classname";
private final static String ASSOCIATIVITY_URL = "db.associativity.connectionUrl";
private final static String ASSOCIATIVITY_USERNAME = "db.associativity.username";
private final static String ASSOCIATIVITY_PASSWORD = "db.associativity.password";
private final static String HIBERNATE_DIALECT = "hibernate.dialect";
#Bean(name = "associativityDataSource")
public DataSource datasource() {
DataSource dataSource = DataSourceBuilder.create()
.driverClassName(env.getProperty(ASSOCIATIVITY_DRIVER_CLASS_NAME))
.url(env.getProperty(ASSOCIATIVITY_URL))
.username(env.getProperty(ASSOCIATIVITY_USERNAME))
.password(env.getProperty(ASSOCIATIVITY_PASSWORD)).build();
if (log.isTraceEnabled())
log.trace(String.format("associativityConfiguration datasource:%s", dataSource.toString()));
return dataSource;
}
#Bean(name = "associativityEntityManager")
#PersistenceContext(unitName = "associativity")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("associativityDataSource") DataSource dataSource) {
Map<String, Object> jpaProperties = new HashMap<>();
jpaProperties.put(HIBERNATE_DIALECT, env.getProperty(HIBERNATE_DIALECT));
LocalContainerEntityManagerFactoryBean em = builder.dataSource(dataSource)
.packages("org.associative.domain.authenticate").persistenceUnit("pu_associativity").properties(jpaProperties)
.build();
em.setJpaPropertyMap(jpaProperties);
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(adapter); // not mandatory definition
return em;
}
#Bean(name = "associativityTransactionManager")
public PlatformTransactionManager associativityTransactionManager(
#Qualifier("associativityEntityManager") EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
and
#Configuration
#EnableTransactionManagement
#EntityScan(basePackages= "org.associative.domain.authenticate")
#EnableJpaRepositories(
basePackages = "org.associative.domain.authenticate.repository"
, entityManagerFactoryRef = "authenticateEntityManager"
, transactionManagerRef = "authenticateTransactionManager"
)
#ConfigurationProperties(prefix="db.authenticate")
public class AuthenticateConfiguration {
private final static Logger log = LoggerFactory.getLogger(AuthenticateConfiguration.class);
#Autowired
private Environment env;
private final static String AUTHENTICATE_DRIVER_CLASS_NAME= "db.authenticate.classname";
private final static String AUTHENTICATE_URL = "db.authenticate.connectionUrl";
private final static String AUTHENTICATE_USERNAME = "db.authenticate.username";
private final static String AUTHENTICATE_PASSWORD = "db.authenticate.password";
private final static String HIBERNATE_DIALECT = "hibernate.dialect";
#Primary
#Bean(name = "authenticateDataSource")
public DataSource datasource() {
DataSource dataSource = DataSourceBuilder.create()
.driverClassName(env.getProperty(AUTHENTICATE_DRIVER_CLASS_NAME))
.url(env.getProperty(AUTHENTICATE_URL))
.username(env.getProperty(AUTHENTICATE_USERNAME))
.password(env.getProperty(AUTHENTICATE_PASSWORD))
.build();
if ( log.isTraceEnabled()) log.trace(String.format("authenticateDataSource datasource:%s", dataSource.toString()));
return dataSource;
}
#Primary
#Bean(name="authenticateEntityManager")
#PersistenceContext(unitName = "authenticate")
//https://raymondhlee.wordpress.com/tag/enablejparepositories/
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder, #Qualifier("authenticateDataSource")DataSource dataSource) {
Map<String,Object> jpaProperties = new HashMap<>();
jpaProperties.put(HIBERNATE_DIALECT, env.getProperty(HIBERNATE_DIALECT));
LocalContainerEntityManagerFactoryBean em = builder
.dataSource(dataSource)
.packages("org.associative.domain.authenticate")
.persistenceUnit("pu_authenticate")
.properties(jpaProperties)
.build();
em.setJpaPropertyMap(jpaProperties);
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(adapter); // not mandatory definition
return em;
}
#Primary
#Bean(name="authenticateTransactionManager")
public PlatformTransactionManager authenticateTransactionManager(
#Qualifier("authenticateEntityManager")EntityManagerFactory entityManagerFactory){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
I'm facing an issue when a service is built by using autowiring in the construction of my client interface:
#SpringUI
public class ParameterListView extends CssLayout implements Serializable {
private final static Logger log = LoggerFactory.getLogger(ParameterListView.class);
#Autowired
private ParameterController controller;
#PostConstruct
private void initView() {
if ( log.isTraceEnabled() ) log.trace(String.format("initView:%s", "no param"));
Grid<Parameter> grid = new Grid<>();
this.addComponent(grid);
grid.setItems(controller.getParameterHeader(""));
grid.addColumn(Parameter::getParameterClass);
grid.addColumn(Parameter::getParameterValueShort);
grid.addColumn(Parameter::getParameterValueLong);
2017-12-01 14:20:07.151 ERROR o.s.b.SpringApplication Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterControllerImpl': Unsatisfied
dependency expressed through field 'serviceParameter'; nested
exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'serviceParameterImpl': Unsatisfied
dependency expressed through field 'parameterRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'parameterRepository': Invocation of
init method failed; nested exception is
java.lang.IllegalArgumentException: Not a managed type: class
org.associative.domain.associativity.Parameter
I already spent a lot of time in order to solve the multiple database connections because I was thinking this issue comes from a definition problem but I'm not sure now.
So, what should I look to in order to solve this.
Thank you very much.
The last line of your stack trace is a clue: Not a managed type: class org.associative.domain.associativity.Parameter. Hibernate doesn't know about your Parameter entity.
In the LocalContainerEntityManagerFactoryBean you set packages to scan to org.associative.domain.authenticate. Your Parameter entity is not under this package.
This should fix the problem:
.packages("org.associative.domain.authenticate", "org.associative.domain.associativity")

JUnit Testing with Google App Engine dev server

I'm new to GAE and trying to setup a few JUnit tests. In this example provided by Google:
public class LocalDatastoreTest {
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
#Before
public void setUp() {
helper.setUp();
}
#After
public void tearDown() {
helper.tearDown();
}
// run this test twice to prove we're not leaking any state across tests
private void doTest() {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
assertEquals(0, ds.prepare(new Query("yam")).countEntities(withLimit(10)));
ds.put(new Entity("yam"));
ds.put(new Entity("yam"));
assertEquals(2, ds.prepare(new Query("yam")).countEntities(withLimit(10)));
}
#Test
public void testInsert1() {
doTest();
}
#Test
public void testInsert2() {
doTest();
}
}
the following line is used to add an Entity to the local datastore:
ds.put(new Entity("yam"));
That works just fine for me. However, I'm using JDO and want to persist one my own POJOs (e.g. Cars) but Cars is not of type Entity, which is what this method requires. Is there a different method or service I can use to accomplish this?
maybe you could use objectify-appengine.. for example
package com.intranet.entity;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
#Entity
public class Voto {
#Id Long id;
#Index String email;
#Index String actividad;
public Voto(){}
public Voto(String email, String actividad) {
this.email = email;
this.actividad = actividad;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getActividad() {
return actividad;
}
public void setActividad(String actividad) {
this.actividad = actividad;
}
}
TEST
public class VotoTest {
private final static LocalServiceTestHelper helper = new LocalServiceTestHelper(
new LocalDatastoreServiceTestConfig());
#Before
public void setUp() {
helper.setUp();
}
#After
public void tearDown() {
helper.tearDown();
}
#Test
public void testEmbedded(){
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Voto voto1 = new Voto("test#localhost","actividad1");
ofy().save().entity(voto1).now();
assertEquals(1, ds.prepare(new Query("Voto")).countEntities(withLimit(10)));
}
}
It works perfectly

Resources