AWS lambda spring . Not able to load properties file - spring

I have problem with loading the properties file where i reference the values from. Locally I am able to run it as expected. But AWS lambda function does not seem to work as expected since it is not able to laod properties file. Below is the handler written. I deploy MainHanlder.java function on lambda.
#Component
public class TestHandler implements RequestHandler<SNSEvent, Object> {
#Override
public String handleRequest(SNSEvent snsEvent, Context context) {
TestClient testClient = Application.getBean("pp",TestClient);
return null;
}
}
MainHandler.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.amazonaws.services.lambda.runtime.events.SNSEvent;
import com.test.lambda.ApplicationConfiguration;
public class MainHandler extends SpringRequestHandler<SNSEvent, Object> {
/**
* Here we create the Spring {#link ApplicationContext} that will
* be used throughout our application.
*/
private static final ApplicationContext context =
new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
#Override
public ApplicationContext getApplicationContext() {
return context;
}
}
SpringRequestHandler.java
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import org.springframework.context.ApplicationContext;
#SuppressWarnings("unchecked")
public abstract class SpringRequestHandler<I, O> implements RequestHandler<I, O>, ApplicationContextProvider {
private final RequestHandler<I, O> handler;
public SpringRequestHandler() {
handler = getApplicationContext().getBean(RequestHandler.class);
}
#Override
public O handleRequest(final I input, final Context context) {
return (O) handler.handleRequest(input, context);
}
}
Application.java
public class Application {
private static final AnnotationConfigApplicationContext springContext = new AnnotationConfigApplicationContext();
private static boolean flag = Boolean.TRUE;
private static final XLogger logger = XLoggerFactory.getXLogger(Application.class);
public static <T> T getBean(String env, Class<T> clazz) {
InputStream i1 = null;
InputStream i2 = null;
if(flag) {
Properties rp = new Properties();
Properties ap = new Properties();
try {
System.out.println("print env " + env);
i1 = Application.class.getResourceAsStream(“/application-” + env + ".properties");
rp.load(i1);
i2 = Application.class.getResourceAsStream("/application-" + env + ".properties");
ap.load(i2);
PropertyPlaceholderConfigurer propertyOverrideConfigurer = new PropertyPlaceholderConfigurer();
propertyOverrideConfigurer.setPropertiesArray(new Properties[]{rp,ap});
springContext.scan(new String[]{"com.pinto.lambda"});
springContext.addBeanFactoryPostProcessor(propertyOverrideConfigurer);
try {
springContext.refresh();
}catch(IllegalStateException e) {
}
flag = Boolean.FALSE;
} catch (Exception e) {
logger.error("Exception in the Application - " +e.getMessage());
throw new RuntimeException("Unable to load properties " + e.getMessage());
}
return springContext.getBean(clazz);
}
ERROR TRACE - AWS CONSOLE LOGS
==================== FUNCTION OUTPUT ====================
{"errorMessage":"Unable to load properties null","errorType":"java.lang.RuntimeException","stackTrace":["com.pinto.lambda.Application.getBean(Application.java:65)","com.pinto.lambda.handler.GetWarehouseInventoryHandler.handleRequest(TestHandler.java:44)","com.pinto.lambda.handler.GetWarehouseInventoryHandler.handleRequest(TestHandler.java:1)","com.pinto.lambda.handler.SpringRequestHandler.handleRequest(SpringRequestHandler.java:19)"]}
==================== FUNCTION LOG OUTPUT ====================
print env pp
[ERROR] Exception in the Application - null
Unable to load properties null: java.lang.RuntimeException
java.lang.RuntimeException: Unable to load properties null
at com.pinto.lambda.Application.getBean(Application.java:65)
at com.pinto.lambda.handler.TestHandler.handleRequest(TestHandler.java:44)
at com.pinto.lambda.handler.TestHandler.handleRequest(TestHandler.java:1)
at com.pinto.lambda.handler.SpringRequestHandler.handleRequest(SpringRequestHandler.java:19)

Related

how to pass the parameters to Websocket endpoint hander

When I create jetty websocket, I register my endpoint handler like this:
public class MyWebSocketEndpoint extends WebSocketServlet {
#Override
public void configure(WebSocketServletFactory webSocketServletFactory) {
webSocketServletFactory.register(MyEndpointHandler.class);
}
}
for MyEndpoingHandler class, I can't define a constructor with some parameters, or it will got runtime exception. How can I pass some parameters when create the MyEndpointHandler instance?
Use a WebSocketCreator.
When you call WebSocketServletFactory.register(MyEndpoingHandler.class) all that's happening internally is the equivalent of ...
#Override
public void register(Class<?> websocketPojo)
{
this.setCreator(new SingleEndpointCreator(websocketPojo));
}
Complete example on WebSocketCreator:
package websocket;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
public class DemoWebSocketCreator
{
public static class MyWebSocketServlet extends WebSocketServlet
{
#Override
public void configure(WebSocketServletFactory wsFactory)
{
wsFactory.setCreator(new MyWebSocketCreator());
}
}
public static class MyWebSocketCreator implements WebSocketCreator
{
private AtomicInteger idGen = new AtomicInteger(0);
#Override
public Object createWebSocket(ServletUpgradeRequest servletUpgradeRequest, ServletUpgradeResponse servletUpgradeResponse)
{
String id = "ws" + idGen.incrementAndGet();
return new MyWebSocket(id);
}
}
#WebSocket
public static class MyWebSocket
{
private final String id;
public MyWebSocket(String id)
{
this.id = id;
}
#OnWebSocketMessage
public void onMessage(Session session, String msg)
{
try
{
session.getRemote().sendString("Hello, my id is [" + id + "]: You said: " + msg);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addServlet(MyWebSocketServlet.class, "/ws/");
// always last, and on default pathspec
context.addServlet(DefaultServlet.class, "");
HandlerList handlers = new HandlerList();
handlers.addHandler(context);
handlers.addHandler(new DefaultHandler());
server.setHandler(handlers);
server.start();
server.join();
}
}

'java.lang.NoSuchMethoderror in java application which uses ehcache for cache implementation

I am facing below error when I run my java application which uses spring framework and ehcache for cache implementation. This application is build on IBM Integration Bus which Java and spring framework.
The full error stack is as below
+BIP2230E (Msg 2/4) MQJLMBRK ARCI511 147 ERROR DETECTED WHILST PROCESSI
NG A MESSAGE IN NODE 'ARFAL_MobilePortProtection01.FailureHandler.Tran
sform Failure'.
+BIP4367E (Msg 3/4) MQJLMBRK ARCI511 147 THE METHOD 'evaluate' IN JAVA
NODE 'FailureHandler.Transform Failure' HAS THROWN THE FOLLOWING EXCEP
TION: java.lang.NoSuchMethodError: org/ehcache/jcache/JCacheManager.ge
tEhCacheNativeCacheManager()Lnet/sf/ehcache/CacheManager;.
+BIP4395E (Msg 4/4) MQJLMBRK ARCI511 147 JAVA EXCEPTION: 'java.lang.NoS
uchMethodError'; THROWN FROM CLASS NAME: 'com.anz.common.cache.impl.Lo
calCacheHandler', METHOD NAME: 'getCacheManager', FILE: 'LocalCacheHan
dler.java', LINE: '99'
The code where error has triggered is as below
/**
*
*/
package com.anz.common.cache.impl;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.net.MalformedURLException;
import java.net.URL;
import javax.cache.Cache;
import javax.cache.configuration.MutableConfiguration;
import javax.management.MBeanServer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ehcache.jcache.JCacheManager;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.management.ManagementService;
/**
* ehCache Cache Handler in JCashe JSR107 standard API
* Cache Handler Factory -> Cache Handler -> Caching Provider -> Cache Manager -> Cache
* #author sanketsw
*
*/
public class LocalCacheHandler extends AbstractCacheHandler {
private static final Logger logger = LogManager.getLogger();
public static LocalCacheHandler _inst = null;
public LocalCacheHandler() throws Exception {
super();
}
/*public static LocalCacheHandler getInstance() throws Exception {
if (_inst == null) {
_inst = new LocalCacheHandler();
}
return _inst;
}*/
#Override
public String getDefaultCacheName() {
return "DefaultMap";
}
#Override
public String getCachingProviderName() {
return "org.ehcache.jcache.JCacheCachingProvider";
}
/* (non-Javadoc)
* #see com.anz.common.cache.impl.AbstractCacheHandler#getCache(java.lang.String)
*/
#Override
public Cache<String, String> getCache(String cacheName) throws CacheException, Exception {
Cache<String, String> cache = null;
try {
//logger.debug("Retriving cache {}", cacheName);
cache = cacheManager.getCache(cacheName);
} catch(Exception e) {
//logger.debug("Retriving cache using type classes {}", cacheName);
try {
cache = cacheManager.getCache(cacheName, String.class, String.class);
}catch(Exception e2) {
logger.throwing(e2);
}
}
if (cache == null) {
//logger.debug("Starting cache {}", cacheName);
MutableConfiguration<String, String> jcacheConfig = new MutableConfiguration<String, String>();
jcacheConfig.setTypes(String.class, String.class);
cache = cacheManager.createCache(cacheName, jcacheConfig);
}
return cache;
}
/* (non-Javadoc)
* #see com.anz.common.cache.impl.AbstractCacheHandler#getCacheManager()
*/
#Override
public javax.cache.CacheManager getCacheManager() throws Exception {
javax.cache.CacheManager ret = super.getCacheManager();
try {
// Register for JMX management
JCacheManager ehCacheManager = (JCacheManager)ret;
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ehCacheManager.getEhCacheNativeCacheManager().setName("LocalCacheManager");
//logger.info("printing mBeanServer {}", mBeanServer);
//logger.info("printing EhCacheNativeCacheManager {}", ehCacheManager.getEhCacheNativeCacheManager());
ManagementService.registerMBeans(ehCacheManager.getEhCacheNativeCacheManager(), mBeanServer, true, true, true, true);
}catch(Exception e) {
//logger.info("net.sf.ehcache:type=CacheManager,name=LocalCacheManager is already registered for JMX management. Ignoring...");
//logger.info(e.getMessage());
}
return ret;
}
#Override
public String getCacheManagerURI() {
String path = System.getenv("CACHE_CONFIG");
//logger.info("System property CACHE_CONFIG={}",path);
File configFile = new File(path + "/" + "ehcache-localcache.xml");
if(configFile.exists()) {
try {
return configFile.toURI().toURL().toString();
} catch (MalformedURLException e) {
logger.throwing(e);
}
} else {
URL resource = LocalCacheHandler.class.getResource("ehcache-localcache.xml");
if(resource != null) {
//logger.warn("Loading a backup config file={}",resource);
return resource.toString();
}
}
//logger.warn("Could not load the resource {}", "ehcache-localcache.xml");
return null;
}
}
Any clue what could be the issue.

Spring boot configure MessageInterpolator #Bean

I am using Spring boot v1.4 and hibernate v4.3.5.finall in my application
I have writen my own ResourceBundle and MessageInterpolator to save messages in database and have configured them as bean in my project. It seems ResourceBundle works fine and returns my custom message but parameters don't pass,for example for this validation :
#Size(min=5,max = 10)
private String lastName;
I expect : size must be between 5 and 10 bla bla.....
but the result is : size must be between {min} and {max} bla bla.....
any Idea? Thanks..
my ResourceBundle class:
package ir.pt.core.bundles;
import ir.pt.common.bean.ResourceEntity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.io.IOException;
import java.util.*;
public class DatabaseResourceBundle extends ResourceBundle {
#PersistenceContext
protected EntityManager em;
private Map<String, String> cache = new HashMap<String, String>();
protected final static String BUNDLE_NAME = "ir.pt.core.bundles";
protected Control DB_CONTROL = new DBControl();
public DatabaseResourceBundle() {
setParent(ResourceBundle.getBundle(BUNDLE_NAME, DB_CONTROL));
}
public DatabaseResourceBundle(Locale locale) {
setParent(ResourceBundle.getBundle(BUNDLE_NAME, locale, DB_CONTROL));
}
#Override
protected Object handleGetObject(String key) {
return cache != null ? cache.get(key) : parent.getObject(key);
}
#Override
public Enumeration<String> getKeys() {
return parent.getKeys();
}
protected class DBControl extends Control {
#Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException {
return new CustomizedLocaleResources(locale);
}
protected class CustomizedLocaleResources extends ListResourceBundle {
private Locale locale;
public CustomizedLocaleResources(Locale locale) {
this.locale = locale;
}
#Override
protected Object[][] getContents() {
String sql = "FROM ResourceEntity re WHERE re.locale = '"+locale.getLanguage()+"'";
TypedQuery<ResourceEntity> query =
em.createQuery(sql, ResourceEntity.class);
List<ResourceEntity> resources = query.getResultList();
Object[][] all = new Object[resources.size()][2];
int i = 0;
for (Iterator<ResourceEntity> it = resources.iterator(); it.hasNext();) {
ResourceEntity resource = it.next();
all[i] = new Object[]{resource.getKey(), resource.getMessage()};
cache.put(resource.getKey(), resource.getMessage());
i++;
}
return all;
}
}
}
}
my MessageInterpolator class:
package ir.pt.core.bundles;
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.MessageInterpolator;
import java.util.Locale;
import java.util.Map;
public class DatabaseMessageInterpolator extends ResourceBundleMessageInterpolator implements MessageInterpolator{
protected final String BRACE_OPEN = "\\{";
protected final String BRACE_CLOSE = "\\}";
#Autowired
DatabaseResourceBundle databaseResourceBundle;
#Override
public String interpolate(String message, Context context) {
return interpolate(message, context, databaseResourceBundle.getLocale());
}
#Override
public String interpolate(String message, Context context, Locale locale) {
String messageKey = context.getConstraintDescriptor().getAttributes().get("message").toString();
message = databaseResourceBundle.getString(messageKey.replaceAll(BRACE_OPEN, "").replaceAll(BRACE_CLOSE, ""));
Map<String, Object> attributes = context.getConstraintDescriptor().getAttributes();
for (String key : attributes.keySet()) {
String value = attributes.get(key).toString();
key = BRACE_OPEN + key + BRACE_CLOSE;
message = message.replaceAll(key, value);
}
return message;
}
}
my bean configuration:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurationSupport {
#Override
public Validator getValidator() {
LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
factory.setMessageInterpolator(messageInterpolator());
return factory;
}
#Bean
public MessageInterpolator messageInterpolator() {
return new DatabaseMessageInterpolator();
}
#Bean
ResourceBundle resourceBundle() {
return new DatabaseResourceBundle(new Locale("fa"));
}
}

Jetty Websocket Compilation Errors

I am trying to do an Jetty Web Socket example .
I copied a example from internet , which was working fine when i deployed directly into server without making any chnages .
But when i copied the Source (the servlet) into Eclipse IDE , it was giving Compilation
Exceptions related to
The method onClose(int, String) of type Html5Servlet.StockTickerSocket must override a superclass method
- The method onOpen(WebSocket.Connection) of type Html5Servlet.StockTickerSocket must override a superclass method
The method onMessage(String) of type Html5Servlet.StockTickerSocket must override a superclass method
This is my servlet , i kept the jars as it is mentioned in that example
package org.ajeesh.app;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketServlet;
public class Html5Servlet extends WebSocketServlet {
private AtomicInteger index = new AtomicInteger();
private static final List<String> tickers = new ArrayList<String>();
static{
tickers.add("ajeesh");
tickers.add("peeyu");
tickers.add("kidillan");
tickers.add("entammo");
}
/**
*
*/
private static final long serialVersionUID = 1L;
public WebSocket doWebSocketConnect(HttpServletRequest req, String resp) {
System.out.println("On server");
return new StockTickerSocket();
}
protected String getMyJsonTicker(){
StringBuilder start=new StringBuilder("{");
start.append("\"stocks\":[");
int counter=0;
for (String aTicker : tickers) {
counter++;
start.append("{ \"ticker\":\""+aTicker +"\""+","+"\"price\":\""+index.incrementAndGet()+"\" }");
if(counter<tickers.size()){
start.append(",");
}
}
start.append("]");
start.append("}");
return start.toString();
}
public class StockTickerSocket implements WebSocket.OnTextMessage{
private Connection connection;
private Timer timer;
#Override
public void onClose(int arg0, String arg1) {
System.out.println("Web socket closed!");
}
#Override
public void onOpen(Connection connection) {
System.out.println("onOpen!");
this.connection=connection;
this.timer=new Timer();
}
#Override
public void onMessage(String data) {
System.out.println("onMessage!");
if(data.indexOf("disconnect")>=0){
connection.close();
timer.cancel();
}else{
sendMessage();
}
}
private void sendMessage() {
System.out.println("sendMessage!");
if(connection==null||!connection.isOpen()){
System.out.println("Connection is closed!!");
return;
}
timer.schedule(new TimerTask() {
#Override
public void run() {
try{
System.out.println("Running task");
connection.sendMessage(getMyJsonTicker());
}
catch (IOException e) {
e.printStackTrace();
}
}
}, new Date(),5000);
}
}
}

EJB3 Client Lookup

I am trying to invoke a EJB from a standalone Java client, getting the below error.
Lookup code
String localJNDIName = "ejbremote:gcmsnew/gcmsutilbeans.jar/CustomerSurveyManageQstBean#com.smbcgroup.gcms.utility.bl.survey.CustomerSurveyManageQstRemote";
InitialContext ic = new InitialContext();
GCMSBaseRemote bean = (GCMSBaseRemote)ic.lookup(localJNDIName);
Exception
javax.naming.ConfigurationException: NamingManager.getURLContext
cannot find the factory for this scheme: ejbremote at
com.ibm.ws.naming.jndicos.CNContextImpl.checkForUrlContext(CNContextImpl.java:471)
at com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:160) at
com.ibm.ws.naming.util.WsnInitCtx.lookup(WsnInitCtx.java:179) at
javax.naming.InitialContext.lookup(Unknown Source) at
com.test.EJBClientTest.main(EJBClientTest.java:18)
Environment
RAD 7.5, EJB3. Websphere Application Server 7.0.
The ejbremote scheme does not exist in WebSphere Application Server (even though "ejblocal" does exist). Try using a ejb/ prefix instead of ejbremote:.
For more information, see the EJB application bindings overview topic in the InfoCenter.
Since this is a standalone ("thin") client may be you should try something like this:
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory");
properties.setProperty(Context.PROVIDER_URL,"corbaloc:iiop:localhost:2809"); //localhost=the host where your EJB is located, 2809=BOOTSTRAP_ADDRESS port
Context initCtx = new InitialContext(properties);
Object homeObject = initCtx.lookup("com.smbcgroup.gcms.utility.bl.survey.CustomerSurveyManageQstRemote"); //by default the JNDI name of your Remote Interface is its full class name
// Narrow to a real object
csmo = (CustomerSurveyManageQstRemote) javax.rmi.PortableRemoteObject.narrow(homeObject, com.smbcgroup.gcms.utility.bl.survey.CustomerSurveyManageQstRemote.class);
You should also have the appropriate Websphere Jars in your classpath in order to make the above calls.
For remote lookup
import java.io.IOException;
import java.util.Hashtable;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class ServiceLocator {
static String url = "corbaloc:iiop:localhost:2809";
static String initial = "com.ibm.websphere.naming.WsnInitialContextFactory";
static String jndi = "ejb/enterprise_app_name/ejb_web_project_name.jar/ejb_name#name.of.remote.impl.interface";
private static ServiceLocator serviceLocator = null;
InitialContext context = null;
private ServiceLocator() throws NamingException, IOException {
Hashtable<String,String> env = new Hashtable<String,String> ();
env.put("java.naming.provider.url", url );
env.put("java.naming.factory.initial", initial );
context = new InitialContext(env);
}
public synchronized static ServiceLocator getInstance() throws NamingException, IOException {
if (serviceLocator == null) {
serviceLocator = new ServiceLocator();
}
return serviceLocator;
}
public Object getService(String jndiName) throws NamingException {
return context.lookup(jndiName);
}
public <T>T getRemoteObject(Class<T> remoteInterfaceClass) {
try {
return (T)javax.rmi.PortableRemoteObject.narrow( context.lookup(jndi), remoteInterfaceClass);
} catch (NamingException nexc) {
nexc.printStackTrace();
}
return null;
}
}
For local lookup
import java.io.IOException;
import java.util.Hashtable;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class ServiceLocator {
static String url = "iiop://localhost";
static String initial = "com.ibm.websphere.naming.WsnInitialContextFactory";
static String jndi = "ejblocal:enterprise_app_name/ejb_web_project_name.jar/ejb_name#name.of.local.impl.interface";
private static ServiceLocator serviceLocator = null;
InitialContext context = null;
private ServiceLocator() throws NamingException, IOException {
Hashtable<String,String> env = new Hashtable<String,String> ();
env.put("java.naming.provider.url", url );
env.put("java.naming.factory.initial", initial );
context = new InitialContext(env);
}
public synchronized static ServiceLocator getInstance() throws NamingException, IOException {
if (serviceLocator == null) {
serviceLocator = new ServiceLocator();
}
return serviceLocator;
}
public Object getService(String jndiName) throws NamingException {
return context.lookup(jndiName);
}
public Object getService() throws NamingException {
return context.lookup(jndi);
}
}
You need to have the stub file to invoke the EJB, so first generate the stub file. In websphere there is utility available in the appserver bin folder createEJBStubs.

Resources