datanucleus complaining about class not being enhanced, but when run 2nd time works fine. - mongodb

I am trying to make datanucleus, work with Mongodb (using JDO). After successful
mvn clean compile
mvn exec:java
when I run first time it fails with
caused by: org.datanucleus.exceptions.NucleusUserException: Found Meta-Data for class com.samples.jdo.mongodb.Account but this class is either not enhanced or you have multiple copies of jdo-api.jar in your CLASSPATH!! Make sure all persistable classes are enhanced before running DataNucleus and/or the CLASSPATH is correct.
but if I run again it works fine and I can see data getting persisted in mongodb too.
// Create a PersistenceManagerFactory for this datastore
PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("datanucleus.properties", this.getClass().getClassLoader());
JDOMetadata jdomd = pmf.newMetadata();
PackageMetadata pmd = jdomd.newPackageMetadata("com.samples.jdo.mongodb");
ClassMetadata cmd1 = pmd.newClassMetadata(Account.class);
cmd1.setTable("Account").setIdentityType(javax.jdo.annotations.IdentityType.DATASTORE);
cmd1.setPersistenceModifier(ClassPersistenceModifier.PERSISTENCE_CAPABLE);
ClassMetadata cmd2 = pmd.newClassMetadata(Login.class);
cmd2.setTable("LOGIN").setIdentityType(javax.jdo.annotations.IdentityType.DATASTORE);
cmd2.setPersistenceModifier(ClassPersistenceModifier.PERSISTENCE_CAPABLE);
PersistenceManager pm = pmf.getPersistenceManager();
Account acct = new Account("firstname","lastname", 3);
Login login = new Login("flastname", "xxxx");
acct.setLogin(login);
final JDOEnhancer enhancer = JDOHelper.getEnhancer();
enhancer.setVerbose(true);
enhancer.registerMetadata(jdomd);
enhancer.setClassLoader(this.getClass().getClassLoader());
String[] classes = {"com.samples.jdo.mongodb.Account","com.samples.jdo.mongodb.Login" };
enhancer.addClasses(classes);
enhancer.enhance();
pmf.registerMetadata(jdomd);
pm.makePersistent(acct);
any ideas?
Thanks

Related

Why does Jooq code-generation break with PostGIS?

Context - I am trying out Postgres' Geographic Information System extension PostGis that enables stories latitude and longitudes as Point and operations on it.
If I understand correctly then I need to add a custom converter that can convert the point between JOOQ and PostGis and add it to the gradle file.
Problem - When I generate the jooq-code, few files are generated incorrectly and have the fields defined twice which fail compilation. These are:
<configured-generation-dir>/tables/StValuecount.java
<configured-generation-dir>/tables/records/StValuecountRecord.java
<configured-generation-dir>/tables/records/StValuepercentRecord.java
<configured-generation-dir>/tables/_StValuecount.java
<configured-generation-dir>/tables/records/_StValuecountRecord.java
<configured-generation-dir>/tables/_StHistogram.java
<configured-generation-dir>/tables/records/_StHistogramRecord.java
<configured-generation-dir>/tables/_StQuantile.java
Gradle config =>
jooq{
myAwesomeApp(sourceSets.main){
logging = 'WARN'
jdbc {
driver = 'org.postgresql.Driver'
url = db_url
user = db_user
password = db_password
}
generator {
name = 'org.jooq.codegen.DefaultGenerator'
strategy {
name = 'org.jooq.codegen.DefaultGeneratorStrategy'
}
database {
name = 'org.jooq.meta.postgres.PostgresDatabase'
inputSchema = 'public'
forcedTypes {
forcedType {
userType = 'org.postgis.Point'
converter = 'com.example.JooqBreaksWithPostGis.jooq.converters.PostgresPointJooqConverter'
expression = '.*\\.point'
types = '.*'
}
}
}
generate {
routines = false
relations = true
deprecated = false
records = true
immutablePojos = false
fluentSetters = true
}
target {
packageName = 'jooq.fancy.app'
directory = 'src/main/java/generated'
}
}
}
}
What am I doing wrong?
I have also created a minimal project where I have reproduced the problem in case someone wants to quickly try it.
Steps to reproduce
Checkout project
git clone git#github.com:raj-saxena/JooqBreaksWithPostGis.git
Go to the project directory and start postgis docker container with
docker-compose up
Similarly, to remove postgis docker container run
docker-compose down
Run migrations that add a simple City table containing Point type with
./gradlew flywayMigrate
I have added few rows in a second migration to verify if the DB structure was working. Details to connect to Postgres instance in the build.gradle file.
Generate jooq files with
./gradlew generateMyAwesomeAppJooqSchemaSource
Verify that the files are generated in the configured src/main/java/generated directory.
Verify that the files mentioned above fail to compile.
Taking Lukas' advice, I added the exclude configuration to the jooq config as below:
database {
name = 'org.jooq.meta.postgres.PostgresDatabase'
...
excludes = '.*ST_ValueCount' +
'|.*St_Valuepercent' +
'|.*St_Histogram' +
'|.*St_Quantile' +
'|.*St_Approxhistogram' +
'|.*St_PixelOfValue' +
'|.*St_Approxquantile' +
'|.*ST_Tile'
}
This allowed the code to compile.
This sounds a lot like https://github.com/jOOQ/jOOQ/issues/4055. jOOQ 3.11 currently cannot handle overloaded table valued functions in any RDBMS that supports table valued functions. Your best option here is to exclude all the affected functions from the code generation, using <excludes>:
https://www.jooq.org/doc/latest/manual/code-generation/codegen-advanced/codegen-config-database/codegen-database-includes-excludes/

How can I print all the settings in Test configuration for a project build using SBT?

I have a scala-js project, adding a particular library dependency, is affecting the way project test cases are running. Without the library dependency everything's fine, the moment I add them, tests doesn't execute. I want to check all sbt settings, if those are getting affected. Is there any way I can print all settings and check?
BuildStructure.data seems to give access to all the settings by scope. We could access it by defining a custom command printAllTestSettings like so:
def printAllTestSettings = Command.command("printAllTestSettings") { state =>
val structure = Project.extract(state).structure
val testScope =
Scope(
Select(ProjectRef(new File("/home/mario/sandbox/hello-world-scala/"), "root")),
Select(ConfigKey("test")),
Zero,
Zero
)
structure
.data
.keys(testScope)
.foreach(key => println(s"${key.label} = ${structure.data.get(testScope, key).get}"))
state
}
commands ++= Seq(printAllTestSettings)
Here is output snippet:
...
managedSourceDirectories = List(/home/mario/sandbox/hello-world-scala/target/scala-2.12/src_managed/test)
managedResourceDirectories = List(/home/mario/sandbox/hello-world-scala/target/scala-2.12/resource_managed/test)
testLoader = Task((taskDefinitionKey: ScopedKey(Scope(Select(ProjectRef(file:/home/mario/sandbox/hello-world-scala/,root)), Select(ConfigKey(test)), Zero, Zero),testLoader)))
packageBin = Task((taskDefinitionKey: ScopedKey(Scope(Select(ProjectRef(file:/home/mario/sandbox/hello-world-scala/,root)), Select(ConfigKey(test)), Zero, Zero),packageBin)))
...

Log4cplus setproperty function usage

I use the following configuration for my logger, in the conf file :
log4cplus.appender.TestLogAppender = log4cplus::TimeBasedRollingFileAppender
log4cplus.appender.TestLogAppender.FilenamePattern = %d{yyyyMMdd}.log
log4cplus.appender.TestLogAppender.MaxHistory = 365
log4cplus.appender.TestLogAppender.Schedule = DAILY
log4cplus.appender.TestLogAppender.RollOnClose = false
log4cplus.appender.TestLogAppender.layout = log4cplus::PatternLayout
log4cplus.appender.TestLogAppender.layout.ConversionPattern = %m%n
And in my code, I have the following initializing function for my logger, in which first, I load the configuration file, and then I wish to set the 'FilenamePattern' property to a new value, so that when I run multiple applications, each application will write to it's own log file:
void InitLogger()
{
ProperyConfigurator::doConfigure (L"LogConf.conf");
helpers:Properties prop(L"LogConf.conf");
props.setPropery(L"log4cplus.appender.TestLogAppender.FilenamePattern" ,
"Log/AppLogName.log.%d{yyyy-MM-dd}");
}
The problem is that when I run even one application, the log messages are written to the file as given in the original configuration file (in the 'FilenamePattern' property).
It seems the 'setproperty' didn't set the new value I gave it.
Is there a problem with my initializing logger function?
Have I used the setProperty method wrong?
You are obviously changing the properties after you have already configured the system, so your changes will be ignored. Do this instead:
helpers:Properties props(L"LogConf.conf");
props.setPropery(L"log4cplus.appender.TestLogAppender.FilenamePattern" ,
"Log/AppLogName.log.%d{yyyy-MM-dd}");
ProperyConfigurator propConf (props);
propConf.configure();

Enterprise Library Fluent API and Rolling Log Files Not Rolling

I am using the Fluent API to handle various configuration options for Logging using EntLib.
I am building up the loggingConfiguration section manually in code. It seems to work great except that the RollingFlatFileTraceListener doesn't actually Roll the file. It will respect the size limit and cap the amount of data it writes to the file appropriately, but it doesn't not actually create a new file and continue the logs.
I've tested it with a sample app and the app.config and it seems to work. So I'm guess that I am missing something although every config option that seems like it needs is there.
Here is the basics of the code (with hard-coded values to show a config that doesn't seem to be working):
//Create the config builder for the Fluent API
var configBuilder = new ConfigurationSourceBuilder();
//Start building the logging config section
var logginConfigurationSection = new LoggingSettings("loggingConfiguration", true, "General");
logginConfigurationSection.RevertImpersonation = false;
var _rollingFileListener = new RollingFlatFileTraceListenerData("Rolling Flat File Trace Listener", "C:\\tracelog.log", "----------------------", "",
10, "MM/dd/yyyy", RollFileExistsBehavior.Increment,
RollInterval.Day, TraceOptions.None,
"Text Formatter", SourceLevels.All);
_rollingFileListener.MaxArchivedFiles = 2;
//Add trace listener to current config
logginConfigurationSection.TraceListeners.Add(_rollingFileListener);
//Configure the category source section of config for flat file
var _rollingFileCategorySource = new TraceSourceData("General", SourceLevels.All);
//Must be named exactly the same as the flat file trace listener above.
_rollingFileCategorySource.TraceListeners.Add(new TraceListenerReferenceData("Rolling Flat File Trace Listener"));
//Add category source information to current config
logginConfigurationSection.TraceSources.Add(_rollingFileCategorySource);
//Add the loggingConfiguration section to the config.
configBuilder.AddSection("loggingConfiguration", logginConfigurationSection);
//Required code to update the EntLib Configuration with settings set above.
var configSource = new DictionaryConfigurationSource();
configBuilder.UpdateConfigurationWithReplace(configSource);
//Set the Enterprise Library Container for the inner workings of EntLib to use when logging
EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
Any help would be appreciated!
Your timestamp pattern is wrong. It should be yyy-mm-dd instead of MM/dd/yyyy. The ‘/’ character is not supported.
Also, you could accomplish your objective by using the fluent configuration interface much easier. Here's how:
ConfigurationSourceBuilder formatBuilder = new ConfigurationSourceBuilder();
ConfigurationSourceBuilder builder = new ConfigurationSourceBuilder();
builder.ConfigureLogging().LogToCategoryNamed("General").
SendTo.
RollingFile("Rolling Flat File Trace Listener")
.CleanUpArchivedFilesWhenMoreThan(2).WhenRollFileExists(RollFileExistsBehavior.Increment)
.WithTraceOptions(TraceOptions.None)
.RollEvery(RollInterval.Minute)
.RollAfterSize(10)
.UseTimeStampPattern("yyyy-MM-dd")
.ToFile("C:\\logs\\Trace.log")
.FormatWith(new FormatterBuilder().TextFormatterNamed("textFormatter"));
var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
var writer = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
DateTime stopWritingTime = DateTime.Now.AddMinutes(10);
while (DateTime.Now < stopWritingTime)
{
writer.Write("test", "General");
}

How to execute the code generated by codeDom?

I just generated the .cs file using codeDom. Can someone explain how do I execute it?
The code below will allow you to compile the code using the codedom and then you can show the user if the code compiled correctly or not. It even creates a DLL as well.
Thanks
Alex
// Store provider from the method into a object, Default is CSharpCodeProvider**
CodeDomProvider provider = this.GetCurrentProvider();
// Configure a CompilerParameters that links System.dll**
String[] referenceAssemblies = { "System.dll", "System.Data.Linq.dll", "System.Web.dll","System.XML.dll","System.ComponentModel.DataAnnotations.dll", "System.Data.dll", _mvcLocation };
CompilerParameters cp = new CompilerParameters(referenceAssemblies, this.fileLocation + this.fileName + ".dll", false);
// Generate an executable rather than a DLL file.**
cp.GenerateExecutable = true;
// Invoke compilation.**
CompilerResults _results = provider.CompileAssemblyFromFile(cp, this.fileLocation + this.fileName + "." + this.extention);
It's not quite that simple. See here for a primer. Basically the CodeDom supports scenarios such as code generation and dynamic compilation. So .cs files created with the CodeDom are not executables in the usual sense.