Liferay Service for Business Logics - liferay

I want to clear one doubt. I am creating my own service class to manipulate data. Should i create this service instance at class level(in MVCPortlet) or create new instance in my processAction/doView method.
Is there is any issue of thread safety while using instance level.
Fg:
public class MvcCycle extends MVCPortlet {
int counter;
LdapService ldapservice;
#Override
public void init() throws PortletException {
counter=0;
ldapservice = new LdapService(); // Option 1
super.init();
}
#Override
public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
// TODO Auto-generated method stub
System.out.println("Counter hits "+ ++counter);
//
LdapService ldapservice = new LdapService(); // Option 2
ldapservice.authUser(request.getParameter("email"));
// -- some code--
super.doView(renderRequest, renderResponse);
}
#Override
public void destroy() {
System.out.println("Last counter "+counter);
counter=0;
super.destroy();
}
}
class LdapService{
public boolean authUser(String email){
if(//logic to authenticate user){
return true;
}else{
return false;
}
}
}
Here, my ldapservice initiate only once. So when multiple hits come. which code is beneficial on this time either Option1 or Option 2.
Hope i have cleared my problem.

Following up on your comment: in general: it depends. We don't have enough information to give you blank architectural recommendations.
In the context of Liferay it could make sense to utilize service builder, even if you don't have database interaction. Just create an empty entity, you'll have a service with no persistence.
<entity name="MyService" local="true"/>
That's it. Now implement MyServiceLocalServiceImpl added you're done
Edit, after your clarification: it doesn't make a difference. I'd still recommend to not instantiate at all in your portlet, because that makes your portlet dependent on the service implementation. E.g. I still go with service builder.
You're also asking about thread safety and that depends on your implementation as well. Your sample code is thread safe, but the actual code might not be. Your judgement.

Related

Override declarative transactional methods with programmatic transactional code in Spring

I am trying to override the transactional behaviour for a service method(someService.updateSomething() in the example) annotated with #Transactional annotation in Spring. To do so, from other class, I am using programmatic transactional code like the next:
#Service
public class MyServiceClass {
private TransactionTemplate transactionTemplate;
public MyClass (PlatformTransactionManager transactionManager) {
transactionTemplate = new TransactionTemplate(transactionManager);
}
#Transactional
public void someMethod(){
transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status){
try{
someService.updateSomething();
}catch(Exception e){
LOGGER.error("Error has ocurred");
}
}
});
}
}
My problem is that someService.updateSomething() does not run in a new Transaction and I dont understand why. So:
If I call a proxied service method with transactional behaviour like someService.updateSomething() but in the call I create a new transaction like in the example, when the code hits to the proxied method, it will take the new transaction created and not the transaction already running for the someMethod() method, right?
Thanks!

Allow only one user to access a page at a time in struts application

Having an huge customers profile page if two or more users start using same page and start editing big change will happen in my database so planing to implement Threads concept where only one user can use that customer page
i'm aware about threads concept but confused how to implement it
hope i need to use Singleton class as well
Any suggestion or Logic's will be helpful
I'm using Struts,Hibernate frame work
You may use application context to store a flag variable. Action will use its value to allow only one simultaneous execution.
public class TestAction extends ActionSupport implements ApplicationAware {
private static final String APP_BUSY_KEY = "APP_BUSY";
Map<String, Object> map;
#Override
public void setApplication(Map<String, Object> map) {
this.map = map;
}
#Override
public String execute() throws Exception {
if (map.containsKey(APP_BUSY_KEY)) {
return ERROR;
} else {
map.put(APP_BUSY_KEY, "1");
try {
// action logic here
} finally {
map.remove(APP_BUSY_KEY);
}
return SUCCESS;
}
}
}
If you plan to implement similar logic for two requests (lock after displaying values and release lock after submitting new values) then logic will be more complex and you will also need to handle lock release after timeout.

Android: "Application level" Pause and Resume [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I've been trying to get Application Level Pause and Resume similar to an activity's onPause and onResume. I know there's no API that has this functionality.
I try to follow this post: http://curioustechizen.blogspot.com/2012/12/android-application-level-pause-and.html
But I've had no luck so far.
Has anyone been able to achieve this? What paradigm did you use?
Let me know if you need me to paste some code into this question.
Thanks for the help
Another solution to the problem would be to just keep track of the count of onStart() and onStop() calls from every activity. Example:
First, create a class to hold the counts:
public class ActiveActivitiesTracker {
private static int sActiveActivities = 0;
public static void activityStarted()
{
if( sActiveActivities == 0 )
{
// TODO: Here is presumably "application level" resume
}
sActiveActivities++;
}
public static void activityStopped()
{
sActiveActivities--;
if( sActiveActivities == 0 )
{
// TODO: Here is presumably "application level" pause
}
}
}
Then in every activity, simply call the activityStarted() and activityStopped() methods:
#Override
public void onStart() {
super.onStart();
ActiveActivitiesTracker.activityStarted();
}
#Override
public void onStop() {
super.onStop();
ActiveActivitiesTracker.activityStopped();
}
I had the same problem. My aim was to lock the App, if the user abandons it. A simple aim, which i thought would be easy to implement. But all the solutions I found were way to complex. So I came to a simple solution: A time based lock.
Basically it works like this:
Start countdown to lock app in onPause
Stop countdown in onResume
If onResume is not called in time, change to locked
Therefor I created a small little class:
public class ApplicationLock {
private static final String TAG = ApplicationLock.class.getSimpleName();
private static final int LOCK_TIME = 1000; //lock after a second
private static boolean lock = true; //default is locked
private static Handler handler = new Handler();
private static Runnable runnable = new Runnable() {
#Override
public void run() {
lock = true;
Log.i("ActivityTracker", "App locked");
}
};
public static boolean activityStarted()
{
handler.removeCallbacks(runnable);
if(lock)
{
Log.i(TAG, "App resumed - LOCKED");
return true;
}else{
Log.i(TAG, "App resumed - NOT LOCKED");
return false;
}
}
public static void activityStopped()
{
handler.postDelayed(runnable, LOCK_TIME);
Log.i(TAG, "App paused - Starting countdown");
}
Just call activityStopped() in your activities onPause() and activityStarted() in onResume(). Check the result of activityStarted(). If it returns true, lock your app. If the orientation of the app is changed, onResume will be called very quickly after onPause, so the app will not lock.
This solution might not fit every scenario, but in my case it was the best solution. Additionally you can change the countdown, to increase the user experience (The user pressed a wrong button and returns to the app in a few seconds, no need to lock the app). Hope this is useful to someone else.
I have done something very similar to this in an app which used a service that provided GPS functions by several activities. The idea was to only have the service there when one of the activities that used it is visible, and not there when none are visible. In your case, every activity would hook into a service, and you will know when the entire application was paused or resumed by hooking into the service's onCreate() and onDestroy() methods.
Here is a stripped-down example:
Components needed (these could probably be placed into a utility class if you want to reuse them, or I just had them for each activity class):
private boolean mAppActiveServiceBound = false;
private AppActiveService mAppActiveService = null;
private ServiceConnection mAppActiveConnection = new ServiceConnection() {
public void onServiceConnected( ComponentName className, IBinder service ) {
mAppActiveService = ( (AppActiveService.AppActiveBinder) service ).getService();
}
public void onServiceDisconnected( ComponentName className ) {
mAppActiveService = null;
}
};
Then in your onStart() and onStop() methods for each activity:
#Override
public void onStart() {
super.onStart();
mAppActiveServiceBound = bindService( new Intent( this, AppActiveService.class ), mAppActiveConnection, Context.BIND_AUTO_CREATE );
}
#Override
public void onStop() {
super.onStop();
if( mAppActiveServiceBound ) {
unbindService( mAppActiveConnection );
mAppActiveServiceBound = false;
}
}
And finally, the service itself:
public class AppActiveService extends Service {
// Receives interactions from clients:
private final IBinder mBinder = new AppActiveBinder();
/**
* Provides a handle to the bound service.
*/
public class AppActiveBinder extends Binder {
AppActiveService getService() {
return AppActiveService.this;
}
}
#Override
public void onCreate(){
// TODO: Here is presumably "application level" resume
}
#Override
public void onDestroy(){
// TODO: Here is presumably "application level" pause
}
}

Update UI while working on background

I have an update database operation, that has an activity, which keeps updating the percentage and it runs inside an AsyncTask.
Inside doInBackground() I call the controller that updates the database and keep updating the percentage on the activity, however, if I press home button or back button, the operation is cancelled. What u suggest me to do?
I was trying to start a Service inside doInBackground() so it would run in background, but it looks like its not working.
My code looks like this:
public class UpdateDatabaseAsyncTask extends AsyncTask<Void, Integer, Integer>
{
#Override
public void onPreExecute()
{
mCustomProgressBar.startAnimation();
}
#Override
public Integer doInBackground(Void... params)
{
return mController.updateDatabase();
}
#Override
public void onPostExecute(Integer result)
{
mCustomProgressBar.stopAnimation();
// finish the activity
}
#Override
public void onProgressUpdate(Integer... value)
{
updatePercentageValue(value[0]);
}
public void callPublishProgress(Integer value)
{
publishProgress(value);
}
}
And inside the controller I call the method callPublishProgress(value) passing the current percentage value, so it will publishProgress(value) in the UI.
I was debugging, and I pressed the home/back button, and it just stopped running the worker thread.
Another solution I tried, was starting a Service to run in background no matter the user press home/back button or not, so I thought, and the Service would make a call to the controller method that does the work, and it would call the callPublishProgress(value) to update the percentage value on the UI anyways.
However, what was happening is, the code reach doInBackground() and start the service, but it goes to onPostExecute() immediately, it just didn't wait the service to finish(of course!). So it gives a NullPointerException. I thought of making a loop inside doInBackground() with a flag set in the Service, so it would leave this loop while the service hasn't been finished (I was using an IntentService), but it didn't work anyways.
I thought of using a Timer too. But I don't know.
I was reading the articles in documentation about Threads, etc. And it suggests using AsyncTask, just as I was trying to do. It also talks about runOnUiThread(Runnable).
Anyways what I need is to make an operation in background(probably using an IntentService), so no matter if the user press the home button, it will keep running, but it must update the percentage on the UI, and when the user leave the screen and back to it, it shows the current percentage value updated in the screen.
What is the best solution for my case?
Thanks.
public class MyServce extends Service{
public static final String BROADCAST_ACTION = "com.myapp";
Intent intent;
private final Handler handler = new Handler();
#Override
public void onCreate()
{
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DoYourWorking();
handler.postDelayed(this, 1000); // 1 seconds
}
private void DoYourWorking() {
........
........
intent.putExtra("key", progress);
sendBroadcast(intent);
}
};
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendUpdatesToUI);
}
Now in your Activity register broadcast to service
private BroadcastReceiver brodcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//intent.getWhatever
// update your progress
//progressbar.setProgress
}
register broadcast
registerReceiver(brodcast, new IntentFilter(MyService.BROADCAST_ACTION));
This worked for me. I started a background service on a thread that just fetches the values and updates an object in a singleton.
In the view controller, I start a timer that keeps updating the view by fetching data from the object in singleton.
I had a little problem understanding your entire question text, so I'm not sure if you have tried this. But this is what worked. Also, the service was started with START_STICKY
Use an IntentService (which is a Service on a thread of its own), and Handler to pass the data back to the Activity.

How to save all FacesMessages over different requests

I was just wondering to implement a kind of log display to user where in all messages in the application are displayed to user all the time.
Since I use JSF 1.2 and RF 3.3.3, wanted to know if it is possible to save all messages be it added by different requests and display them to user, so that user will know the history of actions he has done. It is also useful for support team to analyse the cause of the problem and he can send the messages to developer if it needs to simulated or to debug purpose also.
I also know facesmessages get cleared over different requests, thats where my question lies, to save messages over different requests :)
Could be handled in different ways by saving them is a session variable or so...I would appreciate all possible answers
You could collect all messages during the render response in a PhaseListener. E.g.
public class MessagesListener implements PhaseListener {
#Override
public PhaseId getPhaseId() {
return PhaseId.RENDER_RESPONSE;
}
#Override
public void beforePhase(PhaseEvent event) {
FacesContext context = event.getFacesContext();
Iterator<String> clientIds = context.getClientIdsWithMessages();
while (clientIds.hasNext()) {
String clientId = clientIds.next();
Iterator<FacesMessage> messages = context.getMessages(clientId);
while (messages.hasNext()) {
FacesMessage message = messages.next();
save(clientId, message); // Do your job here.
}
}
}
#Override
public void afterPhase(PhaseEvent event) {
// NOOP.
}
}
To get it to run, register it as follows in faces-config.xml:
<lifecycle>
<phase-listener>com.example.MessagesListener</phase-listener>
</lifecycle>

Resources