Spring data rest repository with exported = false hides other repo with exported = true - spring-data-rest

Does anyone know if it's possible to have two spring data repos for a single resource, but only one of them exported?
When I do this, neither repo is exported:
#RepositoryRestResource(exported = true)
public interface BookRepo extends JpaRepository<Application.Book, Long> { }
#RepositoryRestResource(exported = false)
public interface BookRepo2 extends CrudRepository<Application.Book, Long> { }

I noticed that you have two repositories on the same type - Application.Book
also one is JpaRepository and the other is CrudRepository.
JpaRepository extends from CrudRepository.
may be you could assess why you need 2 repositories on the same type.
instead you could just use one with JpaRepository and then
you can use #RestResource(exported=false) to hide specific methods rather than having to hide repository interfaces.

Related

What is the difference between Provider and Resolver

I often need a class/service that will give me some data trough fetching it from a DB, transforming an existing data structure or do both internally but I sometimes have a difficulty naming them properly.
I am currently working with Sylius and they are using classes/services with suffixes such as Checker, Applicator, Processor... I have clear understanding of these names and their implications as to what and how they are doing things. But there are also suffixes Provider and Resolver and I have a difficulty differentiating between them. I don't understand the exact differences of their naming.
What I observed is:
Provider: fetching data that are not yet available (internally fetching data from DB or external API)
Resolver: I already have a bunch of data (and I don't need any additional data) and I need to filter, transform or get some subset of it.
Is there some convention or design pattern to names Resolver and Provider? Am I somewhat right here? Or is there more nuance to this naming?
In my view, patterns are not depend on technology or language, so this article can be applied here:
Content Providers provide an interface, e.g. for publishing and consuming data
and:
Content Resolver resolves a publishing and consuming data to a specific Content provider.
The Content Resolver includes the CRUD (create, read, update, delete) methods corresponding to the abstract methods (insert, query, update, delete) in the Content Provider class.
UPDATE
Provider is an abstraction that can be implemented by concrete providers. E.g., there is DataProvider and DataProvider is an abstraction. So we want concrete implementations of SqlServerProvider, PostgreProvider, OracleProvider.
Let me show an example via C#:
public interface IDataProvider
{
string GetById();
}
public class SqlServerProvider : IDataProvider
{
public string GetById()
{
return "Data retrieved with SqlServerProvider";
}
}
public class PostgreProvider : IDataProvider
{
public string GetById()
{
return "Data retrieved with PostgreProvider";
}
}
public class OracleProvider : IDataProvider
{
public string GetById()
{
return "Data retrieved with OracleProvider";
}
}
Then we need to resolve the above dependenies to use them. But how? We can create DataResolver:
public enum DataProviderType
{
SqlServer, Posgre, Oracle
}
public class DataResolver
{
private Dictionary<DataProviderType, IDataProvider> _dataProviderByType =
new Dictionary<DataProviderType, IDataProvider>()
{
{ DataProviderType.SqlServer, new SqlServerProvider() },
{ DataProviderType.Posgre, new PostgreProvider() },
{ DataProviderType.Oracle, new OracleProvider() },
};
public IDataProvider Resolve(DataProviderType dataProviderType)
{
return _dataProviderByType[dataProviderType];
}
}
and then we can run the above code like this:
DataResolver dataResolver = new DataResolver();
string someValue = dataResolver.Resolve(DataProviderType.SqlServer).GetById();
Console.WriteLine(someValue); // OUTPUT: Data retrieved with SqlServerProvider
See more examples of code here

Google Guice runtime dependency injection

I am looking for a way to dynamically select the correct dependency during runtime using google guice.
My usecase is a kotlin application which can work with either sqlite or h2 databases depending on the configuration file provided.
The file is read when the application is executed and if the database is not found, the correct one is created and migrated into.
My database structure contains the Database (Interface), H2Database: Database, SQLiteDatabase: Database and the module binding class which looks like this:
class DatabaseModule: KotlinModule() {
override fun configure() {
bind<Database>().annotatedWith<configuration.H2>().to<H2Database>()
bind<Database>().annotatedWith<configuration.SQLite>().to<SQLiteDatabase>()
}
}
So far, with SQlite alone, I would simply request the dependency using:
#Inject
#SQLite
private lateinit var database: Database
How would I make this selection during runtime?
Without knowing too much about the specific of your code, I'll offer three general approaches.
(Also, I have never used Kotlin. I hope Java samples are enough for you to figure things out.)
First Approach
It sounds like you need some non-trivial logic to determine which Database implementation is the right one to use. This is a classic case for a ProviderBinding. Instead binding Database to a specific implementation, you bind Database to a class that is responsible providing instances (a Provider). For example, you might have this class:
public class MyDatabaseProvider.class implements Provider<Database> {
#Inject
public MyDatabaseProvider.class(Provider<SQLiteDatabase> sqliteProvider, Provider<H2Database> h2Provider) {
this.sqliteProvider = sqliteProvider;
this.h2Provider = h2Provider;
}
public Database get() {
// Logic to determine database type goes here
if (isUsingSqlite) {
return sqliteProvider.get();
} else if (isUsingH2) {
return h2Provider.get();
} else {
throw new ProvisionException("Could not determine correct database implementation.");
}
}
}
(Side note: This sample code gets you a new instance every time. It is fairly straightforward to make this also return a singleton instance.)
Then, to use it, you have two options. In your module, you would bind Database not to a specific implementation, but to your DatabaseProvider. Like this:
protected void configure() {
bind(Database.class).toProvider(MyDatabaseProvider.class);
}
The advantage of this approach is that you don't need to know the correct database implementation until Guice tries to construct an object that requires Database as one of its constructor args.
Second Approach
You could create a DatabaseRoutingProxy class which implements Database and then delegates to the correct database implementation. (I've used this pattern professionally. I don't think there's an "official" name for this design pattern, but you can find a discussion here.) This approach is based on lazy loading with Provider using the Providers that Guice automatically creates(1) for every bound type.
public class DatabaseRoutingProxy implements Database {
private Provider<SqliteDatabse> sqliteDatabaseProvider;
private Provider<H2Database> h2DatabaseProvider;
#Inject
public DatabaseRoutingProxy(Provider<SqliteDatabse> sqliteDatabaseProvider, Provider<H2Database> h2DatabaseProvider) {
this.sqliteDatabaseProvider = sqliteDatabaseProvider;
this.h2DatabaseProvider = h2DatabaseProvider;
}
// Not an overriden method
private Database getDatabase() {
boolean isSqlite = // ... decision logic, or maintain a decision state somewhere
// If these providers don't return singletons, then you should probably write some code
// to call the provider once and save the result for future use.
if (isSqlite) {
return sqliteDatabaseProvider.get();
} else {
return h2DatabaseProvider.get();
}
}
#Override
public QueryResult queryDatabase(QueryInput queryInput) {
return getDatabase().queryDatabase(queryInput);
}
// Implement rest of methods here, delegating as above
}
And in your Guice module:
protected void configure() {
bind(Database.class).to(DatabaseRoutingProxy.class);
// Bind these just so that Guice knows about them. (This might not actually be necessary.)
bind(SqliteDatabase.class);
bind(H2Database.class);
}
The advantage of this approach is that you don't need to be able to know which database implementation to use until you actually make a database call.
Both of these approaches have been assuming that you cannot instantiate an instance of H2Database or SqliteDatabase unless the backing database file actually exists. If it's possible to instantiate the object without the backing database file, then your code becomes much simpler. (Just have a router/proxy/delegator/whatever that takes the actual Database instances as the constructor args.)
Third Approach
This approach is completely different then the last two. It seems to me like your code is actually dealing with two questions:
Does a database actually exist? (If not, then make one.)
Which database exists? (And get the correct class to interact with it.)
If you can solve question 1 before even creating the guice injector that needs to know the answer to question 2, then you don't need to do anything complicated. You can just have a database module like this:
public class MyDatabaseModule extends AbstractModule {
public enum DatabaseType {
SQLITE,
H2
}
private DatabaseType databaseType;
public MyDatabaseModule(DatabaseType databaseType) {
this.databaseType = databaseType;
}
protected void configure() {
if (SQLITE.equals(databaseType)) {
bind(Database.class).to(SqliteDatabase.class);
} else if (H2.equals(databaseType)) {
bind(Database.class).to(H2Database.class);
}
}
}
Since you've separated out questions 1 & 2, when you create the injector that will use the MyDatabaseModule, you can pass in the appropriate value for the constructor argument.
Notes
The Injector documentation states that there will exist a Provider<T> for every binding T. I have successfully created bindings without creating the corresponding provider, therefore Guice must be automatically creating a Provider for configured bindings. (Edit: I found more documentation that states this more clearly.)

JavaFX Wrap an Existing Object with Simple Properties

I am writing a new app and I have chosen to use Java for flexibility. It is a GUI app so I will use JavaFX. This is my first time using Java but I have experience with C#.
I am getting familiar with JavaFX Properties, they look like a great way of bi-directional binding between front-end and back-end.
My code uses classes from an open-source API, and I would like to convert the members of these classes to JavaFX Properties (String => StringProperty, etc). I believe this would be transparent to any objects that refer to these members.
Is it ok to do this?
Is it the suggested way of dealing with existing classes?
What do I do about Enum types? E.g. an enum member has it's value changed, how should I connect the enum member to the front-end?
Thank you :)
In general, as long as you don't change the public API of the class - in other words you don't remove any public methods, modify their parameter types or return types, or change their functionality - you should not break any code that uses them.
So, e.g. a change from
public class Foo {
private String bar ;
public String getBar() {
return bar ;
}
public void setBar(String bar) {
this.bar = bar ;
}
}
to
public class Foo {
private final StringProperty bar = new SimpleStringProperty();
public StringProperty barProperty() {
return bar ;
}
public String getBar() {
return barProperty().get();
}
public void setBar(String bar) {
barProperty().set(bar);
}
}
should not break any clients of the class Foo. The only possible problem is that classes that have subclassed Foo and overridden getBar() and/or setBar(...) might get unexpected behavior if their superclass is replaced with the new implementation (specifically, if getBar() and setBar(...) are not final, you have no way to enforce that getBar()==barProperty().get(), which is desirable).
For enums (and other objects) you can use an ObjectProperty<>:
Given
public enum Option { FIRST_CHOICE, SECOND_CHOICE, THIRD_CHOICE }
Then you can do
public class Foo {
private final ObjectProperty<Option> option = new SimpleObjectProperty<>();
public ObjectProperty<Option> optionProperty() {
return option ;
}
public Option getOption() {
return optionProperty().get();
}
public void setOption(Option choice) {
optionProperty().set(choice);
}
}
One caveat to all this is that you do introduce a dependency on the JavaFX API that wasn't previously present in these classes. JavaFX ships with the Oracle JDK, but it is not a full part of the JSE (e.g. it is not included in OpenJDK by default, and not included in some other JSE implementations). So in practice, you're highly unlikely to be able to persuade the developers of the open source library to accept your changes to the classes in the library. Since it's open source, you can of course maintain your own fork of the library with JavaFX properties, but then it will get tricky if you want to incorporate new versions of that library (you will need to merge two different sets of changes, essentially).
Another option is to use bound properties in the classes, and wrap them using a Java Bean Property Adapter. This is described in this question.

Wicket manage differents authentication sections

I'm working on a platform which contains several applications (sections). Each application owns her database. To access to one application, the user has to log in. So I use authrole system but the problem is I've only one WicketApplication class which must implement getWebSessionClass and getSignInClass methods. I would like to be able to return the correct class depending on the concerned application.
here is the code of the two methods :
#Override
protected Class<? extends AbstractAuthenticatedWebSession> getWebSessionClass() {
return BasicAuthenticationSession.class;
}
#Override
protected Class<? extends WebPage> getSignInPageClass() {
return SignInPage.class;
}
I am not exactly sure what you mean, but you could assign Roles to the user based on their credentials.
These roles can be used to protect for example pages.
For example:
#AuthorizeInstantiation( User.ROLE_APP_A_USER )
public class MySubApplicationAPage extends WebPage { ... }
Thanks for your help ! Finally, I've chosen to set up one Authentication page for all applications. And with a system of booleans, I manage the different access to each section.

Ninject NHibernate on plugin oriented architecture

According COMPOSITION ROOT pattern, I must to construct all dependencies graph as close as possible to the application's entry point.
My architecture is plugin oriented. So, if someone wants to extend my base system he can.
For example, in my base system I have this structure:
View Layer
Services Layer
Data Access Layer
Model Layer
In DAL, I expose some classes like:
IRepository
NHibernateRepository
ProductRepository
So, I'd like if a plugin wants to extend my base Product class to ExtendedProduct, and then create ExtendedProductRepository that inherits from NHibernateRepository.
The question is:
How can instantiate from my base system an instance of NHibernateRepository using NInject?
So, I know the first thing to do is to construct the graph dependencies:
using (var kernel = new StandardKernel())
{
kernel.Bind(b => b.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom<IRepository>()
.BindAllInterfaces());
}
However, I'm figuring out that when I execute something like:
kernel.GetAll<IRepository>()
It's going to return me a ProductRepository instance, and another ProductExtendedRepository under two IRepository objects.
So, how I can save a ProductExtended object from my base system...?
Another question, would be, how could I inject a object instance in my plugins, or, how can plugins autoinject some instance of base system assembly?
Thanks for all.
I'll appreciate a lot some help.
I use this pattern for my NHibernate based projects:
public interface IRepository<T> : IQueryable<T>
{
T Get(int id);
void Save(T item);
void Delete(T item);
}
public class NHibernateRepository<ModelType> : IRepository<ModelType>
where ModelType : class
{
// implementation
}
then...
public interface IProductRepository : IRepository<Product>
{
// product specific data access methods
}
public class ProductRepository : NHibernateRepository<Product>, IProductRepository
{
// implementation
}
... and in Ninject Module:
Bind(typeof(IRepository<>)).To(typeof(NHibernateRepository<>));
Bind<IProductRepository>().To<ProductRepository>();
then you can either request the base functionality like:
public Constructor(IRepository<Product> repo) { ... }
or specific product repository functionality:
public Constructor(IProductRepository repo) { ... }
your plugins can either get the base functionality and won't have to register anything:
public PluginConstructor(IRepository<ProductExtended> repo { ... }
or create their own repositories and register them in a Ninject module.
Thanks dave.
It's perfect. I'll try it.
However, how could I save or get or update (whichever IRepository methods)... an ExtendedProduct instance from my base system?
Think the follow out:
public interface BasePlugin<T> {...}
In another assembly:
public class PluginExtendedProduct : BasePlugin<ExtendedProduct>
{
public PluginExtendedProduct (IRepository<ExtendedProduct> repo { ... }
}
My headache is how to create an instance of (so, ExtendedProduct) in my base system in order to call methods PluginExtendedProduct that uses an IRepository.
I don't know if I'm explaining myself well...
Thanks for all.