New ViewScoped Bean instance on multiple fileUpload - primefaces

I'm using primefaces 5.1.7 with wildfly and have a Problem when multiple pictures are uploaded at the same time.
I have multiple instances of a ViewScoped bean which are created (tested using breakpoints in #PostConstruct)
xhtml:
<h:form enctype="multipart/form-data" prependId="true">
<p:fileUpload fileUploadListener="#{myBean.handleFileUpload}"
mode="advanced" auto="true" update="list"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/" multiple="true"/>
...
bean:
import javax.faces.view.ViewScoped;
#Named
#ViewScoped
public class MyBean implements Serializable {
...
public void handleFileUpload(FileUploadEvent event) {
...
}
}
This happens about 75% of the time but sometimes everything is just fine. Any idea how i can avoid those multiple instances?

a possible solution... (not tested!!):
Your Session scoped CDI Bean:
...
import javax.enterprise.context.SessionScoped
...
#SessionScoped
public class MySession implements Serializable {
public void doSomeWork(...) {
...
}
}
And your Conversation scoped CDI Bean:
...
import javax.inject.Named
import javax.enterprise.context.ConversationScoped
...
#Named
#ConversationScoped
public class MyBean implements Serializable {
#Inject
private Conversation conversation;
#Inject
private MySession mySession;
#PostConstruct
public void init() {
conversation.begin();
}
public void handleFileUpload(FileUploadEvent event) {
...
mySession.doSomeWork(...);
...
}
public void remove() {
conversation.end();
}
}
And your Controller:
#Named
public class MyController implements Serializable {
#Inject
private MyBean myBean;
public String doSomethingAfterAllUploadsAreFinished() {
...
myBean.remove();
return "SUCCESS";
}
}

Related

Postman showing empty JSON object from spring boot rest api

public class UserController {
#Autowired
private UserRepository userRepository;
#GetMapping
public List<User> findAllUsers() {
return (List<User>) userRepository.findAll();
}
}
This is the code of the controller class
you specified the url in the #RequestMapping("...") annotation
#RequestMapping("url")
public class UserController {
#Autowired
private UserRepository userRepository;
#GetMapping
public List<User> findAllUsers() {
return (List<User>) userRepository.findAll();
}
and add the #RestController annotation above the class

How to mock Abstract class using Mockito?

I am trying to mock abstract class which is called within another class. I mocked the abstract class however mocked abstract class is not being injected.
Any advise on how to mock the abstract class and inject it?
public abstract class MyAbstractClass {
public HelloBean getHelloBean(HelloBean bean){
return bean;
}
}
public class MyBusinessClass extends MyAbstractClass {
public String getBusinessData(){
HelloBean bean = getHelloBean(new HelloBean()) //I want to mock this method while testing getBusinessData()
}
}
My JUnit Class
public class MyBusinessClass {
private MyAbstractClass myAbstractClass = mock(MyAbstractClass.class);
private MyBusinessClass myBusinessClass = mock(MyBusinessClass.class);
#Test
public String getBusinessData(){
when(myAbstractClass.getHelloBean(any(HelloBean.class))).doReturn(new HelloBean());
myBusinessClass.getBusinessData();
}
}
By using Inject Mock it works
Here the test class is
#SpringBootTest
#AutoConfigureMockMvc
public class HelloServiceMockTest {
#InjectMocks
MyBusinessClass myBusinessClass;
#Mock
MyAbstractClass myAbstractClass;
#Mock
HelloBean helloBean;
#Test
public void getBusinessData(){
when(myAbstractClass.getHelloBean(helloBean)).thenReturn(new HelloBean());
myBusinessClass.getBusinessData();
Assert.assertEquals("ggg",myBusinessClass.getBusinessData());
}
}
HelloBean class is
public class HelloBean {
public String get()
{
return "ggg"; }
}
MyBusinessClass is
public class MyBusinessClass extends MyAbstractClass {
public String getBusinessData(){
HelloBean bean = getHelloBean(new HelloBean()); //I want to mock this method while testing getBusinessData()
return bean.get();
}
}

autowired ObjectMapper is null during #DataJpaTest

I want to test my implementation for AttributeConverter using #DataJpaTest.
test code
#RunWith(SpringRunner.class)
#DataJpaTest
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class FooRepositoryTest {
#Autowired
private FooRepository repository;
#Test
void getPojoTest(){
FooEntity fooEnity= repository.findById("foo");
FooPojo fooPojo = fooEntity.getJsonPojo()
//some assertion
}
}
Entity
#Entity
#Data
#NoArgsConstructor
public class FooEntity{
....
#Column(columnDefinition= "JSON")
#Convert(converter = FooConverter.class)
private FooPojo data;
....
}
Attribute Converter
public class FooConverter implements AttributeConverter<FooPojo, String> {
#Autowired
private ObjectMapper mapper;
#SneakyThrows
#Override
public String convertToDatabaseColumn(FooPojo attribute) {
return mapper.writeValueAsString(attribute);
}
#SneakyThrows
#Override
public FooPojo convertToEntityAttribute(String dbData) {
return mapper.readValue(dbData, FooPojo.class);
}
}
with my code above, when I run getPojoTest(), the #autowired OjbectMapper in Converter is null. When I try the same test with #SpringBootTest instead, it works just fine. I wonder is there any walk-around to use #DataJpaTest and ObjectMapper together.
A better alternative compared to creating your own ObjectMapper is adding the #AutoConfigureJson annotation:
#DataJpaTest
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
#AutoConfigureJson
public void FooRepositoryTest {
}
This is also what #JsonTest uses.
From Docs:
#DataJpaTest can be used if you want to test JPA applications. By
default it will configure an in-memory embedded database, scan for
#Entity classes and configure Spring Data JPA repositories. Regular
#Component beans will not be loaded into the ApplicationContext.

JavaFx maven, MySql, Hibernate,JPA desktop app: doesnt save yet no error or logs

I am creating a simple CRUD JavaFX desktop application but it cant save any records and doesn't throw errors or any logs.
Using Hibernate 4.3.8, Netbeans 8.0.2, Java 8. Generated POJO in Netbeans See code snippets
HibernateUtil
private static EntityManager entityManager;
public static EntityManager getEntityManager() {
if (entityManager == null) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistence");
entityManager = emf.createEntityManager();
}
return entityManager;
}
UserService
#Service
#Configurable
public class UsersService implements IServiceInterface<Users> {
#Override
public Users save(Users entity) {
return usersDAO.save(entity);
}
UserController
#Controller
public class UserCtrl implements Initializable {
private final IServiceInterface userService = new UsersService();
public void addUser(Users user) {
userService.save(user);
}
}
ViewUsers
public class ViewUsers {
#FXML
private TextField username;
#FXML
private TextField password;
public void addUser(ActionEvent event) {
Users user = new Users();
user.setUserName(username.getText());
user.setUserPass(password.getText());
userCtrl.addUser(user);
}
}
View.fxml
<GridPane fx:controller="com.users.view.users"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"
styleClass="root">
<TextField fx:id="username" GridPane.columnIndex="1" GridPane.rowIndex="1"/>
<PasswordField fx:id="password" GridPane.columnIndex="1" GridPane.rowIndex="2"/>
<Button text="Sign In" onAction="#addUser"/>
</GridPane>
UPDATE I am using GenericDao
final EntityManager em = HibernateUtil.getEntityManager();
#Override
public T save(T entity) {
final T savedEntity = em.merge(entity);
return savedEntity;
}

Performing a custom action when a given mocked void method is called

I would like to be able for Mockito to perform a custom action when a given void method is called.
Say I have the following code:
#Autowired
private ProfileService profileService;
#Autowired
private ProfileDao profileDao;
private List<Profile> profiles;
#Before
public void setup() {
Mockito.when(profileDao.findAll()).thenReturn(profiles);
Mockito.when(profileDao.persist(any(Profile.class))).thenAddProfileToAboveList...
}
#Configuration
public static class testConfiguration {
#Bean
public ProfileDao ProfileDao() {
return mock(ProfileDao.class);
}
}
Say I want to add a Profile instance to the profiles list. Can Mockito do that? If so how?
Use Mockito.doAnswer.
doAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
// make the changes you need here
}})
.when(mock).someMethod();