Let say I'm trying to remove a object which is stored in hashmap of ClassA. ClassB is a static class which has a destroy method to remove required object from hashmap. Even after removing it, later when I tried to remove another object, i see old element which was removed before still exist. Is there something I'm missing?
#Named
#Scope
public class ClassA implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private Map<String, ModelObject> modelObjects = new HashMap<String, ModelObject>();
public synchronized void addMo(ModelObject modelObject) {
modelObjects.put(modelObject.getUuid(), modelObject);
}
public synchronized ModelObject updateMo(ModelObject modelObject) {
return modelObjects.put(modelObject.getUuid(), modelObject);
}
public synchronized void removeMo(ModelObject modelObject) {
modelObjects.remove(modelObject.getUuid());
}
public synchronized void removeMo(String modelObjectId) {
modelObjects.remove(modelObjectId);
}
public ModelObject getMo(String uuid) {
return modelObjects.get(uuid);
}
}
ClassB is
public class ClassB{
private static ClassA manager;
#Autowired(required = true)
public void setmanager(ClassA manager) {
ClassB.manager = manager;
}
public static synchronized void destoryMo(String modelObjectID) {
// get ClassA bean
if (manager == null) {
LOG.error("Managed bean ClassA not found (null) ==> no modelObject update!");
}
ModelObject wb = manager.getMo(modelObjectID);
if(wb != null){
wb.removeAllCache();
wb = null;
manager.removeMo(modelObjectID);
}
LOG.info("Destroyed ModelObject with modelObject id :" + modelObjectID);
}
}
Related
public class ServiceFactory {
private static ServiceFactory instance;
private final DishService dishService = new DishService();
private final OrderService orderService = new OrderService();
private final UserService userService = new UserService();
private ServiceFactory() {
}
public static synchronized ServiceFactory getInstance() {
if (instance == null) instance = new ServiceFactory();
return instance;
}
public DishService getDishService() {
return dishService;
}
public OrderService getOrderService() {
return orderService;
}
public UserService getUserService() {
return userService;
}
}
It is just a simple class for getting objects, but it seems like a messed up with naming.
If not, what should be a proper name for such a class?
Since you are essentially accessing the same instance of a set of xxxxService instead of "constructing" new ones, it does not comply with the factory pattern.
Naming it SharedServices makes more sense, given that you made it a singleton, and that it shares various instances of services across the application.
Factory pattern works as follows:
An interface exists
public interface Foo {
String make(String someString);
}
and there are multiple implementations of that interface:
public class DishOrder implements Foo {
//constructor
String make(String someString) {-- custom implementation--}
}
public class DrinkOrder implements Foo {
//constructor
String make(String someString) {-- custom implementation--}
}
And then the factory exists:
public class OrderFactory {
private DishOrder dishOrder;
private DrinkOrder drinkOrder;
//constructor
public Foo getFoo(String type) {
if(type.equals("Dish"))
return DishOrder;
//and every other implementation of the interface
//can use switch here as well
}
}
Hi everyone this is my simple project code block
This service is renewing by sending a request once a day.
public class SingletonService {
private static final SingletonService INSTANCE = new SingletonService();
public static final int TIMEOUT_SEC = 86400 ;//SECONDS every day ONE REQUEST remote service
private static final Object lock = new Object();
private LocalDateTime queryDate;//Time
private EmployeeRepository employeeRepository;//My Remote Employee Repository
private List<Employee> list = new CopyOnWriteArrayList<>();
SingletonService() {//Singleton Design Pattern
}
public static SingletonService getInstance() {
return INSTANCE;
}
private boolean isTimeout() {//this methods check date
LocalDateTime execDate = LocalDateTime.now();
if (queryDate == null) {
return true;
}
LocalDateTime expireDate = queryDate.plusSeconds(TIMEOUT_SEC);
return expireDate.isBefore(execDate);
}
public synchronized void reload() {//this methods call repository employee list
queryDate = LocalDateTime.now();
list = employeeRepository.findAll();
}
public void initQuery() {//this methods check expire date and list size
synchronized(lock) {
if (isTimeout() || list.size() <= 0) {
reload();
}
}
}
public Integer countLatestRanking() {
return list.size();
}
public void setEmployeeRepository(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
public List<Employee> getList() {
return this.list;
}
public void setList(List<Employee> list) {
this.list = list;
}
}
My SingletonInitService
#Component
public class SingletonInitService {
#Autowired
private EmployeeRepository employeeRepository;
#PostConstruct
public void init() {
SingletonService.INSTANCE.setEmployeeRepository(employeeRepository);
}
public void onContextRefreshedEvent() {
SingletonService.INSTANCE.initQuery();
}
public List<Employee> getEmployees(){
return SingletonService.INSTANCE.getList();
}
}
My EmployeeService
#Service
public class EmployeeService {
#Autowired
private SingletonInitService singletonInitService;
public List<Employee> getEmployees(){
singletonInitService.onContextRefreshedEvent();
return singletonInitService.getEmployees();
}
}
My question is how can I write SingletonService abtract because I have too many repositories and I don't want to write this code over and over again (Please don't say why you didn't use the scheduler because it's not good to use job all the time)
public interface A extends C {
String getCh();
String getId();
String getReview();
}
public interface B extends C {
String getCh();
String getId();
String getReview();
}
#Data
#Builder
public class AImpl implements A{
private String ch;
private String id;
private String review;
}
#Data
#Builder
public class BImpl implements B{
private String ch;
private String id;
private String review;
}
so now to use the builders of these I do:
return AImpl.builder()
.ch("ch")
.id("id")
.review("somerview");
For B I do:
return BImpl.builder()
.ch("ch1")
.id("id1")
.review("some new review");
Is there a way where I can make this builder part into a function? I dont like the idea of repeating the same code again. Like where I can pass id channel and review in a function and I can the object?
Disclaimer: I have never really dealt with builders so there might be a really much better option :D
This approach writes builders for each interface individually.
This does require that the interfaces provide a setter method.
Using generics, the methods of the RootBuilder and BaseABuilder return an instance of the ImplABuilder so that the chain can continue properly.
This is a very simple implementation of the Thistype generic which in other languages exists by default. This implementation also relies on casting to the actual Thistype but if you set the generics properly, that shouldnt be an issue.
public class Test
{
public static void main(String[] args)
{
ImplA implA = ImplA
.builder()
.id("id")
.description("description")
.valueA("a")
.build();
}
}
public interface Root
{
String getId();
void setId(String id);
String getDescription();
void setDescription(String description);
}
public class RootBuilder<Thistype extends RootBuilder<Thistype, Instance>, Instance extends Root>
{
protected final Instance object;
RootBuilder(Instance object)
{
this.object = object;
}
public Thistype id(String value)
{
object.setId(value);
return (Thistype)this;
}
public Thistype description(String value)
{
object.setDescription(value);
return (Thistype)this;
}
public Instance build()
{
return object;
}
}
public interface BaseA extends Root
{
String getValueA();
void setValueA(String valueA);
}
public class BaseABuilder<Thistype extends BaseABuilder<Thistype, Instance>, Instance extends BaseA> extends RootBuilder<Thistype, Instance>
{
protected Instance object;
BaseABuilder(Instance object)
{
super(object);
}
public Thistype valueA(String value)
{
object.setValueA(value);
return (Thistype)this;
}
}
public interface BaseB extends Root
{
String getValueB();
void setValueB(String valueB);
}
public interface BaseC extends Root
{
String getValueC();
void setValueC(String valueC);
}
public final class ImplA implements BaseA
{
private String id;
private String description;
private String valueA;
private ImplA() { }
public static ImplABuilder builder()
{
return new ImplABuilder(new ImplA());
}
private static class ImplABuilder extends BaseABuilder<ImplABuilder, ImplA> // assuming ImplA is final
{
ImplABuilder(ImplA object)
{
super(object);
}
// additional methods for ImplA class
}
}
I am trying to use inheritence and generics to create my application, but it doesn't seem to work the way I expect it to. I'll show you what I mean (TL;DR at the bottom):
public interface IModel extends Serializable {
public int save();
public void update();
public void delete();
}
// <T> is a JPA annotated entity/class
#SuppressWarnings("serial")
public abstract class Model<T> implements IModel {
private final Repository<T> _repository;
protected T _entity;
public Model(T entity, Repository<T> repository) {
this._entity = entity;
this._repository = repository;
}
public int save() {
return _repository.save(_entity);
}
...
}
This is implemented in for example my AccountModel, which is a Model with generic Account (which is a JPA entity) and which implements IAccount.
public class AccountModel extends Model<Account> implements IAccount {
private static final AccountRepository REPOSITORY = new AccountRepository();
public AccountModel(Account entity) {
super(entity, REPOSITORY);
}
// Method implementations...
}
My generic Repository looks like this:
public abstract class Repository<T> implements Serializable {
private static SessionFactory SESSION_FACTORY;
private final Class<T> _repositoryClass;
private static boolean _initiated = false;
public Repository(Class<T> repositoryClass) {
if (!Repository._initiated)
setup();
this._repositoryClass = repositoryClass;
}
private void setup() {
// logics
Repository._initiated = true;
}
public final Model<T> getById(int id) {
Session session = SESSION_FACTORY.openSession();
try {
session.beginTransaction();
T t = session.get(_repositoryClass, id);
return new Model<T>(t, this); // As suggested by #Vlad
}
finally {
session.close();
}
}
}
The account implementation of this abstract Repository is:
public class AccountRepository extends Repository<Account> {
public AccountRepository() {
super(Account.class);
}
public Model<Account> getByEmail(String emailAddress) {...}
}
So far so good, this is all working as expected. But I cannot use a Model<T> as a TModel.
TL;DR
I would like use the following line of code:
AccountModel account = new AccountRepository().getById(1);
Since AccountModel inherits Model<Account> and new AccountRepository().getById() always returns Model<Account> I expect this to work, but it doesn't.
What am I missing?
Am developing webapplication with JSF and Hibernate, have Entity, Entity data access & JSF managed bean classes in following pattern and same repeats in all the classes. Since all the classes have the same pattern, I would like to make it as abstract class.
Entity Class
public class MyEntity {
-----
-----
}
Data Access class
public class MyEntityDAO extends AbstractDAO<MyEntity> {
MyEnitityDAO(){
-------
}
}
JSF Managed bean
public class MyBean implements Serializable {
private static final long serialVersionUID = 1L;
private MyEntity current;
private MyEntityDAO dao;
private DataModel<MyEntity> items = null;
public MyBean() {
// TODO Auto-generated constructor stub
}
public MyEntity getCurrent() {
return current;
}
public void setCurrent(MyEntity current) {
this.current = current;
}
public MyEntityDAO getDao() {
if (dao == null) {
dao = new MyEntityDAO();
}
return dao;
}
public DataModel<MyEntity> getItems() {
return items;
}
public List<MyEntity> getMyEntityList() {
return getDao().findAll();
}
public MyEntity getMyEntity(int id) {
return getDao().findById(id);
}
private void reSetDataModel() {
items = null;
}
private void reSetCurrent() {
setCurrent(null);
}
public void prepareCreate() {
current = new MyEntity();
}
public void create() {
// Save the entity
}
public void edit() {
// Update the entity
}
public void delete() {
// Remove the entity
}
}
How to make the abstract class out of above pattern?
Type the word abstract between public and class