I am developing a web application in jsf
I have these classes
Abstract:
RepositoryBase
ManagedBeanCRUD
EntityBase
Classes:
Client extends EntityBase
ClientRepository extends RepositoryBase
ClientManagedBean extends ManagedBeanCRUD
However I am having trouble to implement a save method at ManagedBeanCRUD
during this method I need a Repository, so I have a RepositoryBase rep = repositoryfactory.getFactory((entity.getClass()));
I tried to implement the repositoryFactory in many ways, but still without success.
Anyone has any idea how I could do this???
thank you in advance
public class ManagedBeanCRUD < T extends EntityBase> () {
protected T newEntity;
public void save() {
Repositoryfactory factory = new Repositoryfactory();
RepositoryBase<T> rep = factory.getFactory((entity.getClass()));
rep.persiste(newEntity);
}
}
public class FactoryRepository < T extends EntityBase> () {
public RepositoryBase<T> getFactory(Class newEntity) {
if(newEntity == Client.class) {
return new ClientRepository();
} else {
System.out.println("error");
}
}
}
public class ClientManagedBean extends CRUDBean<Client> {
private static final long serialVersionUID = 1L;
private Clietn client = new Client();
public void setSalve(){
this.setNewEntity(this.client);
this.salvar();
this.client = new Client();
}
}
public class ClientRepository extends RepositoryBase{
#Override
protected Class<Client> getRuntimeClass() {
return Client.class;
}
}
Related
I could need some help with a problem I have with Java's generics.
I constructed a little example for to show what I mean.
Handler
package generalizingTest;
public class Handler<S extends Server<?>> {
public S server;
public Handler(S server) {
this.server = server;
}
}
SubHandler
package generalizingTest;
public class SubHandler<S extends Server<?>> extends Handler<S> {
public SubHandler(S server) {
super(server);
}
public void subHandlerMethod() {
}
}
Server
package generalizingTest;
import java.util.ArrayList;
public class Server<H extends Handler<?>> {
public ArrayList<H> handlers;
public Server() {
handlers = new ArrayList<H>();
}
public void addHandler(H c) {
handlers.add(c);
}
}
SubServer
package generalizingTest;
public class SubServer<H extends Handler<?>> extends Server<H> {
public void subServerMethod() {
}
}
Startup
package generalizingTest;
public class Startup {
public static void main(String[] args) {
Server<Handler<?>> serverWHandler = new Server<Handler<?>>();
Server<SubHandler<?>> serverWSubHandler = new Server<SubHandler<?>>();
SubServer<Handler<?>> subServerWHandler = new SubServer<Handler<?>>();
SubServer<SubHandler<?>> subServerWSubHandler = new SubServer<SubHandler<?>>();
Handler<Server<?>> handlerWServer = new Handler<Server<?>>(serverWHandler);
Handler<SubServer<?>> handlerWSubServer = new Handler<SubServer<?>>(subServerWHandler);
SubHandler<Server<?>> subHandlerWServer = new SubHandler<Server<?>>(serverWSubHandler);
SubHandler<SubServer<?>> subHandlerWSubServer = new SubHandler<SubServer<?>>(subServerWSubHandler);
serverWHandler.addHandler(handlerWServer);
subServerWHandler.addHandler(handlerWSubServer);
serverWSubHandler.addHandler(subHandlerWServer);
subServerWSubHandler.addHandler(subHandlerWSubServer);
subServerWHandler.subServerMethod();
subServerWSubHandler.subServerMethod();
handlerWSubServer.server.subServerMethod();
subHandlerWSubServer.server.subServerMethod();
subHandlerWServer.subHandlerMethod();
subHandlerWSubServer.subHandlerMethod();
System.out.println(subHandlerWSubServer.server.handlers.get(0).getClass().getName()); // SubHandler
//produces an error:
/*
* Unresolved compilation problem:
* The method subHandlerMethod() is undefined for the type Handler<capture#9-of ?>
*/
//subHandlerWSubServer.server.handlers.get(0).subHandlerMethod();
}
}
I just started learning about generics. They seem to be efficient but I am not sure if I solved the problem of the generics loop () correctly with the wildcard and why those errors occur.
I really hope someone can help me out.
EDIT:
So it seems like I did not highlighted the initial problem enough.
The following should be possible in any depth:
subHandlerWSubServer.server.handlers.get(0).server.handlers.get(0).server.handlers.get(0). ... .server.handlers.get(0).subHandlerMethod();
EDIT:
So this problem seems not to be solvable due to an endless loop of definition or the missing self value, see Siguza’s anwser.
Here is the discussion between Siguza, user889742 and myself about this topic.
If I understood you correctly, if you have a Handler<S> you want all handlers on that server to be of type Handler<S>, right?
For that, S.add() would have to only accept objects of type Handler<S>. But in order to implement that in the base class Server, you would need S, so that:
public class Server<H>
{
public ArrayList<H<S>> handlers;
public Server()
{
handlers = new ArrayList<H<S>>();
}
public void addHandler(H<S> c)
{
handlers.add(c);
}
}
The only problem with this is that S is not defined, and you cannot easily define it. What you would need is something that, in the context of Server, means Server, and in the context of SubServer, means SubServer. Basically this.getClass(), but as a compile-time type expression. If Java had a keyword for that, say self, you could use it like this:
public class Server<H>
{
public ArrayList<H<self>> handlers;
public Server()
{
handlers = new ArrayList<H<self>>();
}
public void addHandler(H<self> c)
{
handlers.add(c);
}
}
Then Server.add() would take Handler<Server>, and SubServer.add() would take Handler<SubServer>.
Sadly, Java has no such thing, therefore what you're trying to do is not possible this way.
Java does many things well.
Generics aren't one of them.
It could work with a redesign like this. You would not be able to use Server as your starting point, since it would require generic arguments leading to a recursive definition again. Instead, start with ServerInfo. As you can check it works, but I think it might be a bit cumbersome and not intuitive.
class Server
{
}
class Handler
{
}
class SubServer extends Server
{
}
class SubHandler extends Handler
{
public void subHandlerMethod(){}
}
class HandlerInfo<S extends Server, H extends Handler>
{
ServerInfo<S,H> serverInfo;
H handler;
}
class ServerInfo<S extends Server, H extends Handler>
{
S server;
ArrayList<HandlerInfo<S,H>> handlerInfo = new ArrayList<>();
}
public class Example {
public static void main(String[] args) {
Server s = new Server();
SubHandler h = new SubHandler();
ServerInfo<Server,SubHandler> serverInfo = new ServerInfo<>();
HandlerInfo<Server,SubHandler> handlerInfo = new HandlerInfo<>();
handlerInfo.serverInfo = serverInfo;
handlerInfo.handler = h;
serverInfo.server = s;
serverInfo.handlerInfo.add(handlerInfo);
serverInfo.handlerInfo.get(0).serverInfo.handlerInfo.get(0).handler.subHandlerMethod();
}
}
Edit:
You could simply restrict SubServers to only accept SubHandlers
Subserver<H extends SubHandler> extends Server<H>
When you do that you will see that the compilation error goes away.
But I understand you want to define some Servers that allow only subHandlers, and some subHandlers that allow only Servers. ( Seems strange to me ), and then reflexive relationship H<->S gives you trouble, leading to generic type recursion.
While I think it's strange to mix Server->Subhandler and Handler->SubServer , you could accomplish an unrestricted 2 way relationship as you want by extracting interfaces like this: ( try it, it works )
interface IHandler
{
}
interface IServer
{
}
interface ISubServer extends IServer
{
public void subServerMethod();
}
interface ISubHandler extends IHandler
{
public void subHandlerMethod();
}
class Handler<S extends IServer> implements IHandler {
public S server;
public Handler(S server) {
this.server = server;
}
}
class SubHandler<S extends IServer> extends Handler<S> implements ISubHandler {
public SubHandler(S server) {
super(server);
}
public void subHandlerMethod() {
}
}
class Server<H extends IHandler> implements IServer{
public ArrayList<H> handlers;
public Server() {
handlers = new ArrayList<H>();
}
public void addHandler(H c) {
handlers.add(c);
}
}
class SubServer<H extends IHandler> extends Server<H> implements ISubServer {
public void subServerMethod() {
}
}
public class Example {
public static void main(String[] args) {
Server<IHandler> serverWHandler = new Server<IHandler>();
Server<ISubHandler> serverWSubHandler = new Server<ISubHandler>();
SubServer<IHandler> subServerWHandler = new SubServer<IHandler>();
SubServer<ISubHandler> subServerWSubHandler = new SubServer<ISubHandler>();
Handler<IServer> handlerWServer = new Handler<IServer>(serverWHandler);
Handler<ISubServer> handlerWSubServer = new Handler<ISubServer>(subServerWHandler);
SubHandler<Server<ISubHandler>> subHandlerWServer = new SubHandler<Server<ISubHandler>>(serverWSubHandler);
SubHandler<SubServer<ISubHandler>> subHandlerWSubServer = new SubHandler<SubServer<ISubHandler>>(subServerWSubHandler);
serverWHandler.addHandler(handlerWServer);
subServerWHandler.addHandler(handlerWSubServer);
serverWSubHandler.addHandler(subHandlerWServer);
subServerWSubHandler.addHandler(subHandlerWSubServer);
subServerWHandler.subServerMethod();
subServerWSubHandler.subServerMethod();
handlerWSubServer.server.subServerMethod();
subHandlerWSubServer.server.subServerMethod();
subHandlerWServer.subHandlerMethod();
subHandlerWSubServer.subHandlerMethod();
System.out.println(subHandlerWSubServer.server.handlers.get(0).getClass().getName()); // SubHandler
//no longer produces an error:
subHandlerWSubServer.server.handlers.get(0).subHandlerMethod();
}
}
and remember, anytime your problem is a reflexive relationship A<->B , not just with generics, you can extract IA and IB so that A->IB and B-> IA
Hi ive been reading on some similar topics here but none of them answer my question. Some say you cant even do this which is not a good thing since I cant finnish my course in that case.
Heres som simple code. Think of each block as a separate class.
public interface Interface {
void printMessage(String meddelande);
}
public class Model implements Interface {
String message = "hej!";
public static void main(String[] args) {
Model model1 = new Model();
View view1 = new View();
model1.printMessage(model1.message); //Ska jag anropa funktionen såhär ens?
}
public void printMessage(String str) {
}
}
public class View implements Interface {
printMessage(String str) {
}
}
So, how is it now possible to tel the view to print this string from the model class without the classes knowing about each other? Its not allowed to send a reference of the model-objekt to the view-object. ; (
Define an Interface:
public interface MyInterface {
void printMessage(String str);
}
Define a class that can trigger the notification:
public class ClassNotifier {
MyInterface mInterface;
public ClassNotifier(MyInterface mInterface) {
this.mInterface = mInterface;
}
public void triggerTheMsg(String msg) {
if (mInterface != null) {
mInterface.printMessage(msg);
}
}
}
Define a class that will be informed:
public class InformedClass implements MyInterface {
public static void main(String[] args) throws Exception {
InformedClass c = new InformedClass();
ClassNotifier cn = new ClassNotifier(c);
}
#Override
public void printMessage(String newMsg) {
System.out.println("A new msg is here: " + newMsg);
}
}
How does it works?:
this is named a callback parttern, the class ClassNotifier has a reference to the interface MyInterface, which is impl. by Informed class to, so every time the ClassNotifier calls the method printMessage, the method printMessage in the class Informed will be triggered too.
I advice you to use dependency injection, for example:
public class Model {
String message = "hej!";
Interface printer;
public void Model(Interface printer) {
printer = printer;
}
public static void main(String[] args) {
Model model1 = new Model(new View());
model1.printMessage(model1.message);
}
public void printMessage(String str) {
printer.printMessage(str);
}
}
I would like to create an enum containing one attribut, a list of objects extending the same interface or the same abstract class.
The objective is to have a loop on each list of my enum to call methods dynamically.
public interface Regles {
void verifier();
}
public class Regle01 implements Regles {
#Override
public void verifier() {
}
}
public class Regle02 implements Regles {
#Override
public void verifier() {
}
}
public enum ListRegles {
ENUM1(Arrays.asList(new Regle01(), new Regle02())),
ENUM2(Arrays.asList(new Regle01()))
private List<Regles> regles = new ArrayList<Regles>();
ListRegles(List<Regles> r) {
regles = r;
}
}
how can i do this please ?
enum:
public enum ListRegles {
ENUM1(new Regle01(),new Regle02()),
ENUM2(new Regle01());
private List<Regles> regles ;
ListRegles(Regles... regles) {
this.regles = new ArrayList<>(Arrays.asList(regles));
}
public void verify() {
for (Regles regle : regles) {
regle.verifier();
}
}
}
Will call verifier for Regle01 and Regle02
ListRegles.ENUM1.verify();
I am looking for a design pattern / solution for the following problem, that is related to the Observer pattern, I have already studied.
In my code I have a MyModel class. It has many properties.
public class MyModel {
private List<Flower> flowers = new ArrayList<Flower>();
private List<Toys> toys = new ArrayList<Toys>();
private List<Coffee> coffees = new ArrayList<Coffee>();
private List<IBusinessEntityListener> listener =
new ArrayList<IBusinessEntityListener>();
public void addChangeListener(IBusinessEntityListener newListener) {
listener.add(newListener);
}
}
So classes that implement IBusinessEntityListener can register to MyModel class.
Then I have 10+ listeners that are interested only in some properties of MyModel. They all implement IBusinessEntityListener. But how can I specify (for example with Java Generics?) that some listener are only interested in Flowers, some only about Toys, etc.?
So How to design such class structure that would support listening to certain properties?
All listeners would anyway implement 3 methods for the operations add, update and delete.
How about an application of the Extrinsic Visitor pattern?
Define an interface for properties:
public interface ListenableProperty {
// Degenerate interface for listeners
public interface Listener {}
public void acceptUpdate(Listener listener);
}
Then implement a class for each property, and a Listener interface for each property, and use like so from your model:
public class MyModel {
public static class FlowersProperty implements ListenableProperty {
public interface Listener extends ListenableProperty.Listener {
public void update(FlowersProperty p);
}
#Override
public void acceptUpdate(ListenableProperty.Listener listener) {
if (listener instanceof FlowersProperty.Listener) {
Listener myListenerType = (Listener)listener;
myListenerType.update(this);
}
}
// some property accessors here
}
public static class ToysProperty implements ListenableProperty {
public interface Listener extends ListenableProperty.Listener {
public void update(ToysProperty p);
}
#Override
public void acceptUpdate(ListenableProperty.Listener listener) {
if (listener instanceof ToysProperty.Listener) {
Listener myListenerType = (Listener)listener;
myListenerType.update(this);
}
}
// some property accessors here
}
private FlowersProperty flowers = new FlowersProperty();
private ToysProperty toys = new ToysProperty();
private List<ListenableProperty> properties = new ArrayList();
// CopyOnWrite so that listeners can remove themselves during update if desired
private List<ListenableProperty.Listener> listeners =
new CopyOnWriteArrayList<>();
// Convenience interface for implementors that want all properties
public interface AllPropertiesListener extends
FlowersProperty.Listener,
ToysProperty.Listener
{}
public MyModel() {
properties.add(flowers);
properties.add(toys);
}
public void addListener(ListenableProperty.Listener l) {
if (!listeners.contains(l)) {
listeners.add(l);
}
}
private void updateAll() {
for (ListenableProperty p : properties) {
for (ListenableProperty.Listener l : listeners) {
p.acceptUpdate(l);
}
}
}
private void updateToys() {
for (ListenableProperty.Listener l : listeners) {
toys.acceptUpdate(l);
}
}
private void updateFlowers() {
for (ListenableProperty.Listener l : listeners) {
flowers.acceptUpdate(l);
}
}
}
Listeners can then implement as many or as few of the listener interfaces as they please, or all of them via the convenience interface MyModel.AllPropertiesListener
You could also move the update routines for individual properties to the properties themselves.
for any type of Listeners have a class :
FlowerListerner implemts IBusinessEntityListener;
ToyListerner implemts IBusinessEntityListener;
and a listener list:
public class MyModel {
private List<Flower> flowers = new ArrayList<Flower>();
private List<Toys> toys = new ArrayList<Toys>();
private List<IBusinessEntityListener> flowerListeners =
new ArrayList<IBusinessEntityListener>();
private List<IBusinessEntityListener> toyListeners =
new ArrayList<IBusinessEntityListener>();
public void addListener(IBusinessEntityListener newListener) {
if(newListener instance of FlowerListener)
flowerListeners.add(newListener);
else if (newListener instance of ToyListener)
} toyListeners.add(newListener);
updateFlowerListeners() { ....}
updateToyListeners() { ....}
}
and any changes to each property reflect to related listeners.
UPDATE
another solution is that u have a list of interest in Listener Object:
Class Listener {
private List<Class> interests;
public Listener(List<Class> interests) {
this.interests = interests;
}
public boolean isInterested(Class clazz) {
return list.contains(clazz);
}
public void update() { ... }
}
an in model :
public class MyModel {
private List<Flower> flowers = new ArrayList<Flower>();
private List<Toys> toys = new ArrayList<Toys>();
private List<Listener> listeners =
new ArrayList<Listener>();
public void addListener(Listener newListener) {
listeners.add(newListener);
}
updateFlowerListeners() {
for(Listener l : listerners) {
if(l.isInterested(Flower.class)
l.update();
}
updateToyListeners() { ... }
}
here's an example of what I'm trying to do
public class BookModel {
private void update_method() {
get_info task = new get_info(this)
task.exicute(some args);
}
public void finishedCallback(some_return_type result) {
// do some stuff when finsiehd.
}
class get_info extends AsyncTask<HashMap<String, String>, Void, dataType>
{
private BookModel bookModel;
public get_info ( BookModel reset) {
bookModel = reset;
}
#Override
protected dataType doInBackground(arg...)
some procscessing.
}
protected void onPostExecute(dataType result) {
bookModel.finishedCallback(result);
}
}
}
How can i get this callback system to work... I tried using an inteface as well, but it did not work. I think it's because you need 3 classes with an interface (correct me if I'm wrong). also I'm open to any suggestions, but Ideally I would like to keep this functionality within the same class if possible. any help with this would be greatly appreciated.
try this.
this is worked for me.
public class BookModel implements get_info.xyz {
private void update_method() {
get_info task = new get_info(this);
task.exicute(some args);
}
public void finishedCallback(String result) {
// do some stuff when finsiehd.
}
}
//----------------------------------
class get_info extends AsyncTask<HashMap<String, String>, Void, dataType>
{
private xyz bookModel;
public interface xyz
{
void finishedCallback(String str);
}
public get_info ( xyz reset) {
bookModel = reset;
}
#Override
protected dataType doInBackground(arg...)
some procscessing.
}
protected void onPostExecute(dataType result) {
bookModel.finishedCallback(result);
}
}