How to run/manage container background thread in Java EE 7+? - javabeans

Similar to Background Thread for a Tomcat servlet app but I'm looking for a Java EE 7 specific solution.

This is what I finally came up with for WildFly 11 (Java EE 7) without using any configuration changes/additions to beans.xml/web.xml:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.enterprise.concurrent.ManagedThreadFactory;
#Startup
#Singleton
public class IndexingTask implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(IndexingTask.class);
private Thread taskThread = null;
private final CountDownLatch shutdownLatch = new CountDownLatch(1);
#Resource
private ManagedThreadFactory threadFactory;
#PostConstruct
public void postConstruct() {
taskThread = threadFactory.newThread(this);
taskThread.start();
}
#PreDestroy
public void preDestroy(){
shutdownLatch.countDown();
try {
taskThread.join();
} catch (InterruptedException ex) {
LOG.warn("interrupted while waiting for " + taskThread + " to shut down", ex);
}
}
#Override
public void run() {
LOG.info("started");
try {
while (!shutdownLatch.await(100, TimeUnit.MILLISECONDS)) {
}
} catch (InterruptedException ex) {
LOG.warn("", ex);
}
LOG.info("stopped");
}
}
https://javagc.leponceau.org/2017/10/how-to-runmanage-container-background.html
See also Java EE 7 containers: initialize bean at startup without adding it to beans.xml?

Related

ExtentTest class throws null pointer error

Scope(This is what i want to do): Hey looking for to attached screenshot in my extent report file.
Problem: so now i have used the ExtentTest class in BaseClass file. but when i run my testsuit from testNG.xml file, it give me an below error.
java.lang.NullPointerException: Cannot invoke "org.testng.ITestResult.getStatus()" because "com.example.PageClass.BaseClass.result" is null
Here is my Code in BaseClass.
package com.example.PageClass;
import com.example.Utils.Utilities;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.ITestResult;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.Duration;
import java.util.Properties;
public class BaseClass {
public static WebDriver driver;
public static Properties prop;
public static LoginPage loginPage;
public static ExtentTest extentTest;
public static ITestResult result;
public static void properties() {
try {
FileInputStream fis = new FileInputStream("src/main/resources/generic.properties");
prop = new Properties();
prop.load(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setDriver() {
properties();
if (prop.getProperty("browser").contains("chrome")) {
System.setProperty("webdriver.chrome.driver", prop.getProperty("driverPath"));
driver = new ChromeDriver();
} else {
// FirefoxDriverManager.firefoxdriver().setup();
// driver = new FirefoxDriver();
}
driver.get(prop.getProperty("url"));
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(60));
driver.manage().window().maximize();
loginPage = PageFactory.initElements(driver, LoginPage.class);
}
public static void closeDriver() throws IOException {
if (result.getStatus() == ITestResult.FAILURE) {
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS " + result.getName()); //to add name in extent report
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS " + result.getThrowable()); //to add error/exception in extent report
String screenshotPath = null;
try {
screenshotPath = Utilities.getUtilities().getScreenshot(driver, "firstScreenShot");
} catch (IOException e) {
throw new RuntimeException(e);
}
extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath)); //to add screenshot in extent report
extentTest.log(LogStatus.PASS, extentTest.addScreenCapture(screenshotPath)); //to add screenshot in extent report
}
driver.quit();
}
}
code inside StepsDef file:
package com.example.StepDefinitions;
import com.example.PageClass.BaseClass;
import com.example.Utils.Utilities;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.annotations.*;
import java.io.IOException;
public class LoginStepDefs extends BaseClass implements ITestListener {
#Before
public void setup(){
setDriver();
}
#After
public void teardown() throws IOException {
closeDriver();
}
#Then("I go to OrangeHRM Home page.")
public void iGoToOrangeHomePage() {
try {
loginPage.getOrangeHRMHome();
} catch (Exception e) {
System.out.println("Username not sent.");
}
}
#When("I enter {string} username and {string} password.")
public void iEnterUsernameAndPassword(String arg0, String arg1) {
try {
loginPage.systemLogin(arg0,arg1);
} catch (Exception e) {
System.out.println("Username not sent.");
}
}
#When("I enter username and password.")
public void iEnterUsernameAndPassword() {
try {
loginPage.systemLogin("Admin","admin123");
} catch (Exception e) {
System.out.println("Username not sent.");
}
}
#And("I navigate to PIM tab and click on add employee.")
public void iNavigateToPIMTabAndClickOnAddEmployee() {
try {
loginPage.clickOnPIM().clickOnAddEmployee();
} catch (Exception e) {
System.out.println("Username not navigate to add employee tab.");
}
}
#And("I enter employee details and save it.")
public void iEnterEmployeeDetailsAndSaveIt() {
try {
loginPage.enterFirstNameAndLastName().fileUpload().checkBoxCreateLoginDetail().enterLoginDetail().verifySuccessMessage().verifySuccessMessageForAdd();
} catch (Exception e) {
System.out.println("Username not navigate to add employee tab.");
}
}
My Folder Structure:
Can Anyone please help me out in this?

TomEE websocket behind an httpd proxy connection timeout

In development I have a javascript websocket connecting directly to TomEE and the websocket stays connected with no problems.
In production with TomEE behind an httpd proxy the connection times out after about 30 seconds.
Here is the relevant part of the virtual host config
ProxyPass / ajp://127.0.0.1:8009/ secret=xxxxxxxxxxxx
RewriteEngine on
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteCond %{HTTP:Connection} upgrade [NC]
RewriteRule ^/?(.*) "ws://127.0.0.1:8080/$1" [P,L]
I have tried using the reconnecting-websocket npm library but it seems to keep spawning websockets until chrome runs out of memory. The original websockets remain with status 101 rather that changing to finished.
I did read that the firewall can cause it to disconnect but I searched for firewalld and websocket and couldn't find anything
It looks like the answer is to implement "ping pong". This prevents the firewall or proxy from terminating the connection.
If you ping a websocket (client or server) then the specification says it has to respond (pong). But Javascript websocket depends on the browser implementation so it is best to implement a 30 second ping on the server to all clients. e.g.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.PongMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint(value = "/websockets/admin/autoreply")
public class MyWebSocket {
private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
private static final Set<String> alive = Collections.synchronizedSet(new HashSet<String>());
#OnOpen
public void onOpen(Session session) throws IOException {
sessions.add(session);
alive.add(session.getId());
}
#OnMessage
public void onMessage(Session session, String string) throws IOException {
// broadcast(string);
}
#OnMessage
public void onPong(Session session, PongMessage pongMessage) throws IOException {
// System.out.println("pong");
alive.add(session.getId());
}
#OnClose
public void onClose(Session session) throws IOException {
sessions.remove(session);
}
#OnError
public void onError(Session session, Throwable throwable) {
// Do error handling here
}
public void broadcast(String string) {
synchronized (sessions) {
for (Session session : sessions) {
broadcast(session, string);
}
}
}
private void broadcast(Session session, String string) {
try {
session.getBasicRemote().sendText(string);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void ping() {
synchronized (sessions) {
for (Session session : sessions) {
ping(session);
}
}
}
private void ping(Session session) {
try {
synchronized (alive) {
if (alive.contains(session.getId())) {
String data = "Ping";
ByteBuffer payload = ByteBuffer.wrap(data.getBytes());
session.getBasicRemote().sendPing(payload);
alive.remove(session.getId());
} else {
session.close();
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
and the timer service looks like this
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import org.apache.tomcat.websocket.server.DefaultServerEndpointConfigurator;
import tld.domain.api.websockets.MyWebSocket;
#Singleton
#Lock(LockType.READ)
#Startup
public class HeartbeatTimer {
#Resource
private TimerService timerService;
#PostConstruct
private void construct() {
final TimerConfig heartbeat = new TimerConfig("heartbeat", false);
timerService.createCalendarTimer(new ScheduleExpression().second("*/30").minute("*").hour("*"), heartbeat);
}
#Timeout
public void timeout(Timer timer) {
if ("heartbeat".equals(timer.getInfo())) {
// System.out.println("Pinging...");
try {
DefaultServerEndpointConfigurator dsec = new DefaultServerEndpointConfigurator();
MyWebSocket ws = dsec.getEndpointInstance(MyWebSocket.class);
ws.ping();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
}

Unable to Configure Log4j2 using java.util.Properties

I am unable to configure log4j2 with java.util.properties. I always get this message "tatusLogger No Log4j 2 configuration file found". Please see my logger class. I am reading the log4j2 properties from two files.
I will be attaching my code to this post.
package my.common.logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory;
import org.apache.logging.log4j.util.PropertiesUtil;
public class MyLogger {
private static boolean configured = false;
private static Logger logger;
static {
System.setProperty("log4j.configurationFactory", "my.common.logger.JCFLog4JConfigurationFactory");
}
private static void readConfiguration() throws Exception {
LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
Configuration configuration = ConfigurationFactory.getInstance().getConfiguration(context, createConfigurationSource());
configuration.start();
Configurator.reconfigure();
configured = true;
}
public static Logger getLogger(String className) {
try {
if (!configured) readConfiguration();
return org.apache.log4j.LogManager.getLogger(className);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static ConfigurationSource createConfigurationSource()
{ Properties p = new Properties();
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = null;
try {
p.putAll(<Read from File 1>);
p.putAll(<Read from File 2>);
p.store(out, null);
} catch (IOException e) {
e.printStackTrace();
}
in = new ByteArrayInputStream(out.toByteArray());
ConfigurationSource configSrc = null;
try {
configSrc = new ConfigurationSource(in);
}
catch (IOException i)
{
i.printStackTrace();
}
return configSrc;
}
}
Here is Config Factory Code:
package nj.aoc.ito.cmfw.common.logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory;
public class MyLog4JConfigurationFactory extends ConfigurationFactory {
public MyLog4JConfigurationFactory() {
}
#Override
public Configuration getConfiguration(LoggerContext ctx, ConfigurationSource source) {
PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory();
return factory.getConfiguration(ctx, source);
}
#Override
protected String[] getSupportedTypes() {
return new String[]{".properties", "*"};
}
}
Any idea what I might be doing wrong?
Thanks
Nags

How to use camel type converter to convert exchange data into file object in apahce camel? [duplicate]

I am new to Camel and I am facing an issue while sending files to webservice via camel http.
I have a rest web service which consumes Multipart form data type content and accepts input as part of form data.
When I send file and form parameter via camel it gives me the following error at camel console:
Stacktrace
---------------------------------------------------------------------------------------------------------------------------------------
org.apache.camel.component.http.HttpOperationFailedException: HTTP operation failed invoking http://localhost:8080/JAX_RS_Application/resource/restwb/upload with statusCode: 415
at org.apache.camel.component.http.HttpProducer.populateHttpOperationFailedException(HttpProducer.java:230)
at org.apache.camel.component.http.HttpProducer.process(HttpProducer.java:156)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:129)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:448)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:118)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:80)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:435)
at org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:211)
at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:175)
at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:174)
at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:101)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
The error i get on the server side console is as follows:
SEVERE: MessageBodyReader not found for media type=application/octet-stream, typ
e=class org.glassfish.jersey.media.multipart.FormDataMultiPart, genericType=clas
s org.glassfish.jersey.media.multipart.FormDataMultiPart.
The code snippet of the Rest web-service created via jersey is as follows:
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import org.apache.commons.io.IOUtils;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
#Path("/restwb")
public class FileResource {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(#FormDataParam("username") String username,#FormDataParam("password") String password,#FormDataParam("upload") InputStream is) {
String output ="Hi "+username+" your password is "+password;
output=output+IOUtils.LINE_SEPARATOR +IOUtils.LINE_SEPARATOR;
output=output+"Output :"+IOUtils.LINE_SEPARATOR+"------------------------------------------------------------------------------"+IOUtils.LINE_SEPARATOR;
try {
output=output+IOUtils.toString(is)+IOUtils.LINE_SEPARATOR+IOUtils.LINE_SEPARATOR;
output=output+"==================================================================================================="+IOUtils.LINE_SEPARATOR+IOUtils.LINE_SEPARATOR;
System.out.println("Output :"+output);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return output;
}
}
And my Camel config is as follows:
import org.apache.camel.*;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.Synchronization;
import org.apache.camel.spi.UnitOfWork;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.james.mime4j.message.Multipart;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
/**
* Created by Manish.Pillai on 7/16/2015.
*/
public class LoggingMain {
private static final Logger logger =Logger.getLogger(LoggingMain.class);
public static void main(String[] args) throws Exception{
CamelContext camelContext =new DefaultCamelContext();
try {
camelContext.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:C:\\temp?delay=5000&move=processed&moveFailed=error&antExclude=**/processed/**,**/error/**")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getContext().getTypeConverterRegistry().addTypeConverter(HttpEntity.class,InputStream.class,new InputStreamToHttpEntityConvertor());
exchange.getOut().setBody(exchange.getIn().getBody(),HttpEntity.class);
}
})
.to("http://localhost:8080/JAX_RS_Application/resource/restwb/upload");
}
});
camelContext.getRestConfiguration();
camelContext.start();
Thread.sleep(5000);
camelContext.stop();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
static class InputStreamToHttpEntityConvertor implements TypeConverter {
public boolean allowNull() {
return false;
}
public <T> T convertTo(Class<T> type, Object value) throws TypeConversionException {
Exchange exchange=(Exchange)value;
StringBody username = new StringBody("username", ContentType.MULTIPART_FORM_DATA);
StringBody password = new StringBody("password", ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder multipartEntityBuilder=MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.addPart("upload", new FileBody(exchange.getIn().getBody(File.class), ContentType.MULTIPART_FORM_DATA, (String) exchange.getIn().getHeader(Exchange.FILE_NAME)));
multipartEntityBuilder.addPart("username",username);
multipartEntityBuilder.addPart("password",password);
return (T)multipartEntityBuilder.build();
}
public <T> T convertTo(Class<T> aClass, Exchange exchange, Object o) throws TypeConversionException {
return convertTo(aClass,o);
}
public <T> T mandatoryConvertTo(Class<T> type, Object value) throws TypeConversionException, NoTypeConversionAvailableException {
return convertTo(type,value);
}
public <T> T mandatoryConvertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException, NoTypeConversionAvailableException {
return convertTo(type,value);
}
public <T> T tryConvertTo(Class<T> type, Object value) {
return convertTo(type,value);
}
public <T> T tryConvertTo(Class<T> type, Exchange exchange, Object value) {
return convertTo(type,value);
}
}
}
Any leads would be helpful.
Well, there are several things that can be improved in your code.
First, since you are using a MultipartEntityBuilder, that means you're using Apache's HttpClient version 4.3+, so for best compatibility you should use Camel's HTTP4 component.
Third, in an example as small as this, you don't really need to use the converter, you can do something like this:
public class LoggingMain {
private static final Logger logger = Logger.getLogger(LoggingMain.class);
public static void main(String[] args) throws Exception {
CamelContext camelContext = new DefaultCamelContext();
try {
camelContext.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:C:\\temp?delay=5000&move=processed&moveFailed=error&antExclude=**/processed/**,**/error/**")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
StringBody username = new StringBody("username", ContentType.MULTIPART_FORM_DATA);
StringBody password = new StringBody("password", ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.addPart("username", username);
multipartEntityBuilder.addPart("password", password);
String filename = (String) exchange.getIn().getHeader(Exchange.FILE_NAME);
File file = exchange.getIn().getBody(File.class);
multipartEntityBuilder.addPart("upload", new FileBody(file, ContentType.MULTIPART_FORM_DATA, filename));
exchange.getIn().setBody(multipartEntityBuilder.build());
}
})
.to("http4://localhost:8080/JAX_RS_Application/resource/restwb/upload");
}
});
camelContext.getRestConfiguration();
camelContext.start();
Thread.sleep(5000);
camelContext.stop();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}
I hope this helps!

Singleton Service in weblogic cluster is registering but not invoking activate method

I am implementing a singleton service in a weblogic 12.2.1.2 with EBJ 3.1 in a maven multimodule EAR project.
My singleton service is registering in the cluster.
This is the log from the node where is registered:
<BEA-000189> <The Singleton Service Appscoped_Singleton_Service is now active on this server.>
And this is from other node:
<BEA-003130> <Appscoped_Singleton_Service successfully activated on server iss3.>
The singleton service is implementing the interface weblogic.cluster.singleton.SingletonService but the methods activate and deactivate is not invoked when the nodes starts or shutdown.
I was reading something about versioned EARs and MANIFEST files but not understood this.
I need some help to make methods activate and deactivate be invoked.
This is my class:
import java.io.Serializable;
import javax.inject.Inject;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.test.MyTimerLocal;
import weblogic.cluster.singleton.SingletonService;
public class MySingletonServiceClass implements SingletonService, Serializable, MySingletonServiceInterface {
private static final long serialVersionUID = 3966807367110330202L;
private static final String jndiName = "MySingletonServiceClass";
private int myValue;
#Inject
private MyTimerLocal myTimer;
#Override
public int getMyValue() {
return this.myValue;
}
#Override
public synchronized void setMyValue(final int myValue) {
this.myValue = myValue;
}
#Override
public void activate() {
System.out.println("activate triggered");
Context ic = null;
try {
ic = new InitialContext();
ic.bind(MySingletonServiceClass.jndiName, this);
System.out.println("Object now bound in JNDI at " + MySingletonServiceClass.jndiName);
this.myValue = 5;
final String msg = "###################### MySingletonServiceClass.activate():: Fechamento agendado para " + this.myTimer.agendaExecucao() + " ###############";
System.out.println(msg);
} catch (final NamingException e) {
this.myValue = -1;
e.printStackTrace();
} finally {
try {
if (ic != null) {
ic.close();
}
} catch (final NamingException e) {
e.printStackTrace();
}
}
}
#Override
public void deactivate() {
System.out.println("deactivate triggered");
Context ic = null;
try {
ic = new InitialContext();
ic.unbind(MySingletonServiceClass.jndiName);
System.out.println("Context unbound successfully");
} catch (final NamingException e) {
e.printStackTrace();
}
}
}
Thanks for your time.
I got this working now with this in my src\main\application\META-INF\weblogic-application.xml
<wls:singleton-service>
<wls:class-name>com.test.MySingletonServiceClass</wls:class-name>
<wls:name>Appscoped_Singleton_Service</wls:name>
</wls:singleton-service>