Module Class
public class MorphiaModule extends AbstractModule {
#Override
protected void configure() {
bind(PlayMorphia.class).asEagerSingleton();
}
}
PlayMorphia
#Singleton
public class PlayMorphia {
MongoClient mongo = null;
Datastore datastore = null;
Morphia morphia = null;
#Inject
public PlayMorphia(ApplicationLifecycle lifecycle, Environment env, Configuration config) {
try {
configure(config, env.classLoader(), env.isTest()); // Method calling to get the config
} catch (Exception e) {
e.printStackTrace();
}
lifecycle.addStopHook(()->{
if (env.isTest()) {
mongo().close();
}
return CompletableFuture.completedFuture(null);
});
}
}
In My application.conf, I mentioned the correct package/path name for Module class i.e.
play.modules.enabled += "configuration.MorphiaModule"
I followed the Play framework official doc on Eager Binding: https://www.playframework.com/documentation/2.6.x/JavaDependencyInjection#Eager-bindings
At compile time, I am getting this:
CreationException: Unable to create injector, see the following errors:
1) No implementation for play.inject.ApplicationLifecycle was bound.
while locating play.inject.ApplicationLifecycle
for the 1st parameter of configuration.PlayMorphia. .
(PlayMorphia.java:28)
at configuration.MorphiaModule.configure(MorphiaModule.java:24) (via
modules: com.google.inject.util.Modules$OverrideModule ->
configuration.MorphiaModule)
What am I doing wrong here? Any help would be appreciable.
Related
Launching Spring Boot's jar file throws me these errors:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'temperatureController' defined in URL <...>
Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'temperatureService' defined in URL <...>
Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.temperaturetracker.services.TokenService]: Constructor threw exception; nested exception is java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist.
Each class contains appropriate #: #Service or #RestController or #SpringBootApplication or #Entity or #Repository.
Some classes:
#Service
public class TemperatureService {
private final AlertService alertService;
#Autowired
public TemperatureService(AlertService alertService) {
this.alertService = alertService;
}
<...>
}
#Service
class AlertService #Autowired constructor(private val tokenService: TokenService,
private val cloudMessagingService: CloudMessagingService) {
#PostConstruct
fun initialize() {
<...>
}
}
#Service
public class CloudMessagingService {
final Logger logger = LoggerFactory.getLogger(CloudMessagingService.class);
public void sendFirebaseMessage() {
<...>
try {
var response = FirebaseMessaging.getInstance().send(fbMessage);
logger.debug("Notification response: " + response);
} catch (FirebaseMessagingException e) {
e.printStackTrace();
logger.error("Error sending Firebase Cloud Message: " + e);
}
}
}
#Service
public class FirebaseInitialize {
#PostConstruct
public void initialize() {
try {
FileInputStream serviceAccount =
new FileInputStream("hidden-path");
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("hidden-path")
.build();
FirebaseApp.initializeApp(options);
} catch (Exception e) {
e.printStackTrace();
}
}
}
#SpringBootApplication
public class TemperatureTrackerApplication {
public static void main(String[] args) {
SpringApplication.run(TemperatureTrackerApplication.class, args);
}
}
These errors occurs only when I launch my jar file. Running app via green arrow or Shift + F10 everything works perfectly.
Make sure your Firebase configuration is ok because the error is thrown when SpringBoot try to execute the class
FirebaseInitialize
I've changed my class's FirebaseInitialize method initialize() to:
try {
ClassPathResource serviceAccount =
new ClassPathResource("myFile.json"); // it is in resources folder
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount.getInputStream()))
.setDatabaseUrl("database-path-provided-by-firebase.app")
.build();
FirebaseApp.initializeApp(options);
} catch (Exception e) {
e.printStackTrace();
}
FileInputStream I've used before expected the resource to be on the file system, which cannot be nested in a jar file. Thus, using getInputStream() of ClassPathResource worked.
Please read more: Classpath resource not found when running as jar
Use a #PostConstruct method to initialize Firebase inside your #SpringBootApplication class. So the case above should become
#SpringBootApplication
public class TemperatureTrackerApplication {
public static void main(String[] args) {
SpringApplication.run(TemperatureTrackerApplication.class, args);
}
#PostConstruct
public void initialize() {
try {
FileInputStream serviceAccount =
new FileInputStream("hidden-path");
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("hidden-path")
.build();
FirebaseApp.initializeApp(options);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I try to get some data from a dbus service and work with it in Java.
I can get the information in cli with the following command:
dbus-send --print-reply --system --dest=com.victronenergy.solarcharger.ttyUSB0 /Dc/0/Voltage com.victronenergy.BusItem.GetValue
The result is:
method return time=1538903662.321580 sender=:1.14 -> destination=:1.806 serial=335692 reply_serial=2
variant double 13.43
What I tried to get this data in Java, is:
After hours of reading, I created an Interface.
package javadbus;
import java.util.Map;
import org.freedesktop.dbus.DBusInterface;
import org.freedesktop.dbus.DBusSignal;
import org.freedesktop.dbus.Variant;
import org.freedesktop.dbus.exceptions.DBusException;
public interface BusItem extends DBusInterface
{
public static class PropertiesChanged extends DBusSignal
{
public final Map<String,Variant> changes;
public PropertiesChanged(String path, Map<String,Variant> changes) throws DBusException
{
super(path, changes);
this.changes = changes;
}
}
public String GetDescription(String language, int length);
public Variant GetValue();
public String GetText();
public int SetValue(Variant value);
public Variant GetMin();
public Variant GetMax();
public int SetDefault();
public Variant GetDefault();
}
Here I call getConnection() and getRemoteObject() successfully.
package javadbus;
import org.freedesktop.dbus.DBusConnection;
import org.freedesktop.dbus.exceptions.DBusException;
import org.freedesktop.dbus.Variant;
public class VictronEnergyDBusSolarCharger {
private String port;
private DBusConnection conn;
public VictronEnergyDBusSolarCharger(String port) {
this.port = port;
try {
this.conn = DBusConnection.getConnection(DBusConnection.SYSTEM);
} catch (DBusException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getData(String item) {
BusItem bi;
String data = null;
Variant vData = null;
try {
bi = (BusItem)conn.getRemoteObject("com.victronenergy.solarcharger." + this.port, item, BusItem.class);
vData = bi.GetValue();
//data = bi.GetText();
} catch (DBusException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
...
}
It was a big task to resolve all dependecies and get the code compiled. But finaly I did it. So, javac now runs without errors.
But if I try to call the Method GetValue(), I get the following Exception:
[Sender] INFO org.freedesktop.dbus.MessageWriter - <= MethodCall(0,1) { Path=>/org/freedesktop/DBus, Interface=>org.freedesktop.DBus, Member=>Hello, Destination=>org.freedesktop.DBus } { }
[Sender] INFO org.freedesktop.dbus.MessageWriter - <= MethodCall(0,3) { Path=>/Dc/0/Voltage, Interface=>javadbus.BusItem, Member=>GetValue, Destination=>com.victronenergy.solarcharger.ttyUSB0 } { }
Exception in thread "main" org.freedesktop.DBus$Error$UnknownMethod: Method "GetValue" with signature "" on interface "javadbus.BusItem" doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.freedesktop.dbus.Error.getException(Error.java:141)
at org.freedesktop.dbus.Error.throwException(Error.java:171)
at org.freedesktop.dbus.RemoteInvocationHandler.executeRemoteMethod(RemoteInvocationHandler.java:158)
at org.freedesktop.dbus.RemoteInvocationHandler.invoke(RemoteInvocationHandler.java:222)
at com.sun.proxy.$Proxy1.GetValue(Unknown Source)
at javadbus.VictronEnergyDBusSolarCharger.getData(VictronEnergyDBusSolarCharger.java:28)
at javadbus.VictronEnergyDBusSolarCharger.getDcV(VictronEnergyDBusSolarCharger.java:38)
at javadbus.MainClass.main(MainClass.java:7)
Is it necessary to make a implementation of this Method GetValue? But why e.g. how should I do this? I only want to get this Information and not provide it like a Server.
Why was it a big task to get all dependencies?
dbus-java library and dependencies are all available at maven central, so a proper maven project should just work out-of-the-box.
Back to topic:
You don't have to implement GetValue(), but you need a suitable java interface for BusItem.
As far as I can see in the documentation of victronenergy (https://www.victronenergy.com/live/open_source:ccgx:d-bus) , your interface is not correct.
You provide SetDefault()/GetDefault() methods, which are only available on com.victronenergy.settings Objects, but you want to retrieve a com.victronenergy.BusItem (no part of the com.victronenergy.settings package).
This is one error. The second error is: you use the wrong package name for your BusItem class.
In your case DBus will try to resolve an object with the path javadbus.BusItem which is not provided by the connected BusAddress com.victronenergy.solarcharger.ttyUSB0.
The BusItem class has to be in package com.victronenergy or you have to use the annotation #DBusInterfaceName("com.victronenergy.BusItem").
The annotation will tell the DBus library to ignore the java package/class name and use the one provided in the annotation.
The Inteface BusItem had been created by CreateInterface-Script from https://dbus.freedesktop.org/doc/dbus-java/dbus-java/dbus-javase10.html and the XML from Introspect()
But you solved my real problem. I used the annotation #DBusInterfaceName("com.victronenergy.BusItem") now. No Exception anymore an i get data from my solarcharger. Thank you so much!
With Spring 4 and Hibernate 4, I was able to use Reflection to get the Hibernate Configuration object from the current environment, using this code:
#Autowired LocalContainerEntityManagerFactoryBean lcemfb;
EntityManagerFactoryImpl emf = (EntityManagerFactoryImpl) lcemfb.getNativeEntityManagerFactory();
SessionFactoryImpl sf = emf.getSessionFactory();
SessionFactoryServiceRegistryImpl serviceRegistry = (SessionFactoryServiceRegistryImpl) sf.getServiceRegistry();
Configuration cfg = null;
try {
Field field = SessionFactoryServiceRegistryImpl.class.getDeclaredField("configuration");
field.setAccessible(true);
cfg = (Configuration) field.get(serviceRegistry);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
SchemaUpdate update = new SchemaUpdate(serviceRegistry, cfg);
With Hibernate 5, I must use some MetadataImplementor, which doesn't seems to be available from any of those objects. I also tried to use MetadataSources with the serviceRegistry. But it did say that it's the wrong kind of ServiceRegistry.
Is there any other way to get this working?
Basic idea for this problem is:
implementation of org.hibernate.integrator.spi.Integrator which stores required data to some holder. Register implementation as a service and use it where you need.
Work example you can find here https://github.com/valery-barysok/spring4-hibernate5-stackoverflow-34612019
create org.hibernate.integrator.api.integrator.Integrator class
import hello.HibernateInfoHolder;
import org.hibernate.boot.Metadata;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.service.spi.SessionFactoryServiceRegistry;
public class Integrator implements org.hibernate.integrator.spi.Integrator {
#Override
public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
HibernateInfoHolder.setMetadata(metadata);
HibernateInfoHolder.setSessionFactory(sessionFactory);
HibernateInfoHolder.setServiceRegistry(serviceRegistry);
}
#Override
public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
}
}
create META-INF/services/org.hibernate.integrator.spi.Integrator file
org.hibernate.integrator.api.integrator.Integrator
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
new SchemaExport((MetadataImplementor) HibernateInfoHolder.getMetadata()).create(true, true);
new SchemaUpdate(HibernateInfoHolder.getServiceRegistry(), (MetadataImplementor) HibernateInfoHolder.getMetadata()).execute(true, true);
}
}
I would like to add up on Aviad's answer to make it complete as per OP's request.
The internals:
In order to get an instance of MetadataImplementor, the workaround is to register an instance of SessionFactoryBuilderFactory through Java's ServiceLoader facility. This registered service's getSessionFactoryBuilder method is then invoked by MetadataImplementor with an instance of itself, when hibernate is bootstrapped. The code references are below:
Service Loading
Invocation of getSessionFactoryBuilder
So, ultimately to get an instance of MetadataImplementor, you have to implement SessionFactoryBuilderFactory and register so ServiceLoader can recognize this service:
An implementation of SessionFactoryBuilderFactory:
public class MetadataProvider implements SessionFactoryBuilderFactory {
private static MetadataImplementor metadata;
#Override
public SessionFactoryBuilder getSessionFactoryBuilder(MetadataImplementor metadata, SessionFactoryBuilderImplementor defaultBuilder) {
this.metadata = metadata;
return defaultBuilder; //Just return the one provided in the argument itself. All we care about is the metadata :)
}
public static MetadataImplementor getMetadata() {
return metadata;
}
}
In order to register the above, create simple text file in the following path(assuming it's a maven project, ultimately we need the 'META-INF' folder to be available in the classpath):
src/main/resources/META-INF/services/org.hibernate.boot.spi.SessionFactoryBuilderFactory
And the content of the text file should be a single line(can even be multiple lines if you need to register multiple instances) stating the fully qualified class path of your implementation of SessionFactoryBuilderFactory. For example, for the above class, if your package name is 'com.yourcompany.prj', the following should be the content of the file.
com.yourcompany.prj.MetadataProvider
And that's it, if you run your application, spring app or standalone hibernate, you will have an instance of MetadataImplementor available through a static method once hibernate is bootstraped.
Update 1:
There is no way it can be injected via Spring. I digged into Hibernate's source code and the metadata object is not stored anywhere in SessionFactory(which is what we get from Spring). So, it's not possible to inject it. But there are two options if you want it in Spring's way:
Extend existing classes and customize all the way from
LocalSessionFactoryBean -> MetadataSources -> MetadataBuilder
LocalSessionFactoryBean is what you configure in Spring and it has an object of MetadataSources. MetadataSources creates MetadataBuilder which in turn creates MetadataImplementor. All the above operations don't store anything, they just create object on the fly and return. If you want to have an instance of MetaData, you should extend and modify the above classes so that they store a local copy of respective objects before they return. That way you can have a reference to MetadataImplementor. But I wouldn't really recommend this unless it's really needed, because the APIs might change over time.
On the other hand, if you don't mind building a MetaDataImplemetor from SessionFactory, the following code will help you:
EntityManagerFactoryImpl emf=(EntityManagerFactoryImpl)lcemfb.getNativeEntityManagerFactory();
SessionFactoryImpl sf=emf.getSessionFactory();
StandardServiceRegistry serviceRegistry = sf.getSessionFactoryOptions().getServiceRegistry();
MetadataSources metadataSources = new MetadataSources(new BootstrapServiceRegistryBuilder().build());
Metadata metadata = metadataSources.buildMetadata(serviceRegistry);
SchemaUpdate update=new SchemaUpdate(serviceRegistry,metadata); //To create SchemaUpdate
// You can either create SchemaExport from the above details, or you can get the existing one as follows:
try {
Field field = SessionFactoryImpl.class.getDeclaredField("schemaExport");
field.setAccessible(true);
SchemaExport schemaExport = (SchemaExport) field.get(serviceRegistry);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
Take a look on this one:
public class EntityMetaData implements SessionFactoryBuilderFactory {
private static final ThreadLocal<MetadataImplementor> meta = new ThreadLocal<>();
#Override
public SessionFactoryBuilder getSessionFactoryBuilder(MetadataImplementor metadata, SessionFactoryBuilderImplementor defaultBuilder) {
meta.set(metadata);
return defaultBuilder;
}
public static MetadataImplementor getMeta() {
return meta.get();
}
}
Take a look on This Thread which seems to answer your needs
Well, my go to on this:
public class SchemaTranslator {
public static void main(String[] args) throws Exception {
new SchemaTranslator().run();
}
private void run() throws Exception {
String packageName[] = { "model"};
generate(packageName);
}
private List<Class<?>> getClasses(String packageName) throws Exception {
File directory = null;
try {
ClassLoader cld = getClassLoader();
URL resource = getResource(packageName, cld);
directory = new File(resource.getFile());
} catch (NullPointerException ex) {
throw new ClassNotFoundException(packageName + " (" + directory + ") does not appear to be a valid package");
}
return collectClasses(packageName, directory);
}
private ClassLoader getClassLoader() throws ClassNotFoundException {
ClassLoader cld = Thread.currentThread().getContextClassLoader();
if (cld == null) {
throw new ClassNotFoundException("Can't get class loader.");
}
return cld;
}
private URL getResource(String packageName, ClassLoader cld) throws ClassNotFoundException {
String path = packageName.replace('.', '/');
URL resource = cld.getResource(path);
if (resource == null) {
throw new ClassNotFoundException("No resource for " + path);
}
return resource;
}
private List<Class<?>> collectClasses(String packageName, File directory) throws ClassNotFoundException {
List<Class<?>> classes = new ArrayList<>();
if (directory.exists()) {
String[] files = directory.list();
for (String file : files) {
if (file.endsWith(".class")) {
// removes the .class extension
classes.add(Class.forName(packageName + '.' + file.substring(0, file.length() - 6)));
}
}
} else {
throw new ClassNotFoundException(packageName + " is not a valid package");
}
return classes;
}
private void generate(String[] packagesName) throws Exception {
Map<String, String> settings = new HashMap<String, String>();
settings.put("hibernate.hbm2ddl.auto", "drop-create");
settings.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQL94Dialect");
MetadataSources metadata = new MetadataSources(
new StandardServiceRegistryBuilder()
.applySettings(settings)
.build());
for (String packageName : packagesName) {
System.out.println("packageName: " + packageName);
for (Class<?> clazz : getClasses(packageName)) {
System.out.println("Class: " + clazz);
metadata.addAnnotatedClass(clazz);
}
}
SchemaExport export = new SchemaExport(
(MetadataImplementor) metadata.buildMetadata()
);
export.setDelimiter(";");
export.setOutputFile("db-schema.sql");
export.setFormat(true);
export.execute(true, false, false, false);
}
}
I configured spring social for facebook and also the spring social authentication in my application with a custom UsersConnectionRepository and ConnectionRepository.
Configuration file
#Configuration
public class SocialConfig extends SocialConfigurerAdapter{
...
#Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator factoryLocator) {
SecUsersConnectionRepository repository = new SecUsersConnectionRepository(factoryLocator, userRepository, userConnectionRepository);
return repository;
}
...
}
Connection Repository implementation
public class SecConnectionRepository implements ConnectionRepository {
...
#Override
public void addConnection(Connection<?> connection) {
UserConnection userConnection = userRepository.findConnectionBy(user, connection.getKey().getProviderId(), connection.getKey().getProviderUserId());
if (userConnection == null) {
...
userConnection.setProviderId(data.getProviderId());
userConnection.setProviderUserId(data.getProviderUserId());
userConnection.setDisplayName(data.getDisplayName());
userConnection.setProfileUrl(data.getProfileUrl());
userConnection.setImageUrl(data.getImageUrl());
...
} else {
throw new DuplicateConnectionException(connection.getKey());
}
}
When I add my facebook login, the Connect<A> interface object fetch the profileUrl, But the URL is in this format
https://www.facebook.com/profile.php?id=XXXXXXXXXXXXXXX&_rdr
If I open up this link the browser is says
Gradle file
buildscript {
repositories {
maven { url "https://repo.spring.io/libs-release" }
... }
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.3.RELEASE")
}
}
apply plugin: 'java'
...
jar {...}
repositories {
...
maven { url "https://repo.spring.io/libs-release" }
}
dependencies {
...
compile("org.springframework.social:spring-social-facebook")
compile("org.springframework.social:spring-social-security")
... }
task wrapper(type: Wrapper) {...}
What am I doing wrong here?
SOLUTION
updating the FB libary in spring solved the issue.
compile("org.springframework.social:spring-social-facebook:2.0.1.RELEASE")
Check if you're using the most recent version of Spring Social. The profileUrl should nowadays have the scheme
https://www.facebook.com/app_scoped_user_id/{app_scoped_user_id}/
where {app_scoped_user_id} is the actual app-scoped user id.
See
https://developers.facebook.com/docs/apps/changelog#v2_0_graph_api
I have started reading the Apache commons documentation but its very extensive so I am hoping someone can answer a simple question so I don't need to read all of it just to start using it for basic configuration. I am losing patience really quick with it - there is no "quick start chapter" and I don't need to know every detail before I decide if I want to use the library or not.
I want (what I think is a common use-case) a class with static methods that provides look up of properties.
E.g. in class Foo i can use
Settings.config.getString("paramter");
Where
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.DefaultConfigurationBuilder;
/**
* Settings configuration class
*/
public class Settings {
private static final DefaultConfigurationBuilder factory = new DefaultConfigurationBuilder("config.xml");
public static final Configuration config= factory.getConfiguration();
}
The problem is that the factory method can throw an exception! So this code does not compile, a class cannot throw an exception either so I suspect that I need to do a lot more coding.
I suspect that there is a simple solution to this. But it surely cannot be calling
DefaultConfigurationBuilder factory = new DefaultConfigurationBuilder("config.xml");
Configuration config= factory.getConfiguration();
In every class where I want to read configurations?
I have tried:
public class Settings {
public static final Configuration config;
static {
try {
DefaultConfigurationBuilder factory;
factory = new DefaultConfigurationBuilder("config.xml") ;
config = factory.getConfiguration();
}
catch (ConfigurationException e) {
// Deal with the exception
config=null;
System.exit(1);
}
}
}
But I get the compilation error:
error: variable config might already have been assigned
[javac] config=null;
You could put the code to initialize config in a static initializer block and deal with the exception there. For example:
public class Settings {
public static final Configuration config;
static {
Configuration c = null;
try {
DefaultConfigurationBuilder factory = new DefaultConfigurationBuilder("config.xml");
c = factory.getConfiguration();
}
catch (SomeException e) {
// Deal with the exception
c = null;
}
config = c;
}
}