Commit b8684c95 by amir

initial

parents
Manifest-Version: 1.1
Class-Path:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>PushServer</display-name>
<servlet>
<servlet-name>ApiServlet</servlet-name>
<servlet-class>web.ApiServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ApiServlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>web.ApiServlet</listener-class>
</listener>
</web-app>
\ No newline at end of file
<project name="PushServer" default="rebuild-all" basedir="./">
<description>General thread manager</description>
<!-- set global properties for this build -->
<property name="src" location="src/" />
<property name="classes" location="build/classes" />
<property name="dist" location="../dist/PushServer" />
<property name="lib" location="../lib" />
<target name="init">
<!-- Create the time stamp -->
<tstamp />
<!-- Create the build directory structure used by compile -->
<mkdir dir="${classes}" />
</target>
<target name="compile" depends="init" description="compile the source ">
<javac srcdir="${src}" destdir="${classes}" debug="true">
<classpath path="${lib}/external/commons-collections-3.2.1.jar" />
<classpath path="${lib}/external/commons-io-2.0.1.jar" />
<classpath path="${lib}/external/commons-logging-1.1.1.jar" />
<classpath path="${lib}/external/commons-pool2-2.2.jar" />
<classpath path="${lib}/external/cxf-rt-rs-client-3.0.0.jar" />
<classpath path="${lib}/external/dom4j-1.6.1.jar" />
<classpath path="${lib}/external/gdata-core-1.0.jar" />
<classpath path="${lib}/external/gson-2.2.2.jar" />
<classpath path="${lib}/external/httpclient-4.1.jar" />
<classpath path="${lib}/external/httpcore-4.1.jar" />
<classpath path="${lib}/external/httpheaders-0.0.0.jar" />
<classpath path="${lib}/external/httpmime-4.1.jar" />
<classpath path="${lib}/external/jackson-annotations-2.2.3.jar" />
<classpath path="${lib}/external/jackson-core-2.2.3.jar" />
<classpath path="${lib}/external/jackson-databind-2.2.3.jar" />
<classpath path="${lib}/external/javaee-16.jar" />
<classpath path="${lib}/external/JavaPNS_2.2.jar" />
<classpath path="${lib}/external/javax.ws.rs-api-2.0.jar" />
<classpath path="${lib}/external/jedis-2.4.2.jar" />
<classpath path="${lib}/external/libphonenumber-5.8.jar" />
<classpath path="${lib}/external/log4j-1.2.17.jar" />
<classpath path="${lib}/external/rabbitmq-client.jar" />
<classpath path="${lib}/external/spring-aop-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-aspects-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-beans-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-context-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-core-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-data-redis-1.3.0.RELEASE.jar" />
<classpath path="${lib}/external/spring-expression-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-instrument-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-instrument-tomcat-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-jdbc-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-jms-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-oxm-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-struts-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-test-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-tx-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-web-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/spring-webmvc-3.2.6.RELEASE.jar" />
<classpath path="${lib}/external/wsdl4j-1.5.2.jar" />
<classpath path="${lib}/external/json_simple-1.1.jar" />
<classpath path="${lib}/internal/jinfra-util.jar" />
<classpath path="${lib}/internal/jinfra-generic-rest-servlet.jar" />
<classpath path="${lib}/internal/jinfra-Generic-seh.jar" />
<classpath path="${lib}/internal/jinfra-http-utilities.jar" />
<classpath path="${lib}/internal/jinfra-itm.jar" />
<classpath path="${lib}/internal/jinfra-kvstore.jar" />
<classpath path="${lib}/internal/jinfra-rabbitmq.jar" />
<classpath path="${lib}/internal/jinfra-rcs-core-api.jar" />
<classpath path="${lib}/internal/jinfra-simple-itc.jar" />
<classpath path="${lib}/internal/jinfra-microservice.jar" />
<classpath path="${lib}/internal/mcz-core.jar" />
</javac>
</target>
<target name="build-jar">
<jar destfile="${dist}/push-server.jar">
<manifest>
<attribute name="Main-Class" value="org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader"/>
<attribute name="Rsrc-Main-Class" value="web.App"/>
<attribute name="Class-Path" value="."/>
<attribute name="Rsrc-Class-Path" value="./ junit.jar
commons-collections-3.2.1.jar
commons-io-2.0.1.jar
commons-logging-1.1.1.jar
commons-pool2-2.2.jar
cxf-rt-rs-client-3.0.0.jar
dom4j-1.6.1.jar
gdata-core-1.0.jar
external/gson-2.2.2.jar
httpclient-4.1.jar
httpcore-4.1.jar
httpheaders-0.0.0.jar
external/httpmime-4.1.jar
jackson-annotations-2.2.3.jar
jackson-core-2.2.3.jar
jackson-databind-2.2.3.jar
javaee-16.jar
JavaPNS_2.2.jar
javax.ws.rs-api-2.0.jar
jedis-2.4.2.jar
jboss-logging-3.2.1.Final.jar
libphonenumber-5.8.jar
log4j-1.2.17.jar
rabbitmq-client.jar
spring-aop-3.2.6.RELEASE.jar
spring-aspects-3.2.6.RELEASE.jar
spring-beans-3.2.6.RELEASE.jar
spring-context-3.2.6.RELEASE.jar
spring-core-3.2.6.RELEASE.jar
spring-data-redis-1.3.0.RELEASE.jar
spring-expression-3.2.6.RELEASE.jar
spring-instrument-3.2.6.RELEASE.jar
spring-instrument-tomcat-3.2.6.RELEASE.jar
spring-jdbc-3.2.6.RELEASE.jar
spring-jms-3.2.6.RELEASE.jar
spring-oxm-3.2.6.RELEASE.jar
spring-struts-3.2.6.RELEASE.jar
spring-test-3.2.6.RELEASE.jar
spring-tx-3.2.6.RELEASE.jar
spring-web-3.2.6.RELEASE.jar
spring-webmvc-3.2.6.RELEASE.jar
wsdl4j-1.5.2.jar
undertow-core-1.0.1.Final.jar
json_simple-1.1.jar
jinfra-util.jar
jinfra-generic-rest-servlet.jar
jinfra-Generic-seh.jar
jinfra-http-utilities.jar
jinfra-itm.jar
jinfra-kvstore.jar
jinfra-rabbitmq.jar
jinfra-rcs-core-api.jar
jinfra-simple-itc.jar
jinfra-microservice.jar
xnio-api-3.2.0.Final.jar
xnio-nio-3.2.0.Final.jar
mcz-core.jar" />
</manifest>
<!-- required packages for creating this jar -->
<zipfileset src="${lib}/external/jar-in-jar-loader.zip"/>
<zipfileset dir="${lib}/external" includes="junit.jar"/>
<!-- add all your application generated classes -->
<fileset dir="${classes}"/>
<!-- add lib/external jars -->
<zipfileset dir="${lib}/external" includes="
commons-collections-3.2.1.jar
commons-io-2.0.1.jar
commons-logging-1.1.1.jar
commons-pool2-2.2.jar
cxf-rt-rs-client-3.0.0.jar
dom4j-1.6.1.jar
gdata-core-1.0.jar
external/gson-2.2.2.jar
httpclient-4.1.jar
httpcore-4.1.jar
httpheaders-0.0.0.jar
external/httpmime-4.1.jar
jackson-annotations-2.2.3.jar
jackson-core-2.2.3.jar
jackson-databind-2.2.3.jar
javaee-16.jar
JavaPNS_2.2.jar
javax.ws.rs-api-2.0.jar
jedis-2.4.2.jar
libphonenumber-5.8.jar
log4j-1.2.17.jar
jboss-logging-3.2.1.Final.jar
rabbitmq-client.jar
spring-aop-3.2.6.RELEASE.jar
spring-aspects-3.2.6.RELEASE.jar
spring-beans-3.2.6.RELEASE.jar
spring-context-3.2.6.RELEASE.jar
spring-core-3.2.6.RELEASE.jar
spring-data-redis-1.3.0.RELEASE.jar
spring-expression-3.2.6.RELEASE.jar
spring-instrument-3.2.6.RELEASE.jar
spring-instrument-tomcat-3.2.6.RELEASE.jar
spring-jdbc-3.2.6.RELEASE.jar
spring-jms-3.2.6.RELEASE.jar
spring-oxm-3.2.6.RELEASE.jar
spring-struts-3.2.6.RELEASE.jar
spring-test-3.2.6.RELEASE.jar
spring-tx-3.2.6.RELEASE.jar
spring-web-3.2.6.RELEASE.jar
spring-webmvc-3.2.6.RELEASE.jar
wsdl4j-1.5.2.jar
json_simple-1.1.jar
undertow-core-1.0.1.Final.jar
xnio-api-3.2.0.Final.jar
xnio-nio-3.2.0.Final.jar
"/>
<!-- add lib/internal jars -->
<zipfileset dir="${lib}/internal" includes="
jinfra-util.jar
jinfra-generic-rest-servlet.jar
jinfra-Generic-seh.jar
jinfra-http-utilities.jar
jinfra-itm.jar
jinfra-kvstore.jar
jinfra-rabbitmq.jar
jinfra-rcs-core-api.jar
jinfra-simple-itc.jar
jinfra-microservice.jar
mcz-core.jar
"/>
</jar>
</target>
<target name="rebuild-all" depends="clean-all,compile,build-jar"
description="rebuild the jar">
</target>
<target name="clean-all" description="clean up">
<delete dir="${classes}" />
<delete file="${dist}/push-server.jar" />
</target>
</project>
## mcx properties ##
ds.ip.address=172.16.1.10
ds.ip=172.16.1.10:9001
mclogic.sip.ip=172.16.1.244:5065
mclogic.ip=172.16.1.244:8001
# -Dmcpresence.ip=172.16.1.244:9001
# -Dmcpresence.sip.ip=172.16.1.244:5070
mcweb.ip=172.16.1.244:8080
redis.port=6379
log4j.prop.file.path=/home/amir/resincfg/log4j.properties
mcz.files.location=/opt/mcz
## microservice props
server.port=7070
server.host=172.16.1.151
server.worker.threads=6
rmqServer.listenRMQId=pushServer@172.16.1.151
rmqServer.WorkerThreadsNum=4
rmqServer.maxRMQSize=1000
rmqServer.logPath=/logs
## app props
file.name.location=/opt/mcz/config/PushServer/customerList.properties
android.push.app.username=876050233151
android.push.app.password=AIzaSyA20S_29tZdcjy9IWseviAXZczuFUu9H5M
config.apple.cert.type=development
{
"Tata": {
"Apple": {
"prod":"/opt/Certificates/ProductionAPS.p12",
"dev":"/opt/Certificates/DevelopmentAPS.p12"
},
"Google": {
"user":"876050233151",
"pass":"AIzaSyA20S_29tZdcjy9IWseviAXZczuFUu9H5M"
}
},
"Main": {
"Apple": {
"prod":"/opt/Certificates/ProductionAPS.p12",
"dev":"/opt/Certificates/DevelopmentAPS.p12"
},
"Google": {
"user":"876050233151",
"pass":"AIzaSyA20S_29tZdcjy9IWseviAXZczuFUu9H5M"
}
}
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:redis="http://www.springframework.org/schema/redis"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
http://www.springframework.org/schema/redis http://www.springframework.org/schema/redis/spring-redis.xsd">
<context:property-placeholder />
<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${ds.ip.address}" p:port="${redis.port}" p:password="" p:use-pool="false"/>
<!-- the default ConnectionFactory -->
<redis:listener-container connection-factory="redisConnectionFactory" >
<redis:listener ref="listener" method="handleStringMessage" topic="cfg:*" />
</redis:listener-container>
<bean id="listener" class="mcz.core.dsclient.DefaultMessageDelegate" />
<bean id="daoImpl" class="mcz.core.dsclient.DaoDsImpl" depends-on="systemPropertiesSetter" />
<util:properties id="staticConfiguration" location="file:${configFile.location}"/>
<bean id="systemPropertiesSetter" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="java.lang.System" />
<property name="targetMethod" value="getProperties" />
</bean>
</property>
<property name="targetMethod" value="putAll" />
<property name="arguments" ref="staticConfiguration">
</property>
</bean>
</beans>
\ No newline at end of file
package data;
import java.util.List;
public class SendBulkPushModel
{
public static class DevicePushData
{
public String publicId;
public SendPushModel model;
};
public String msg = null;
public List<DevicePushData> devicePushList = null;
}
package data;
import mcz.core.defs.Enums.EnumMobilePhoneOS;
public class SendPushModel
{
public EnumMobilePhoneOS enumMobileOS = EnumMobilePhoneOS.E_ANDROID;
public String msg = null;
public String token = null;
public String customerId = null;
}
package handlers;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import HttpUtilities.SimpleRestResponse;
import com.grs.BaseRestResponse;
import data.SendBulkPushModel;
import data.SendPushModel;
import data.SendBulkPushModel.DevicePushData;
import utils.BulkPushNotificationWorker;
import mcx.microservice.RequestContext;
import mcx.microservice.handlers.BaseHandler;
import mcz.core.beans.Dao;
import mcz.core.beans.deviceinstances.DeviceInstance;
import mcz.core.util.Common;
import mcz.core.util.pushNotification.PushCustomerList;
import mcz.core.util.pushNotification.PushUtil;
import mcz.core.util.pushNotification.PushCustomerList.Provider;
public class MobilePushHandler extends BaseHandler
{
private static final Logger logger = Logger.getLogger(MobilePushHandler.class.getName()); // api's
private static final String SEND_PUSH_API = "sendPush";
private static final String SEND_BULK_PUSH_API = "sendBulkPush";
private static final String TEST_API = "test";
private final static String MISSING_JSON_OBJECT = "Missing json object";
private final static String MISSING_TOKEN_OR_PUBLIC_ID_NOT_FOUND = "MISSING TOKEN OR PUBLIC ID NOT FOUND";
Dao dao;
PushCustomerList pcl = null;
Map<String,Provider> customerMap = null;
public MobilePushHandler(Dao dao)
{
super();
this.dao = dao;
this.pcl = new PushCustomerList();
this.customerMap = pcl.readFromFile();
}
@Override
public void doCreate(RequestContext reqCtx)
{
if (reqCtx.params[0].equals(SEND_PUSH_API))
{
handlePostSendPush(reqCtx);
}
else if (reqCtx.params[0].equals(SEND_BULK_PUSH_API))
{
handlePostSendBulkPush(reqCtx);
}
}
@Override
public void doDelete(RequestContext reqCtx)
{
// TODO Auto-generated method stub
}
@Override
public void doRead(RequestContext reqCtx)
{
if (reqCtx.params[0].equals(SEND_PUSH_API))
{
writeObjectToResponse(reqCtx,new SendPushModel());
}
else if (reqCtx.params[0].equals(SEND_BULK_PUSH_API))
{
writeObjectToResponse(reqCtx,new SendBulkPushModel());
}
else if (reqCtx.params[0].equals(TEST_API))
{
// test code for rabbit
SimpleRestResponse mbiResp = new SimpleRestResponse(false, "method not implemented", null);
writeObjectToResponse(reqCtx, mbiResp);
}
}
@Override
public void doUpdate(RequestContext reqCtx)
{
// TODO Auto-generated method stub
}
/**
* sending single push msg
* @param reqCtx
*/
private void handlePostSendPush(RequestContext reqCtx)
{
String publicId = reqCtx.params[1];
BaseRestResponse brr = new BaseRestResponse(true,null);
logger.info("handlePostSendPush: " + publicId);
SendPushModel spm = (SendPushModel)readObjectFromRequest(reqCtx,SendPushModel.class);
if (spm != null && spm.msg != null)
{
if (spm.token == null)
{
/*
* setting the token and os from db
*/
setDeviceParams(publicId,spm);
}
if (spm.token != null)
{
/*
* create and send push job
*/
brr.success = PushUtil.sendPushMsg(spm.token, spm.enumMobileOS, spm.msg);
// int queueNumber = threadManager.getQueueNumber(publicId);
// threadManager.sendJob(1,
// new PushNotificationWorker(spm.token, spm.enumMobileOS, spm.msg),
// null,
// queueNumber,
// MobilePushHandler.class.getName());
}
else
{
logger.warning(MISSING_TOKEN_OR_PUBLIC_ID_NOT_FOUND);
brr.success = false;
brr.error = MISSING_TOKEN_OR_PUBLIC_ID_NOT_FOUND;
}
}
else
{
logger.warning(MISSING_JSON_OBJECT);
brr.success = false;
brr.error = MISSING_JSON_OBJECT;
}
writeObjectToResponse(reqCtx,brr);
}
/**
* sending bulk of push messages
* @param reqCtx
*/
private void handlePostSendBulkPush(RequestContext reqCtx)
{
BaseRestResponse brr = new BaseRestResponse(true,null);
logger.info("handlePostSendBulkPush");
List<SendPushModel> devicePushList = null;
SendBulkPushModel sbpm = (SendBulkPushModel)readObjectFromRequest(reqCtx,SendBulkPushModel.class);
if (sbpm != null && sbpm.msg != null &&
sbpm.devicePushList != null && !sbpm.devicePushList.isEmpty())
{
devicePushList = new LinkedList<SendPushModel>();
/*
* collecting data
*/
for (DevicePushData dpd : sbpm.devicePushList)
{
if (dpd != null)
{
if (dpd.model.token == null || dpd.model.enumMobileOS == null)
{
if (setDeviceParams(dpd.publicId,dpd.model) )
devicePushList.add(dpd.model);
}
else
devicePushList.add(dpd.model);
}
}
/*
* sending bulk job
*/
brr.success = (new BulkPushNotificationWorker(devicePushList ,sbpm.msg,this.customerMap)).sendBulk();
// currentNumber = threadManager.getNextQueueNumber(currentNumber);
// threadManager.sendJob(1,
// new BulkPushNotificationWorker(devicePushList ,sbpm.msg,this.customerMap),
// null,
// currentNumber,
// MobilePushHandler.class.getName());
}
else
{
logger.warning(MISSING_JSON_OBJECT);
brr.success = false;
brr.error = MISSING_JSON_OBJECT;
}
writeObjectToResponse(reqCtx,brr);
}
/**
* setting the push token and mobile os from device
* @param publicId
* @return
*/
private boolean setDeviceParams(String publicId,SendPushModel spm)
{
DeviceInstance di = Common.getDeviceInstanceByPublicId(dao, publicId);
if (di != null && di.getToken() != null)
{
spm.token = di.getToken();
spm.enumMobileOS = di.getMobileOS();
return true;
}
return false;
}
}
package utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import data.SendBulkPushModel.DevicePushData;
import data.SendPushModel;
import mcz.core.beans.deviceinstances.DeviceInstance;
import mcz.core.defs.Enums.EnumMobilePhoneOS;
import mcz.core.util.pushNotification.PushCustomerList.Provider;
import mcz.core.util.pushNotification.PushUtil;
/**
* send bulk push notification
* @author amir
*
*/
public class BulkPushNotificationWorker implements Runnable
{
List<SendPushModel> devicePushList;
List<String> appleInstanceList = new ArrayList<String>();
List<String> androidInstanceList = new ArrayList<String>();
String msg;
Map<String,Provider> customerMap;
public BulkPushNotificationWorker(List<SendPushModel> devicePushList, String msg, Map<String,Provider> customerMap)
{
super();
this.devicePushList = devicePushList;
this.msg = msg;
this.customerMap = customerMap;
}
@Override
public void run()
{
sendBulk();
}
public boolean sendBulk()
{
String customerId = null;
Provider provider = null;
boolean bSendBulkAndroid = false, bSendBulkIOS = false;
if (devicePushList != null && msg != null && !msg.isEmpty())
{
bSendBulkAndroid = true;
bSendBulkIOS = true;
for (SendPushModel di : devicePushList)
{
if (di != null)
{
if(customerId == null) {
customerId = di.customerId;
provider = customerMap.get(customerId);
}
if(EnumMobilePhoneOS.E_IOS.equals(di.enumMobileOS))
{
appleInstanceList.add(di.token);
}
else if(EnumMobilePhoneOS.E_ANDROID.equals(di.enumMobileOS))
{
androidInstanceList.add(di.token);
}
}
}
if(appleInstanceList.size() > 0 )
bSendBulkIOS = PushUtil.sendAppleBulkPushMsg(appleInstanceList, msg, provider);
if(androidInstanceList.size() > 0 )
bSendBulkAndroid = PushUtil.sendAndroidBulkPushMsg(androidInstanceList, msg, provider);
}
return (bSendBulkAndroid && bSendBulkIOS);
}
}
package utils;
import mcz.core.defs.Enums.EnumMobilePhoneOS;
import mcz.core.util.pushNotification.PushUtil;
/**
* send push notification
* @author Yacov
*
*/
public class PushNotificationWorker implements Runnable{
String token;
EnumMobilePhoneOS enumMobileOS;
String msg;
public PushNotificationWorker(String token, EnumMobilePhoneOS enumMobileOS, String msg)
{
this.enumMobileOS = enumMobileOS;
this.token = token;
this.msg = msg;
}
@Override
public void run()
{
PushUtil.sendPushMsg(token, enumMobileOS, msg);
}
}
package web;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mcz.core.beans.ConfParameter;
import mcz.core.beans.Dao;
import mcz.core.dsclient.DaoDsImpl;
//import org.codehaus.jackson.map.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.web.context.support.ServletContextResource;
import com.grs.GeneralRestHandler;
/**
* Servlet implementation class ApiServlet
*/
//@WebServlet("/api")
public class ApiServlet extends HttpServlet implements ServletContextListener{
private static final long serialVersionUID = 1L;
public static final ObjectMapper MAPPER = new ObjectMapper();
private GeneralRestHandler restHandler;
private static Object lock = new Object();
/**
* @see HttpServlet#HttpServlet()
*/
public ApiServlet() {
super();
// TODO Auto-generated constructor stub
}
public static Dao getDao(ServletContext servletContext) {
Dao dao = null;
synchronized (lock) {
dao = (Dao)servletContext.getAttribute(Dao.ATTR_NAME);
if (dao == null) {
dao = new DaoDsImpl();
servletContext.setAttribute(Dao.ATTR_NAME, dao);
}
}
return dao;
}
// public static Dao getDao(ServletContext servletContext, BeanFactory factory) {
// // TODO move this static method to somewhere in the Dao section, maybe Dao util?
// Dao dao = null;
// synchronized (lock) {
// dao = (Dao)servletContext.getAttribute(Dao.ATTR_NAME);
// if (dao == null) {
// dao = (Dao)factory.getBean("daoImpl");
// servletContext.setAttribute(Dao.ATTR_NAME, dao);
// }
// }
// return dao;
//}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
Dao dao = getDao(config.getServletContext());
restHandler = new GeneralRestHandler(config.getServletContext());
//Adding rest handlers:
restHandler.addPrefixPath(new MobilePushHandler("/push",MAPPER,dao));
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
restHandler.doGet(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
restHandler.doPost(request, response);
}
@Override
public void contextDestroyed(ServletContextEvent arg0)
{
}
private void validateConfiguration(Dao dao)
{
// logger.info("Validating configuration parameters...");
for (ConfParameter param : ConfParameter.values()) {
Object value = dao.getValue(param);
if (value == null) {
// logger.fine("Creating conf parameter " + param + " with default value " + param.getDefaultValue());
dao.setValue(param, param.getDefaultValue());
} else {
// logger.fine("conf parameter " + param + " exists with value " + value);
}
}
}
@Override
public void contextInitialized(ServletContextEvent arg0)
{
ServletContext servletContext = arg0.getServletContext();
// init spring beans
Resource resource = new ServletContextResource(servletContext, "/WEB-INF/classes/config/beans.xml");
BeanFactory factory = new XmlBeanFactory(resource);
factory.getBean("systemPropertiesSetter");
Dao dao = getDao(servletContext);
validateConfiguration(dao); // testing
}
}
package web;
import handlers.MobilePushHandler;
import Util.ConfigProperties;
import Util.ConfigProperties.EnumPropertyType;
import mcx.microservice.MicroserviceApp;
import mcx.microservice.params.MBIParams;
import mcx.microservice.params.RestServerParams;
import mcz.core.beans.Dao;
import mcz.core.dsclient.DaoDsImpl;
public class App
{
public static void main(final String[] args) {
ConfigProperties.getInstance().loadProperties();
// load rest server parameters
Long port = (Long) ConfigProperties.getInstance().addConfigurationPropertyToHash("server.port","8080",EnumPropertyType.E_LONG);
String host = (String) ConfigProperties.getInstance().addConfigurationPropertyToHash("server.host","localhost",EnumPropertyType.E_STRING);
Long workerThreadsNum = (Long) ConfigProperties.getInstance().addConfigurationPropertyToHash("server.worker.threads","8",EnumPropertyType.E_LONG);
RestServerParams rsiParams = new RestServerParams(port.intValue(), host, workerThreadsNum.intValue());
// load RMQ server parameters
// String listenRMQId, int numOfWorkerThreads, int maxRMQSize, String logPath
String rmqListenQueue = (String)ConfigProperties.getInstance().addConfigurationPropertyToHash("rmqServer.listenRMQId", null,EnumPropertyType.E_STRING);
int rmqWorkerThreadsNum = ((Long) ConfigProperties.getInstance().addConfigurationPropertyToHash("rmqServer.WorkerThreadsNum","8",EnumPropertyType.E_LONG)).intValue();
int rmqMaxRMQSize = ((Long)ConfigProperties.getInstance().addConfigurationPropertyToHash("rmqServer.maxRMQSize","1000",EnumPropertyType.E_LONG)).intValue();
String rmqLogPath = (String)ConfigProperties.getInstance().addConfigurationPropertyToHash("rmqServer.logPath", "/logs", EnumPropertyType.E_STRING);
MBIParams mbiParams = new MBIParams(rmqListenQueue, rmqWorkerThreadsNum, rmqMaxRMQSize, rmqLogPath);
Dao dao = new DaoDsImpl();
MicroserviceApp msApp = new MicroserviceApp(rsiParams, mbiParams, "PushServer");
msApp.addHandler("/push", new MobilePushHandler(dao));
if (msApp.startApp() == false)
System.out.println("failed starting... check logs");
}
}
package web;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mcz.core.beans.Dao;
import mcz.core.beans.deviceinstances.DeviceInstance;
import mcz.core.util.Common;
import mcz.core.util.MultiThreadQueueManager;
import mcz.core.util.pushNotification.PushCustomerList;
//import org.codehaus.jackson.map.ObjectMapper;
import mcz.core.util.pushNotification.PushCustomerList.Provider;
import utils.BulkPushNotificationWorker;
import utils.PushNotificationWorker;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.grs.BaseRestHandler;
import com.grs.BaseRestResponse;
import data.SendBulkPushModel;
import data.SendPushModel;
import data.SendBulkPushModel.DevicePushData;
public class MobilePushHandler extends BaseRestHandler
{
private final static String THREAD_MANAGER_THREADS;
private final static String THREAD_MANAGER_QUEUE_SIZE;
static
{
THREAD_MANAGER_THREADS = (System.getProperty("config.thread.manager.threads") != null)? System.getProperty("config.offline.task.threads") : "7";
THREAD_MANAGER_QUEUE_SIZE = (System.getProperty("config.thread.manager.queue.size") != null)? System.getProperty("config.offline.task.queue.size") : "100";
}
Dao dao = null;
PushCustomerList pcl = null;
Map<String,Provider> customerMap = null;
private static MultiThreadQueueManager threadManager = null;
int currentNumber = 0;
private static final Logger logger = Logger.getLogger(MobilePushHandler.class.getName()); // api's
private static final String SEND_PUSH_API = "sendPush";
private static final String SEND_BULK_PUSH_API = "sendBulkPush";
private final static String MISSING_JSON_OBJECT = "Missing json object";
private final static String MISSING_TOKEN_OR_PUBLIC_ID_NOT_FOUND = "MISSING TOKEN OR PUBLIC ID NOT FOUND";
public MobilePushHandler(String apiContextPath, ObjectMapper objMapper, Dao dao)
{
super(apiContextPath, objMapper);
this.dao = dao;
this.pcl = new PushCustomerList();
this.customerMap = pcl.readFromFile();
synchronized(this)
{
if (threadManager == null)
{
threadManager = new MultiThreadQueueManager();
threadManager.startManager(Integer.parseInt(THREAD_MANAGER_THREADS), Integer.parseInt(THREAD_MANAGER_QUEUE_SIZE));
}
}
}
@Override
protected void finalize() throws Throwable
{
synchronized(this)
{
threadManager.stopManager();
}
super.finalize();
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res,
String[] parts)
{
if (parts[0].equals(SEND_PUSH_API))
{
writeObjectToResponse(res,new SendPushModel());
}
else if (parts[0].equals(SEND_BULK_PUSH_API))
{
writeObjectToResponse(res,new SendBulkPushModel());
}
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res,
String[] parts)
{
if (parts[0].equals(SEND_PUSH_API))
{
handlePostSendPush(req,res,parts);
}
else if (parts[0].equals(SEND_BULK_PUSH_API))
{
handlePostSendBulkPush(req,res,parts);
}
}
/**
* sending single push msg
* @param req
* @param res
* @param parts
*/
private void handlePostSendPush(HttpServletRequest req,
HttpServletResponse res, String[] parts)
{
String publicId = parts[1];
BaseRestResponse brr = new BaseRestResponse(true,null);
logger.info("handlePostSendPush: " + publicId);
SendPushModel spm = (SendPushModel)readObjectFromRequest(req,SendPushModel.class);
if (spm != null && spm.msg != null)
{
if (spm.token == null)
{
/*
* setting the token and os from db
*/
setDeviceParams(publicId,spm);
}
if (spm.token != null)
{
/*
* create and send push job
*/
int queueNumber = threadManager.getQueueNumber(publicId);
threadManager.sendJob(1,
new PushNotificationWorker(spm.token, spm.enumMobileOS, spm.msg),
null,
queueNumber,
MobilePushHandler.class.getName());
}
else
{
logger.warning(MISSING_TOKEN_OR_PUBLIC_ID_NOT_FOUND);
brr.success = false;
brr.error = MISSING_TOKEN_OR_PUBLIC_ID_NOT_FOUND;
}
}
else
{
logger.warning(MISSING_JSON_OBJECT);
brr.success = false;
brr.error = MISSING_JSON_OBJECT;
}
writeObjectToResponse(res,brr);
}
/**
* sending bulk of push messages
* @param req
* @param res
* @param parts
*/
private void handlePostSendBulkPush(HttpServletRequest req,
HttpServletResponse res, String[] parts)
{
BaseRestResponse brr = new BaseRestResponse(true,null);
logger.info("handlePostSendBulkPush");
List<SendPushModel> devicePushList = null;
SendBulkPushModel sbpm = (SendBulkPushModel)readObjectFromRequest(req,SendBulkPushModel.class);
if (sbpm != null && sbpm.msg != null &&
sbpm.devicePushList != null && !sbpm.devicePushList.isEmpty())
{
devicePushList = new LinkedList<SendPushModel>();
/*
* collecting data
*/
for (DevicePushData dpd : sbpm.devicePushList)
{
if (dpd != null)
{
if (dpd.model.token == null || dpd.model.enumMobileOS == null)
{
if (setDeviceParams(dpd.publicId,dpd.model) )
devicePushList.add(dpd.model);
}
else
devicePushList.add(dpd.model);
}
}
/*
* sending bulk job
*/
currentNumber = threadManager.getNextQueueNumber(currentNumber);
threadManager.sendJob(1,
new BulkPushNotificationWorker(devicePushList ,sbpm.msg,this.customerMap),
null,
currentNumber,
MobilePushHandler.class.getName());
}
else
{
logger.warning(MISSING_JSON_OBJECT);
brr.success = false;
brr.error = MISSING_JSON_OBJECT;
}
writeObjectToResponse(res,brr);
}
/**
* setting the push token and mobile os from device
* @param publicId
* @return
*/
private boolean setDeviceParams(String publicId,SendPushModel spm)
{
DeviceInstance di = Common.getDeviceInstanceByPublicId(dao, publicId);
if (di != null && di.getToken() != null)
{
spm.token = di.getToken();
spm.enumMobileOS = di.getMobileOS();
return true;
}
return false;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment