Liferay transactional method - java

I want to call method filterFindByG_U from DLFileEntryUtil. The problem is, that the method in which I call filterFindBy must be transactional. But I dont know how to do this. I tried to write an annotation #Transactional before the method declaration but this didn't help. Can someone please give me some idea how to do this in Liferay 6.2? The method that should be transactional is:
public List<DLFileEntry> filterEntriesPermissions(User user) {
List<DLFileEntry> filtered = new ArrayList<DLFileEntry>();
try {
filtered = DLFileEntryUtil.filterFindByG_U(user.getGroupId(), user.getUserId());
} catch (SystemException | PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return filtered;
}
I will be thankful for some help and explanation.

Try this method:
DLFileEntryLocalServiceUtil.getGroupFileEntries(user.getGroupId(), user.getUserId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS);

Related

Unit test for method which calls void method in catch block and throws exception

I have a project with Morphia ORM - Without transactions. And I have this method:
public void methodForTest() {
try {
methodCanThrowException();
} catch (Exception e) {
methodWhiсhICanNotTest(template);
throw new Exception("message of exception");
}
}
private void methodWhiсhICanNotTest(String template){
serviceWhichCanBeMockOne.clearAll(template);
serviceWhichCanBeMockTwo.clearAll(template);
serviceWhichCanBeMockThree.clearAll(template);
}
Can I check that methodWhiсhICanNotTest(); was called? or how can I rewrite this code for easier testing?
UPDATE ANSWER FOR THE UPDATED QUESTION :D
If your methodWhiсhICanNotTest is a private method. Then you cannot verify it using Mockito in my previous answer. PowerMock is another solution for you. Read this article and try it :-)
=======================
You can use Mockito to verify whether methodWhiсhICanNotTest is called.
Mockito.verify(abc.methodWhiсhICanNotTest())

Create instance of Generic class at runtime with getConstructor(): NoSuchMethodException()

am using generics and need to create an instance of a generic class at runtime, so I am trying to use getConstructor(). Unfortunately, I receive a NoSuchMethodException despite having the correct signature, so I am at a loss as to what is wrong. I will appreciate your suggestions so I can get beyond this issue. :) I've provided the constructors for CustomerAssembler. I need to create an instance of this class, dynamically, due to generics being used. I've included the snippet of code that I am using. In it, I called getConstructors() to see whether the constructors exist and their signatures. Both constructors exist and I have used the proper signature, so I don't know why I keep getting this exception. Arggg... Hopefully, you will see what I am doing wrong. :)
Thank you for your time and help,
Mike
// Here are the constructors for CustomerAssembler.
public CustomerAssembler()
{
super();
}
public CustomerAssembler(
Class<Customer> entityClass,
Class<CustomerPreviewDTO> entityPreviewDTOClass,
Class<CustomerDetailDTO> entityDetailDTOClass,
Class<CustomerUpdateDTO> entityUpdateDTOClass,
EntityManager entityManager)
{
super(entityClass, entityPreviewDTOClass, entityDetailDTOClass, entityUpdateDTOClass, entityManager);
}
Here is the exception: NoSuchMethodException:
java.lang.NoSuchMethodException: assemblers.CustomerAssembler.<init>(entities.Customer, dtos.CustomerPreviewDTO, dtos.CustomerDetailDTO, dtos.CustomerUpdateDTO, javax.persistence.EntityManager)
Here is the code...
try
{
Class<CustomerAssembler> customerAssemblerClass = CustomerAssembler.class;
Constructor<CustomerAssembler>[] lst = (Constructor<CustomerAssembler>[]) this.customerAssemblerClass.getConstructors();
/* See what the signature is for the non-default constructor, so I can make sure that
getConstructor() is configured properly. Here is what was reported in the debugger:
[0] = {java.lang.reflect.Constructor#10796}"public assemblers.CustomerAssembler()"
[1] = {java.lang.reflect.Constructor#10797}"public assemblers.CustomerAssembler(java.lang.Class,java.lang.Class,java.lang.Class,java.lang.Class,javax.persistence.EntityManager)"
signature = {java.lang.String#10802}"(Ljava/lang/Class<Lentities/Customer;>
Ljava/lang/Class<dtos/CustomerPreviewDTO;>
Ljava/lang/Class<dtos/CustomerDetailDTO;>
Ljava/lang/Class<dtos/CustomerUpdateDTO;>
Ljavax/persistence/EntityManager;)V"
*/
// Configure our constructor call... this.contactAssemblerClass
Constructor<CustomerAssembler> ca =
customerAssemblerClass.getConstructor(
Customer.class,
CustomerPreviewDTO.class,
CustomerDetailDTO.class,
CustomerUpdateDTO.class,
EntityManager.class);
// Create an instance here...
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
customerAssemblerClass.getConstructor(
Customer.class,
CustomerPreviewDTO.class,
CustomerDetailDTO.class,
CustomerUpdateDTO.class,
EntityManager.class);
This looks for a constructor that has the following signature:
CustomerAssemble(Customer c,
CustomerPreviewDTO cpDTO,
CustomerDetailDTO cdDTO,
CustomerUpdateDTO cuDTO,
EntityManager em)
Your constructor doesn't take that as argument. It takes 4 instances of Class, and an instance of EntityManager.
So the code should be
customerAssemblerClass.getConstructor(
Class.class,
Class.class,
Class.class,
Class.class,
EntityManager.class);

Why is there no InputManager.getInstance() for me? And injectInputEvent()?

I'm trying to develop a service that injects touch events to the system while the service interacts with some hardware/remote server. I've googled and everyone suggests using the InputManager class, referencing Monkey as an example project to follow.
However, there is no getInstance() method for me in InputManager! All I have access to is exactly what the documentation shows. No getInstance() method, and most importantly, no injectInputEvent() method.
My build target SDK is Android 4.1.2, and my AndroidManifest.xml file specifies a target SDK version of 16 (I've tried changing the min target to 16 too, which didn't help (plus I'd like to keep it at 8 if possible)).
How on earth can I use InputManager like Monkey does? Where are the methods Monkey is using, and why can't I use them?
You cannot inject input events to one application from other application. Also you cannot inject events to your own application from within application. https://groups.google.com/forum/?fromgroups=#!topic/android-developers/N5R9rMJjgzk%5B1-25%5D
If you want to automate, you can use monkeyrunner scripts to do the same.
Class cl = InputManager.class;
try {
Method method = cl.getMethod("getInstance");
Object result = method.invoke(cl);
InputManager im = (InputManager) result;
method = cl.getMethod("injectInputEvent", InputEvent.class, int.class);
method.invoke(im, event, 2);
}
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Maybe this is a bit late but could be helpful for future reference.
Method 1: Using an instrumentation object
Instrumentation instrumentation = new Instrumentation();
instrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
instrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
Method 2: Using internal APIs with reflection
This method uses reflection to access internal APIs.
private void injectInputEvent(KeyEvent event) {
try {
getInjectInputEvent().invoke(getInputManager(), event, 2);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
}
private static Method getInjectInputEvent() throws NoSuchMethodException {
Class<InputManager> cl = InputManager.class;
Method method = cl.getDeclaredMethod("injectInputEvent", InputEvent.class, int.class);
method.setAccessible(true);
return method;
}
private static InputManager getInputManager() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<InputManager> cl = InputManager.class;
Method method = cl.getDeclaredMethod("getInstance");
method.setAccessible(true);
return (InputManager) method.invoke(cl);
}
injectInputEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
injectInputEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
Please note that method 1 is a clean solution based on public API and internally it uses the same calls from method 2.
Also note that neither of this two methods can be invoked from the MainThread.

vaadin, getting null pointer when trying to add item to sqlContainer

I'm very new to vaadin ( and to java).
i have an table that has an SQLcontainer like so :
public class ProjectTable extends Table {
public ProjectTable(final DocumentmanagerApplication app) {
setSizeFull();
setContainerDataSource(app.getDbHelp().getProjectContainer());
setImmediate(true);
commit();
setSelectable(true);
}
}
i have a button and a TextField , to fill data in the table
public void buttonClick(ClickEvent event)
{
SQLContainer cont = h.getAssetContainer();
String dataResult = tf.getValue().toString(); // TEXT FIELD
System.out.println(dataResult);
Object itemId = cont.addItem(); // cont is the container
**cont.getContainerProperty(itemId , "id").setValue(dataResult); // BUG IS HERE !!! **
try {
cont.commit();
} catch (UnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i keep getting a " null pointer exception" no matter what i do. on the line **cont.getContainerProperty(itemId , "id").setValue(dataResult);
am i doing anything wrong ? and what is null pointer ?
please inform me if anything was unclear.
please help , thanks in advance.
BTW, if you have a Vaadin Table and you applied a Filter to it, you need to remove it before, if not probably you will get a null pointer exception in the getContainerProperty(itemId, property) method
This expression returns null:
cont.getContainerProperty(itemId , "id")
And then you try to invoke a method on null. This causes the NullPointerException. So have a look, why the container does not provide a non-null value for the key at the time you invoke it.

Hibernate transaction end example

This is a very simple example of hibernate usage in java: a function that when it's called, it creates a new object in the database. If everything goes fine, the changes are stored and visible immediately (no cache issues). If something fails, the database should be restored as if this function was never called.
public String createObject() {
PersistentTransaction t = null;
try {
t = PersistentManager.instance().getSession().beginTransaction();
Foods f = new Foods(); //Foods is an Hibernate object
//set some values on f
f.save();
t.commit();
PersistentManager.instance().getSession().clear();
return "everything allright";
} catch (Exception e) {
System.out.println("Error while creating object");
e.printStackTrace();
try {
t.rollback();
System.out.println("Database restored after the error.");
} catch (Exception e1) {
System.out.println("Error restoring database!");
e1.printStackTrace();
}
}
return "there was an error";
}
Is there any error? Would you change / improve anything?
I don't see anything wrong with your code here. As #Vinod has mentioned, we rely on frameworks like Spring to handle the tedious boiler plate code. After all, you don't want code like this to exist in every possible DAO method you have. They makes things difficult to read and debug.
One option is to use AOP where you apply AspectJ's "around" advice on your DAO method to handle the transaction. If you don't feel comfortable with AOP, then you can write your own boiler plate wrapper if you are not using frameworks like Spring.
Here's an example that I crafted up that might give you an idea:-
// think of this as an anonymous block of code you want to wrap with transaction
public abstract class CodeBlock {
public abstract void execute();
}
// wraps transaction around the CodeBlock
public class TransactionWrapper {
public boolean run(CodeBlock codeBlock) {
PersistentTransaction t = null;
boolean status = false;
try {
t = PersistentManager.instance().getSession().beginTransaction();
codeBlock.execute();
t.commit();
status = true;
}
catch (Exception e) {
e.printStackTrace();
try {
t.rollback();
}
catch (Exception ignored) {
}
}
finally {
// close session
}
return status;
}
}
Then, your actual DAO method will look like this:-
TransactionWrapper transactionWrapper = new TransactionWrapper();
public String createObject() {
boolean status = transactionWrapper.run(new CodeBlock() {
#Override
public void execute() {
Foods f = new Foods();
f.save();
}
});
return status ? "everything allright" : "there was an error";
}
The save will be through a session rather than on the object unless you have injected the session into persistent object.
Have a finally and do a session close also
finally {
//session.close()
}
Suggestion: If this code posted was for learning purpose then it is fine, otherwise I would suggest using Spring to manage this boiler plate stuff and worry only about save.

Categories

Resources