Skip to main content

Improve your REST Webservice response time using java.util.TimerTask

A while ago, I built an MAF application, which was consuming a few REST webservices from Oracle Java Cloud. But for each request from the app, the response JSON was getting created, and which made the app response very slow. 
So, I created the contents of the REST response as a scheduled job. My data wasn't getting changed that often, so I choose to build my REST responses every morning at 10am using java.util.TimerTask.

Used Software: JDeveloper 12.1.3

#1. REST response POJOs :
public class Feed {
   
    public String url;
    public String source;
   
    public Feed() {
        super();
    }
   
    public Feed(String source, String url) {
        setSource(source);
        setUrl(url);
    }
   
    public void setSource(String source) {
        this.source = source;
    }

    public String getSource() {
        return source;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }
}


================================

@XmlRootElement(name = "feeds")
public class FeedsArray {

    private List<Feed> feeds;

    public void setFeeds(List<Feed> feeds) {
        this.feeds = feeds;
    }

    public List<Feed> getFeeds() {
        return feeds;
    }
}


#2. TimerTask class :
You need to create a class which extends java.util.TimerTask and override run() to put your custom code.
I have used a Singleton object (Feeds) to create and store my response.

public class FeedRSSScheduler extends TimerTask {
    public FeedRSSScheduler() {
        super();
    }

    @Override
    public void run() {
        Feeds.getInstance().buildFeedsMap();
    }
}


============================

public class Feeds {
   
    private static Feeds instance = null;
   
    private FeedsArray feedsArray;
   
    protected Feeds() {
        super();
    }
   
    public static Feeds getInstance() {
      if(instance == null) {
         instance = new Feeds();
      }
      return instance;
    }


    public FeedsArray getFeedsArray() {
        if(feedsArray == null) {
            buildFeedsMap();
        }
        return feedsArray;
    }
   
    public void buildFeedsMap() {
        // PUT your custom code here to populate the FeedsArray object

    }
}


#3. Servlet container class :
 
public class JobSchedulerServlet extends ServletContainer {
   
    private final static long ONCE_PER_DAY = 1000*60*60*24;
    private final static int TEN_AM = 10;
    private final static int ZERO_MINUTES = 0;
   
    public JobSchedulerServlet(Application application) {
        super(application);
    }

    @Override
    public void init() throws ServletException {   
        startFeedRSSTask();
        super.init();
    }

    public JobSchedulerServlet(Class<? extends Application> class1) {
        super(class1);
    }

    public JobSchedulerServlet() {
        super();
    }
   
    private Date getTomorrowMorning10AM(){
        Date date2am = new Date();
        date2am.setHours(TEN_AM);
        date2am.setMinutes(ZERO_MINUTES);
        return date2am;
    }
   
    private void startFeedRSSTask(){
        FeedRSSScheduler feedRSSScheduler = new FeedRSSScheduler();
        Timer timer = new Timer(); 
        timer.schedule(feedRSSScheduler, getTomorrowMorning10AM(), ONCE_PER_DAY);
    }
}


#4. Register your Servlet container class in web.xml :
  <servlet>
    <servlet-name>jersey</servlet-name>
    <servlet-class>rest.scheduler.JobSchedulerServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>jersey</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>


#5. Create REST service :

@Path("/feeds")
public class FeedMap {
   
    @GET
    @Path("/sources")
    @Produces(MediaType.APPLICATION_JSON)
    public FeedsArray getFeedsMap() {
        return Feeds.getInstance().getFeedsArray();
    }
}

/// URL to access this service : http://<server>:<port>/<context_root>/feeds/sources

That's it. When you create and deploy this WAR file, the job will start instantly and then every day morning at 10am.

Comments

  1. TimerTask is old approach, use ScheduledThreadPoolExecutor

    ReplyDelete
  2. Amazing Article, thank you!. I am very glad to read your informative & practical blog. Kindly keep updating your blog.
    Java Developer is a wonderful career for IT students.To start Dream Career to become a Java developer learn from
    Java Training in Chennai
    . or learn thru Java Online Training from India .

    ReplyDelete

Post a Comment

Popular posts from this blog

Secure your Node/Express REST APIs using Passport JS

Recently I have been involved in various discussions on how to make the REST APIs as secure as SOAP.
First of all, let me start with a very basic statement, about security, it doesn't depend on your Webservice type, be it REST or SOAP, your design decisions depicts whether they can be made secure or not.
In this example blog, I will use "Micro CRUD services for Oracle Database Cloud" APIs and implement (read attach) Passport's "local" authentication strategy, to make them secure.

Code in Github : LeasifyAPIs with Passport

What is Passport JS? (from Documentation)

Passport is authentication middleware for Node. It is designed to serve a singular purpose: authenticate requests. When writing modules, encapsulation is a virtue, so Passport delegates all other functionality to the application. This separation of concerns keeps code clean and maintainable, and makes Passport extremely easy to integrate into an application.

What are "strategies" in P…

Chatbots and Oracle Cloud Services

Thanks to Oracle A-Team, I had a chance to work with Chatbots.
3 pure NodeJS applications, on couple of Oracle Cloud platforms and Facebook messenger, and my chatbot was running.

Let me explain, the architecture a bit. To start with, following is the simple representation of how it works.

ADF Utility : Find UIComponent from Managed Bean

Many a times, it is required to find an UIComponent from ADF managed bean, to do something with it, for example : change the value of an af:outputText, change readOnly property of an af:inputText etc.

private UIComponent getUIComponent(String id) { 

        FacesContext facesCtx = FacesContext.getCurrentInstance(); 
        return findComponent(facesCtx.getViewRoot(), id);
    } 

    private UIComponent findComponent(UIComponent base, String id) {

        if (id.equals(base.getId())) {
            return base;
        }

        UIComponent children = null;
        UIComponent result = null;
        Iterator childrens = base.getFacetsAndChildren();
        while (childrens.hasNext() && (result == null)) {
            children = (UIComponent)childrens.next();
            if (id.equals(children.getId())) {
                result = children;
                break;
            }
            result = findComponent(children, id);
            if (result != null) {
                break;
            }
  …