AEM6.2 sling models | Resource resolver is already closed

Avatar

Avatar

pradeepdubey82

Avatar

pradeepdubey82

pradeepdubey82

18-03-2018

Hi All,

I am  getting error in  sing model class saying resource resolver is already closed

Below is my code for reference.

@Model(adaptables = Resource.class)

public class SchedulerComponent {

private static Logger LOG = LoggerFactory.getLogger(SchedulerComponent.class);

@Inject

    private Date timer;

@Inject

private ResourceResolver resourceResolver;

@PostConstruct

public final void init() {

try {

     Session session = resourceResolver.adaptTo(Session.class);

} catch(Exception ex) {

}

}

}

Below is error stack trace.

java.lang.IllegalStateException: Resource resolver is already closed.

at org.apache.sling.resourceresolver.impl.ResourceResolverImpl.checkClosed(ResourceResolverImpl.java:202)

at org.apache.sling.resourceresolver.impl.ResourceResolverImpl.adaptTo(ResourceResolverImpl.java:826)

at com.test.core.models.SchedulerComponent$MyTimeTask.run(SchedulerComponent.java:69)

at java.util.TimerThread.mainLoop(Unknown Source)

at java.util.TimerThread.run(Unknown Source)

Please advise to fix the problem.

Thanks,

Pradeep

View Entire Topic

Avatar

Avatar

pradeepdubey82

Avatar

pradeepdubey82

pradeepdubey82

19-03-2018

Hi Jorg,

Please find the full class code below

package com.test.core.models;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

import java.nio.charset.Charset;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

import javax.annotation.PostConstruct;

import javax.inject.Inject;

import javax.jcr.Node;

import javax.jcr.RepositoryException;

import javax.jcr.Session;

import org.apache.sling.api.resource.Resource;

import org.apache.sling.api.resource.ResourceResolver;

import org.apache.sling.models.annotations.Model;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

@Model(adaptables = Resource.class)

public class SchedulerComponent {

private static Logger LOG = LoggerFactory.getLogger(SchedulerComponent.class);

@Inject

    private Date timer;

@Inject

private ResourceResolver resourceResolver;

/*@Inject

    private String classification;

*/

/*@Inject

private ResourceResolver resourceResolver;

*/

/*@Inject

private Session session;

*/

 

static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

private boolean taskOver;

public boolean isTaskOver() {

return taskOver;

}

Timer timer1 = new Timer();

   private class MyTimeTask extends TimerTask {

   private ResourceResolver resourceResolver;

  

   public MyTimeTask(ResourceResolver resourceResolver) {

   this.resourceResolver = resourceResolver;

}

      public void run() {

      try {

      /*Map<String, Object> param = new HashMap<String, Object>();

      param.put(ResourceResolverFactory.SUBSERVICE, "ReadService");

      ResourceResolver resolver = null;

      resolver = resolverFactory.getServiceResourceResolver(param);

      */Session session = resourceResolver.adaptTo(Session.class);

      LOG.info("Entering to run method");

// write custom code  here

      LOG.info("0000000");

      String classification = "english";

      Node classificationNode = session.getNode("/content/myapp/api-data/"+classification);

      LOG.info("111111");

     

  //System.setProperty("https.proxyHost", "proxy.global.dish.com");

  //System.setProperty("https.proxyPort", "8080");

  URL url = new URL("https://teamtreehouse.com/matthew.json");

      LOG.info("2222222");

  URLConnection con = url.openConnection();

  LOG.info("connection opened");

  BufferedReader br  = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8")));

  StringBuilder sb = new StringBuilder();

  String line;

  while ((line = br.readLine()) != null) {

  sb.append(line);

  }

  System.out.println(sb.toString());

 

  Node fileNode = classificationNode.addNode("twelve-month-pre-pay", "nt:file");

  fileNode.setProperty("jcr:date", sb.toString());

  session.save();

  LOG.info("Original data saved in repository");

  /*

  File jsonFile = new File("api-call-hindi.json");

  BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(jsonFile));

 

  // Read json content from repository 

String content = new String(Files.readAllBytes(Paths.get("api-call.json")));

LOG.info("Content is ::: "+content);

JSONObject apiJson =  new JSONObject(content);

JSONArray base_linear_packages = apiJson.getJSONArray("base_linear_packages");

for(int i=0; i< base_linear_packages.length(); i++) {

JSONObject base_linear_package = base_linear_packages.getJSONObject(i);

// assuming all channels are present in  classification_name:Hindi identifier:hindi-gold

if(base_linear_package.get("classification_name").equals("Hindi") && base_linear_package.get("identifier").equals("hindi-gold")) {

JSONArray channels = base_linear_package.getJSONArray("channels");

File channelsFile = new File("channels.json");

BufferedWriter channelsWriter = new BufferedWriter(new FileWriter(channelsFile));

ObjectMapper mapper1 = new ObjectMapper();

Object jsonObject1 = mapper.readValue(channels.toString(), Object.class);

String prettyString1 = mapper1.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject1);

channelsWriter.write(prettyString1);

System.out.println("Channles written!!!");

channelsWriter.close();

break;

}

}*/

LOG.info("Running Task");

LOG.info("Current Time: " + df.format( new Date()));

timer1.cancel();

taskOver = true;

} catch (RepositoryException e) {

LOG.info("RepositoryException is :::: ", e);

} catch (MalformedURLException e) {

LOG.info("MalformedURLException is :::: ", e);

} catch (IOException e) {

e.printStackTrace();

} catch(Exception e) {

LOG.info("Exception is :::: ", e);

}

      }

   }

@PostConstruct

public final void init() {

try {

LOG.info("Time is :::: "+timer);

SimpleDateFormat inFormat = new  SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

LOG.info("Right format is :::: "+outFormat.format(timer));

LOG.info("Current Time: " + df.format( new Date()));

            //Date and time at which you want to execute

//Date date = df.parse("2018-03-18 17:08:00");

MyTimeTask task = new MyTimeTask(resourceResolver);

timer1.schedule(task, timer);

} catch(Exception ex) {

LOG.error("Error in init :::: ", ex);

}

}

}