diff --git a/.gitignore b/.gitignore
index e6e96a8..0a675dd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -53,3 +53,7 @@ dist/
nbdist/
.nb-gradle/
+.settings
+.classpath
+.project
+bin/
diff --git a/Examples/iexec/pom.xml b/Examples/iexec/pom.xml
new file mode 100755
index 0000000..4e86e71
--- /dev/null
+++ b/Examples/iexec/pom.xml
@@ -0,0 +1,45 @@
+
+ 4.0.0
+ com.fourelementscapital
+ iexec
+ 3.0.0-Beta1
+ iexec
+ http://www.fourelementscapital.com
+
+
+
+
+ org.apache.commons
+ commons-jcs-core
+ 2.2
+
+
+
+
+ commons-logging
+ commons-logging
+ 1.2
+
+
+
+
+ com.fourelementscapital
+ lib-db
+ 2.0
+
+
+
+
+ org.apache.logging.log4j
+ log4j-core
+ 2.8.1
+
+
+
+
+
+
+ UTF-8
+
+
\ No newline at end of file
diff --git a/Examples/iexec/src/main/java/com/fourelementscapital/iexec/common/IExecMgmt.java b/Examples/iexec/src/main/java/com/fourelementscapital/iexec/common/IExecMgmt.java
new file mode 100755
index 0000000..e0a4b24
--- /dev/null
+++ b/Examples/iexec/src/main/java/com/fourelementscapital/iexec/common/IExecMgmt.java
@@ -0,0 +1,74 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.iexec.common;
+
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+import javax.servlet.http.HttpServletRequest;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import com.fourelementscapital.db.IExecDB;
+import com.fourelementscapital.db.vo.ValueObject;
+
+
+/**
+ * Use lib-db to generate tree menu on iExec
+ */
+
+public class IExecMgmt{
+
+ private HttpServletRequest request=null;
+ private Logger log = LogManager.getLogger(IExecMgmt.class.getName());
+
+ public IExecMgmt() throws Exception {
+ super();
+
+ }
+
+ public Map getTreeViewData() throws Exception {
+
+ IExecDB iedb=IExecDB.getIExcecDB();
+
+ try{
+ HashMap rtn=new HashMap();
+
+ iedb.connectDB();
+
+ List glist=iedb.listGroups();
+ List folders=iedb.listFolders();
+ List strategies=iedb.listStrategies();
+
+ Vector groups=new Vector();
+ HashMap colors=new HashMap();
+ for(Iterator it=glist.iterator();it.hasNext();){
+ Map data=(Map)it.next();
+
+ ValueObject vo=new ValueObject();
+ vo.setKey((String)data.get("group_uid"));
+ vo.setValue((String)data.get("group_name"));
+ groups.add(vo);
+ colors.put(data.get("group_uid"), data.get("color_code"));
+ }
+ rtn.put("folders", folders);
+ rtn.put("groups",groups);
+ rtn.put("group_colors",colors);
+ rtn.put("strategies",strategies);
+
+ return rtn;
+
+ }catch(Exception e){
+ throw e;
+ }finally{
+ iedb.closeDB();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Examples/qlib/pom.xml b/Examples/qlib/pom.xml
new file mode 100755
index 0000000..037c416
--- /dev/null
+++ b/Examples/qlib/pom.xml
@@ -0,0 +1,78 @@
+
+ 4.0.0
+ com.fourelementscapital
+ qLib
+ ${revision}${changelist}
+ war
+ qLib
+ http://www.fourelementscapital.com
+
+
+ 3.0.0
+ -Beta1
+ UTF-8
+
+
+
+
+
+
+
+ com.fourelementscapital
+ lib-config
+ 2.0
+
+
+ com.fourelementscapital
+ lib-auth
+ 2.0
+
+
+ com.fourelementscapital
+ lib-db
+ 2.0
+
+
+
+
+
+ org.slf4j
+ slf4j-simple
+ 1.7.25
+
+
+ org.apache.logging.log4j
+ log4j-core
+ 2.8.1
+
+
+
+ org.apache.commons
+ commons-compress
+ 1.15
+
+
+
+
+ org.apache.commons
+ commons-jcs-core
+ 2.2
+
+
+
+ commons-logging
+ commons-logging
+ 1.2
+
+
+
+
+ com.fourelementscapital
+ lib-client
+ 2.0
+
+
+
+
+
\ No newline at end of file
diff --git a/Examples/qlib/src/main/java/com/fourelementscapital/rfunction/common/AbstractTeamOrgMgmt.java b/Examples/qlib/src/main/java/com/fourelementscapital/rfunction/common/AbstractTeamOrgMgmt.java
new file mode 100755
index 0000000..ef7e044
--- /dev/null
+++ b/Examples/qlib/src/main/java/com/fourelementscapital/rfunction/common/AbstractTeamOrgMgmt.java
@@ -0,0 +1,305 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.rfunction.common;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import com.fourelementscapital.config.Constant;
+import com.fourelementscapital.auth.UserThemeAccessPermission;
+import com.fourelementscapital.db.AbstractTeamOrgDB;
+import com.fourelementscapital.db.SchedulerDB;
+import com.fourelementscapital.client.Authenticated;
+
+
+
+/**
+ * This class is abstract and provide basic implementation for all Team Organization related moudles
+ * for example: Themes tag support on scheduler, R function *
+ * @author Administrator
+ *
+ */
+@SuppressWarnings("unchecked")
+public abstract class AbstractTeamOrgMgmt extends Authenticated{
+
+ protected static String ACCESS_PRIVILEGE_RWX="RWX";
+ protected static String ACCESS_PRIVILEGE_RX="RX";
+ protected static String ACCESS_PRIVILEGE_R="R";
+ private Logger log = LogManager.getLogger(AbstractTeamOrgMgmt.class.getName());
+
+
+ /**
+ * this constructor to be used only for DWR, manual invoking to get the object using of this constructor will mis-behave
+ * @throws Exception
+ */
+ public AbstractTeamOrgMgmt() throws Exception {
+ super();
+
+ }
+
+
+ /**
+ * this constructor will be used only when JSP or Httprequest request is available.
+ * @param request
+ * @throws Exception
+ */
+ public AbstractTeamOrgMgmt(HttpServletRequest request) throws Exception {
+ super(request);
+ }
+
+
+ /**
+ * to be used in child class
+ * @param sdb
+ * @return
+ * @throws Exception
+ */
+ protected Map getThemeAccessData(AbstractTeamOrgDB sdb) throws Exception {
+
+ UserThemeAccessPermission auth=getAuthenticatedUserObj(sdb);
+ HashMap rtn=new HashMap();
+ if(auth!=null){
+ rtn.put("rwx_tags",auth.getRwx());
+ rtn.put("rx_tags",auth.getRx());
+ rtn.put("r_tags",auth.getR());
+ }
+
+ String superuser=(String)getRequest().getSession().getAttribute(Constant.SESSION_LOGGED_SUPERUSER);
+ if(superuser!=null && !superuser.equals("")){
+ rtn.put("superuser",superuser);
+ }
+ return rtn;
+ }
+
+
+ /**
+ *
+ * @param scheduler_id
+ * @param sdb
+ * @return
+ * @throws Exception
+ */
+ protected String getAccessPrivilege(int scheduler_id, AbstractTeamOrgDB sdb) throws Exception {
+ String rtn="";
+ UserThemeAccessPermission user=getAuthenticatedUserObj(sdb);
+ if(user!=null){
+ List themes=sdb.getThemeTags(scheduler_id);
+
+ log.debug("themes:"+themes);
+ log.debug("user.getRwx():"+user.getRwx());
+ log.debug("user.getRx():"+user.getRx());
+ log.debug("user.getR():"+user.getR());
+
+ for(String ttag:themes){
+ if(user.getRwx().contains(ttag)) rtn=ACCESS_PRIVILEGE_RWX;
+ if(user.getRx().contains(ttag) && (!rtn.equals(ACCESS_PRIVILEGE_RWX) )) rtn=ACCESS_PRIVILEGE_RX;
+ if(user.getR().contains(ttag) && rtn.equals("")) rtn=ACCESS_PRIVILEGE_R;
+ }
+ if(themes.size()==0) rtn=ACCESS_PRIVILEGE_RWX;
+
+
+
+
+
+ }
+ log.debug("user:"+user);
+ log.debug("getAccessPrivilege:rtn:"+rtn);
+ String superuser=(String)getRequest().getSession().getAttribute(Constant.SESSION_LOGGED_SUPERUSER);
+ if(superuser!=null && !superuser.equals("")){
+ rtn=ACCESS_PRIVILEGE_RWX;
+ }
+ if(rtn.equals("")) rtn=null;
+ return rtn;
+ }
+
+
+
+ /**
+ * @deprecated
+ * @param notity_tags
+ * @param sdb
+ * @return
+ * @throws Exception
+ */
+ protected ArrayList getNotifications(List notity_tags, AbstractTeamOrgDB sdb) throws Exception {
+
+ Map priv_data=getThemeHirarchy(notity_tags,sdb);
+ ArrayList user_notification=new ArrayList();
+
+ for(Iterator i=priv_data.keySet().iterator();i.hasNext();){
+ String ky=i.next();
+ if(priv_data.get(ky)!=null && priv_data.get(ky).equalsIgnoreCase("rwx")){
+ user_notification.add(ky);
+ }
+ }
+ return user_notification;
+ }
+
+
+
+
+
+
+ /**
+ *
+ * @param sdb
+ * @return
+ * @throws Exception
+ */
+ protected boolean isAuthorizedUser(SchedulerDB sdb) throws Exception {
+
+ String user=getAuthenticatedUser();
+ if(user!=null){
+ Map u=sdb.getSVNUser4WikiUser(user);
+ if(u!=null && u.get("svn_username")!=null && u.get("svn_password")!=null
+ && !((String)u.get("svn_username")).equals("") && !((String)u.get("svn_password")).equals("")
+ ){
+ return true;
+ }else{
+ return false;
+ }
+ }else{
+ return false;
+ }
+ }
+
+ /**
+ *
+ * @param sdb
+ * @return
+ * @throws Exception
+ */
+ protected String getAuthorizedUser(SchedulerDB sdb) throws Exception {
+
+ String user=getAuthenticatedUser();
+ log.debug("getAuthorizedUser() user:"+user);
+ if(user!=null){
+ Map u=sdb.getSVNUser4WikiUser(user);
+ if(u!=null && u.get("svn_username")!=null && u.get("svn_password")!=null
+ && !((String)u.get("svn_username")).equals("") && !((String)u.get("svn_password")).equals("")
+ ){
+ return (String)u.get("svn_username");
+ }else{
+ return null;
+ }
+ }else{
+ return null;
+ }
+ }
+
+
+ /**
+ *
+ * @param scheduler_id
+ * @param sdb
+ * @return
+ * @throws Exception
+ */
+
+ protected Map getItemTags2(int scheduler_id,AbstractTeamOrgDB sdb) throws Exception {
+
+ //SchedulerDB sdb=SchedulerDB.getSchedulerDB();
+
+ //try{
+ HashMap h=new HashMap();
+ Vector tagids=sdb.getTagIds4Item(scheduler_id);
+ Vector tags=sdb.getTags();
+ Vector follow_tagids=sdb.getFollowTagIds4Item(scheduler_id);
+
+ ArrayList themes=sdb.getThemeNames4Item(scheduler_id);
+ //Vector followers=sdb.getFollowers(scheduler_id);
+
+
+ Map priv_data=getThemeHirarchy(themes,sdb);
+ if(priv_data.get("theme")!=null){
+ priv_data.remove("theme");
+ }
+
+ List ftags=sdb.getFollowTags4Item(scheduler_id);
+ List user_notifications=ftags.size()>0?getNotifications(ftags,sdb):new ArrayList();
+ ArrayList all=new ArrayList(ftags);
+ all.addAll(themes);
+
+ h.put("tagids", tagids);
+ h.put("user_privileges",priv_data);
+ h.put("user_notifications",user_notifications);
+ h.put("follow_tagids",follow_tagids);
+ h.put("notice_escalated", getThemeHirarchy(all,sdb));
+ h.put("tags", tags);
+ h.putAll(priv_data);
+ return h;
+ }
+
+
+ /**
+ *
+ * @param item_id
+ * @param newtask_tags
+ * @param follow_tags
+ * @param atodb
+ * @param sdb
+ * @param name
+ * @param comment
+ * @param rev
+ * @param diff
+ * @param tempdata
+ * @param templ_file
+ * @throws Exception
+ */
+ protected void updateAllItemTags(int item_id, List newtask_tags,List follow_tags,AbstractTeamOrgDB atodb,SchedulerDB sdb,String name, String comment,long rev,String diff, Map tempdata, String templ_file) throws Exception {
+
+ ArrayList ids=new ArrayList();
+ for(Iterator i=newtask_tags.iterator();i.hasNext();){
+ String tid=(String)i.next();
+ ids.add(Integer.parseInt(tid));
+ }
+ atodb.updateItemTagIds(item_id, ids);
+ String owner_tag=null;
+ if(ids.size()>0){
+ owner_tag=atodb.getThemeTagName(ids.get(0));
+ }
+ ArrayList fids=new ArrayList();
+ for(Iterator i=follow_tags.iterator();i.hasNext();){
+ String tid=(String)i.next();
+ fids.add(Integer.parseInt(tid));
+ }
+ atodb.updateFollwerTagIds(item_id, fids);
+
+
+ }
+
+
+
+
+
+ protected Map getItemPrivilegeNotifications(ArrayList themes,ArrayList ftags,AbstractTeamOrgDB sdb) throws Exception {
+
+
+ Map priv_data=getThemeHirarchy(themes,sdb);
+ HashMap h=new HashMap();
+
+ ArrayList all=new ArrayList(ftags);
+ all.addAll(themes);
+ List user_notifications=getNotifications(all,sdb);
+ h.put("user_notifications",user_notifications);
+ h.put("user_privileges",priv_data);
+ h.put("notice_escalated",getThemeHirarchy(all,sdb));
+
+ return h;
+
+ }
+}
\ No newline at end of file
diff --git a/Examples/qlib/src/main/java/com/fourelementscapital/rfunction/common/RFunctionMgmt.java b/Examples/qlib/src/main/java/com/fourelementscapital/rfunction/common/RFunctionMgmt.java
new file mode 100755
index 0000000..d72a247
--- /dev/null
+++ b/Examples/qlib/src/main/java/com/fourelementscapital/rfunction/common/RFunctionMgmt.java
@@ -0,0 +1,164 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.rfunction.common;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+import javax.servlet.http.HttpServletRequest;
+import org.apache.commons.jcs.JCS;
+import org.apache.commons.jcs.access.CacheAccess;
+import org.apache.commons.jcs.engine.behavior.IElementAttributes;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import com.fourelementscapital.db.RFunctionDB;
+import com.fourelementscapital.db.SchedulerDB;
+import com.fourelementscapital.db.vo.ValueObject;
+
+
+/**
+ * This class exposes data to R function editor in Ajax call
+ * Remember all methods in the class are required user to be logged in
+ */
+@SuppressWarnings("unchecked")
+public class RFunctionMgmt extends AbstractTeamOrgMgmt {
+
+ private HttpServletRequest request=null;
+ private Logger log = LogManager.getLogger(RFunctionMgmt.class.getName());
+ private static CacheAccess lockcache=null;
+ private String cache_packaged_key="packaged_functions";
+ public static String RFUNCTION_FILE_EXTENSION=".r";
+
+ private static String FUNCTION_ID="function_id";
+ private static String LOCK_DURATION="duration";
+ private static String USER="user";
+
+ /**
+ * DWR invocation
+ * @throws Exception
+ */
+ public RFunctionMgmt() throws Exception {
+ super();
+ }
+
+ /**
+ * JSP or internal invocation
+ * @param request
+ * @throws Exception
+ */
+ public RFunctionMgmt(HttpServletRequest request) throws Exception {
+ super(request);
+
+ }
+
+ /**
+ * JCS caching for speed data retrival and not necessary to hit the database for every user.
+ * @return
+ * @throws Exception
+ */
+ private static CacheAccess getLockCache() throws Exception {
+ if(RFunctionMgmt.lockcache==null) RFunctionMgmt.lockcache=JCS.getInstance("lock-cache");
+ return RFunctionMgmt.lockcache;
+ }
+
+ /**
+ * Locking r function while a user is editing
+ * @param function_id
+ * @param seconds
+ * @return
+ * @throws Exception
+ */
+ public boolean lockFunction(int function_id, long seconds) throws Exception {
+ SchedulerDB sdb=SchedulerDB.getSchedulerDB();
+ RFunctionDB rfdb=RFunctionDB .getRFunctionDB();
+ try{
+ sdb.connectDB();
+ rfdb.connectDB();
+ String usr=new SchedulerMgmt(getRequest()).getAuthorizedUser(sdb);
+ if(seconds>0){
+ refreshCache(function_id, seconds,usr);
+ }else{
+ rfdb.updateLock(function_id, usr);
+ }
+ return true;
+ }catch(Exception e){
+
+ throw e;
+ }finally{
+ sdb.closeDB();
+ rfdb.closeDB();
+ }
+
+ }
+
+
+ private void removeLockFromCache(int function_id, String usr ) throws Exception {
+ //String ky=usr+"_"+function_id;
+ String ky=usr+function_id;
+ if(getLockCache().get(ky)!=null)getLockCache().remove(ky);
+ }
+
+ private void refreshCache(int function_id, long seconds, String usr ) throws Exception {
+
+ //String ky=usr+"_"+function_id;
+ String ky=usr+function_id;
+ HashMap h=new HashMap();
+ h.put(RFunctionMgmt.FUNCTION_ID, function_id);
+ h.put(RFunctionMgmt.LOCK_DURATION, seconds);
+ h.put(RFunctionMgmt.USER, usr);
+
+ IElementAttributes att= getLockCache().getDefaultElementAttributes();
+ att.setMaxLife(seconds);
+ if(getLockCache().get(ky)!=null)getLockCache().remove(ky);
+ getLockCache().put(ky,h,att);
+ }
+
+
+ /**
+ * return data for folder generation.
+ * @return
+ * @throws Exception
+ */
+ public Map getFolderTree() throws Exception {
+
+ RFunctionDB rfdb=RFunctionDB.getRFunctionDB();
+
+ try{
+ HashMap rtn=new HashMap();
+
+ rfdb.connectDB();
+ List glist=rfdb.listFunctionGroups();
+ List folders=rfdb.listOfFolders();
+
+ //TreeMap groups=new TreeMap();
+ Vector groups=new Vector();
+
+ for(Iterator it=glist.iterator();it.hasNext();){
+ Map data=(Map)it.next();
+ //groups.put(data.get("group_uid"),data.get("group_name"));
+
+ ValueObject vo=new ValueObject();
+ vo.setKey((String)data.get("group_uid"));
+ vo.setValue((String)data.get("group_name"));
+ groups.add(vo);
+ }
+ rtn.put("folders", folders);
+ rtn.put("groups",groups);
+
+ return rtn;
+
+
+ }catch(Exception e){
+ throw e;
+ }finally{
+
+ }
+ }
+}
\ No newline at end of file
diff --git a/Examples/qlib/src/main/java/com/fourelementscapital/rfunction/common/SchedulerMgmt.java b/Examples/qlib/src/main/java/com/fourelementscapital/rfunction/common/SchedulerMgmt.java
new file mode 100755
index 0000000..e09415c
--- /dev/null
+++ b/Examples/qlib/src/main/java/com/fourelementscapital/rfunction/common/SchedulerMgmt.java
@@ -0,0 +1,46 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.rfunction.common;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+@SuppressWarnings("unchecked")
+public class SchedulerMgmt extends AbstractTeamOrgMgmt {
+
+ private Logger log = LogManager.getLogger(SchedulerMgmt.class.getName());
+ private HttpServletRequest request=null;
+ private static String USER="user";
+
+ /**
+ * for DWR invocation
+ * @throws Exception
+ */
+ public SchedulerMgmt() throws Exception {
+ super();
+
+ }
+
+ /**
+ * Invocation only when you have HttpRequest is available,
+ * in JSP or internally.
+ * @param request
+ * @throws Exception
+ */
+ public SchedulerMgmt(HttpServletRequest request) throws Exception {
+ super(request);
+
+ }
+
+ protected String getPeerIPAddress() throws Exception {
+ String rtn=(String) getRequest().getSession().getAttribute(REMOTE_IP);
+ return rtn;
+ }
+}
\ No newline at end of file
diff --git a/README.md b/README.md
index f781ca9..a1a58b5 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,4 @@
# scheduler4e-javalibs
-This is the repository of javalibs required by the scheduler4e project.
\ No newline at end of file
+This is the repository of javalibs required by the scheduler4e project.
+JavaLibs that is being used by scheduler4e. This is based on JavaLibs 2.0 plus some minor changes including build flags with target and source optimized for JDK 1.8
diff --git a/archetype-app/pom.xml b/archetype-app/pom.xml
new file mode 100755
index 0000000..db64abb
--- /dev/null
+++ b/archetype-app/pom.xml
@@ -0,0 +1,26 @@
+
+ 4.0.0
+
+
+ com.fourelementscapital
+ lib
+ ${revision}
+
+
+ com.fourelementscapital
+ archetype-app
+ maven-archetype
+ archetype-app
+ A fourelementscapital archetype as the basis of building a four elements capital application
+ http://www.fourelementscapital.com
+
+
+
+ org.apache.maven.archetype
+ archetype-packaging
+ 2.2
+
+
+
+
diff --git a/archetype-app/src/main/resources/META-INF/maven/archetype-metadata.xml b/archetype-app/src/main/resources/META-INF/maven/archetype-metadata.xml
new file mode 100755
index 0000000..5850659
--- /dev/null
+++ b/archetype-app/src/main/resources/META-INF/maven/archetype-metadata.xml
@@ -0,0 +1,36 @@
+
+
+
+ src/main/java
+
+ **/*.java
+
+
+
+ src/main/resources
+
+ **/*.*
+
+
+
+ src/test/java
+
+ **/*.java
+
+
+
+
+
+ 1.0
+
+
+ com.fourelementscapital
+
+
+ com.fourelementscapital.${artifactId}
+
+
+
diff --git a/archetype-app/src/main/resources/archetype-resources/pom.xml b/archetype-app/src/main/resources/archetype-resources/pom.xml
new file mode 100755
index 0000000..3d0fd21
--- /dev/null
+++ b/archetype-app/src/main/resources/archetype-resources/pom.xml
@@ -0,0 +1,149 @@
+
+ 4.0.0
+ ${groupId}
+ ${artifactId}
+ ${version}
+ jar
+ ${artifactId}
+ http://www.fourelementscapital.com
+
+
+
+
+ maven-shade-plugin
+ 2.3
+
+
+ package
+
+ shade
+
+
+
+
+ ${package}.App
+
+
+ false
+
+
+ *:*
+
+ META-INF/*.SF
+ META-INF/*.DSA
+ META-INF/*.RSA
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-site-plugin
+ 3.5.1
+
+
+ attach-javadocs
+ package
+
+ site
+ stage
+
+
+
+
+
+
+
+
+
+ ${artifactId}
+ ${artifactId}
+ http://www.fourelementscapital.com
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ 2.10.4
+
+
+
+
+ aggregate
+ true
+
+
+
+ javadoc
+ test-javadoc
+
+
+
+
+
+
+
+
+
+ junit
+ junit
+ 3.8.1
+ test
+
+
+ org.apache.logging.log4j
+ log4j-core
+ 2.8.1
+
+
+
+ com.fourelementscapital
+ lib-alarm
+ 2.0
+
+
+ com.fourelementscapital
+ lib-auth
+ 2.0
+
+
+ com.fourelementscapital
+ lib-db
+ 2.0
+
+
+ com.fourelementscapital
+ lib-fileutils
+ 2.0
+
+
+ com.fourelementscapital
+ lib-r
+ 2.0
+
+
+ com.fourelementscapital
+ lib-socket
+ 2.0
+
+
+ com.fourelementscapital
+ lib-tts
+ 2.0
+
+
+ com.fourelementscapital
+ lib-imonitor
+ 2.0
+
+
+
+
+
\ No newline at end of file
diff --git a/archetype-app/src/main/resources/archetype-resources/src/main/java/App.java b/archetype-app/src/main/resources/archetype-resources/src/main/java/App.java
new file mode 100755
index 0000000..70de889
--- /dev/null
+++ b/archetype-app/src/main/resources/archetype-resources/src/main/java/App.java
@@ -0,0 +1,26 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package ${package};
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+
+/**
+ * A com.fourelementscapital Class
+ */
+public class App {
+
+ private static final Logger log = LogManager.getLogger(App.class.getName());
+
+ public static void main( String[] args )
+ {
+ log.debug( "Hello Four Elements Capital !" );
+ }
+}
+
diff --git a/archetype-app/src/main/resources/archetype-resources/src/main/resources/log4j2.xml b/archetype-app/src/main/resources/archetype-resources/src/main/resources/log4j2.xml
new file mode 100755
index 0000000..304acc5
--- /dev/null
+++ b/archetype-app/src/main/resources/archetype-resources/src/main/resources/log4j2.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/archetype-app/src/main/resources/archetype-resources/src/test/java/AppTest.java b/archetype-app/src/main/resources/archetype-resources/src/test/java/AppTest.java
new file mode 100755
index 0000000..0f1eee7
--- /dev/null
+++ b/archetype-app/src/main/resources/archetype-resources/src/test/java/AppTest.java
@@ -0,0 +1,47 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package ${package};
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+/**
+ * Unit test for App
+ */
+public class AppTest extends TestCase {
+
+ /**
+ * Create the test case
+ *
+ * @param testName name of the test case
+ */
+ public AppTest( String testName )
+ {
+ super( testName );
+ }
+
+ /**
+ * @return the suite of tests being tested
+ */
+ public static Test suite()
+ {
+ return new TestSuite( AppTest.class );
+ }
+
+ /**
+ * Empty Test
+ */
+ public void testApp()
+ {
+ assertTrue( true );
+ }
+
+}
+
+
diff --git a/archetype-lib/pom.xml b/archetype-lib/pom.xml
new file mode 100755
index 0000000..ac0c240
--- /dev/null
+++ b/archetype-lib/pom.xml
@@ -0,0 +1,26 @@
+
+ 4.0.0
+
+
+ com.fourelementscapital
+ lib
+ ${revision}
+
+
+ com.fourelementscapital
+ archetype-lib
+ maven-archetype
+ archetype-lib
+ A fourelementscapital archetype as the basis of creating a com.fourelementscapital library / jar file
+ http://www.fourelementscapital.com
+
+
+
+ org.apache.maven.archetype
+ archetype-packaging
+ 2.2
+
+
+
+
diff --git a/archetype-lib/src/main/resources/META-INF/maven/archetype-metadata.xml b/archetype-lib/src/main/resources/META-INF/maven/archetype-metadata.xml
new file mode 100755
index 0000000..fc217d6
--- /dev/null
+++ b/archetype-lib/src/main/resources/META-INF/maven/archetype-metadata.xml
@@ -0,0 +1,30 @@
+
+
+
+ src/main/java
+
+ **/*.java
+
+
+
+ src/test/java
+
+ **/*.java
+
+
+
+
+
+ 1.0
+
+
+ com.fourelementscapital
+
+
+ com.fourelementscapital.${artifactId}
+
+
+
\ No newline at end of file
diff --git a/archetype-lib/src/main/resources/archetype-resources/pom.xml b/archetype-lib/src/main/resources/archetype-resources/pom.xml
new file mode 100755
index 0000000..d9fe5d5
--- /dev/null
+++ b/archetype-lib/src/main/resources/archetype-resources/pom.xml
@@ -0,0 +1,119 @@
+
+ 4.0.0
+ ${groupId}
+ ${artifactId}
+ ${version}
+ jar
+ ${artifactId}
+ http://www.fourelementscapital.com
+
+
+
+
+ org.apache.maven.plugins
+ maven-site-plugin
+ 3.5.1
+
+
+ attach-javadocs
+ package
+
+ site
+ stage
+
+
+
+
+
+
+
+
+
+ ${artifactId}
+ ${artifactId}
+ http://www.fourelementscapital.com
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ 2.10.4
+
+
+
+
+ aggregate
+ true
+
+
+
+ javadoc
+ test-javadoc
+
+
+
+
+
+
+
+
+
+ junit
+ junit
+ 3.8.1
+ test
+
+
+ org.apache.logging.log4j
+ log4j-core
+ 2.8.1
+
+
+
+ com.fourelementscapital
+ lib-alarm
+ 2.0
+
+
+ com.fourelementscapital
+ lib-auth
+ 2.0
+
+
+ com.fourelementscapital
+ lib-db
+ 2.0
+
+
+ com.fourelementscapital
+ lib-fileutils
+ 2.0
+
+
+ com.fourelementscapital
+ lib-r
+ 2.0
+
+
+ com.fourelementscapital
+ lib-socket
+ 2.0
+
+
+ com.fourelementscapital
+ lib-tts
+ 2.0
+
+
+ com.fourelementscapital
+ lib-imonitor
+ 2.0
+
+
+
+
+
\ No newline at end of file
diff --git a/archetype-lib/src/main/resources/archetype-resources/src/main/java/App.java b/archetype-lib/src/main/resources/archetype-resources/src/main/java/App.java
new file mode 100755
index 0000000..1823620
--- /dev/null
+++ b/archetype-lib/src/main/resources/archetype-resources/src/main/java/App.java
@@ -0,0 +1,22 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package ${package};
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+/**
+ * A com.fourelementscapital Class
+ */
+public class App {
+
+ private static final Logger log = LogManager.getLogger(App.class.getName());
+
+}
+
+
\ No newline at end of file
diff --git a/archetype-lib/src/main/resources/archetype-resources/src/test/java/AppTest.java b/archetype-lib/src/main/resources/archetype-resources/src/test/java/AppTest.java
new file mode 100755
index 0000000..9c6830f
--- /dev/null
+++ b/archetype-lib/src/main/resources/archetype-resources/src/test/java/AppTest.java
@@ -0,0 +1,46 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package ${package};
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+/**
+ * Unit test for App
+ */
+public class AppTest extends TestCase {
+
+ /**
+ * Create the test case
+ *
+ * @param testName name of the test case
+ */
+ public AppTest( String testName )
+ {
+ super( testName );
+ }
+
+ /**
+ * @return the suite of tests being tested
+ */
+ public static Test suite()
+ {
+ return new TestSuite( AppTest.class );
+ }
+
+ /**
+ * Empty Test
+ */
+ public void testApp()
+ {
+ assertTrue( true );
+ }
+
+}
+
diff --git a/archetype-webapp/pom.xml b/archetype-webapp/pom.xml
new file mode 100755
index 0000000..3bce3a5
--- /dev/null
+++ b/archetype-webapp/pom.xml
@@ -0,0 +1,26 @@
+
+ 4.0.0
+
+
+ com.fourelementscapital
+ lib
+ ${revision}
+
+
+ com.fourelementscapital
+ archetype-webapp
+ maven-archetype
+ archetype-webapp
+ A fourelementscapital archetype as the basis of building a four elements capital web application
+ http://www.fourelementscapital.com
+
+
+
+ org.apache.maven.archetype
+ archetype-packaging
+ 2.2
+
+
+
+
diff --git a/archetype-webapp/src/main/resources/META-INF/maven/archetype-metadata.xml b/archetype-webapp/src/main/resources/META-INF/maven/archetype-metadata.xml
new file mode 100755
index 0000000..6d14eb0
--- /dev/null
+++ b/archetype-webapp/src/main/resources/META-INF/maven/archetype-metadata.xml
@@ -0,0 +1,36 @@
+
+
+
+ src/main/java
+
+ **/*.java
+
+
+
+ src/main/webapp
+
+ **/*.*
+
+
+
+ src/main/resources
+
+ **/*.*
+
+
+
+
+
+ 1.0
+
+
+ com.fourelementscapital
+
+
+ com.fourelementscapital.${artifactId}
+
+
+
diff --git a/archetype-webapp/src/main/resources/archetype-resources/pom.xml b/archetype-webapp/src/main/resources/archetype-resources/pom.xml
new file mode 100755
index 0000000..a350232
--- /dev/null
+++ b/archetype-webapp/src/main/resources/archetype-resources/pom.xml
@@ -0,0 +1,125 @@
+
+ 4.0.0
+ ${groupId}
+ ${artifactId}
+ ${version}
+ war
+ ${artifactId}
+ http://www.fourelementscapital.com
+
+
+ ${artifactId}
+
+
+ org.apache.maven.plugins
+ maven-site-plugin
+ 3.5.1
+
+
+ attach-javadocs
+ package
+
+ site
+ stage
+
+
+
+
+
+
+
+
+
+ ${artifactId}
+ ${artifactId}
+ http://www.fourelementscapital.com
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ 2.10.4
+
+
+
+
+ aggregate
+ true
+
+
+
+ javadoc
+ test-javadoc
+
+
+
+
+
+
+
+
+
+ junit
+ junit
+ 3.8.1
+ test
+
+
+ javax.servlet
+ servlet-api
+ 2.5
+
+
+ org.apache.logging.log4j
+ log4j-core
+ 2.8.1
+
+
+
+ com.fourelementscapital
+ lib-alarm
+ 2.0
+
+
+ com.fourelementscapital
+ lib-auth
+ 2.0
+
+
+ com.fourelementscapital
+ lib-db
+ 2.0
+
+
+ com.fourelementscapital
+ lib-fileutils
+ 2.0
+
+
+ com.fourelementscapital
+ lib-r
+ 2.0
+
+
+ com.fourelementscapital
+ lib-socket
+ 2.0
+
+
+ com.fourelementscapital
+ lib-tts
+ 2.0
+
+
+ com.fourelementscapital
+ lib-imonitor
+ 2.0
+
+
+
+
+
\ No newline at end of file
diff --git a/archetype-webapp/src/main/resources/archetype-resources/src/main/java/servlet/HelloServlet.java b/archetype-webapp/src/main/resources/archetype-resources/src/main/java/servlet/HelloServlet.java
new file mode 100755
index 0000000..18e11f8
--- /dev/null
+++ b/archetype-webapp/src/main/resources/archetype-resources/src/main/java/servlet/HelloServlet.java
@@ -0,0 +1,39 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package ${package}.servlet;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+public class HelloServlet extends HttpServlet {
+
+ private Logger log = LogManager.getLogger(HelloServlet.class.getName());
+
+ protected void doGet(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+
+ String str = "Hello four elements capital !";
+
+ log.debug(">>> String result : " + str);
+
+ PrintWriter out = response.getWriter();
+ out.println(str);
+ out.close();
+ }
+
+}
+
+
\ No newline at end of file
diff --git a/archetype-webapp/src/main/resources/archetype-resources/src/main/resources/log4j2.xml b/archetype-webapp/src/main/resources/archetype-resources/src/main/resources/log4j2.xml
new file mode 100755
index 0000000..304acc5
--- /dev/null
+++ b/archetype-webapp/src/main/resources/archetype-resources/src/main/resources/log4j2.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/archetype-webapp/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/web.xml b/archetype-webapp/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/web.xml
new file mode 100755
index 0000000..28535d0
--- /dev/null
+++ b/archetype-webapp/src/main/resources/archetype-resources/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,22 @@
+
+
+
+ Four Elements Capital Web Application
+
+ This is a simple web application.
+
+
+
+ hello
+ ${package}.servlet.HelloServlet
+
+
+
+ hello
+ /hello
+
+
+
\ No newline at end of file
diff --git a/archetype-webapp/src/main/resources/archetype-resources/src/main/webapp/index.jsp b/archetype-webapp/src/main/resources/archetype-resources/src/main/webapp/index.jsp
new file mode 100755
index 0000000..0eb001e
--- /dev/null
+++ b/archetype-webapp/src/main/resources/archetype-resources/src/main/webapp/index.jsp
@@ -0,0 +1 @@
+
diff --git a/lib-alarm/pom.xml b/lib-alarm/pom.xml
new file mode 100755
index 0000000..18d7974
--- /dev/null
+++ b/lib-alarm/pom.xml
@@ -0,0 +1,29 @@
+
+ 4.0.0
+
+
+ com.fourelementscapital
+ lib
+ ${revision}
+
+
+ com.fourelementscapital
+ lib-alarm
+ jar
+ lib-alarm
+ Alarm functions, call iMonitor API
+ http://www.fourelementscapital.com
+
+
+
+ commons-httpclient
+ commons-httpclient
+
+
+ org.apache.logging.log4j
+ log4j-api
+
+
+
+
diff --git a/lib-alarm/src/main/java/com/fourelementscapital/alarm/Alarm.java b/lib-alarm/src/main/java/com/fourelementscapital/alarm/Alarm.java
new file mode 100755
index 0000000..24169c6
--- /dev/null
+++ b/lib-alarm/src/main/java/com/fourelementscapital/alarm/Alarm.java
@@ -0,0 +1,300 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.alarm;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.net.Socket;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Properties;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.StringRequestEntity;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+/**
+ * Send alarm to iMonitor API
+ */
+public class Alarm {
+
+ private static final Logger log = LogManager.getLogger(Alarm.class.getName());
+
+ /**
+ * Private constructor
+ */
+ private Alarm(){}
+
+
+ /**
+ * Construct alarm message with default parameters and send it to iMonitor API
+ * @param themes ThemeVO array list
+ * @param alarm_type Alarm type
+ * @param subject Subject
+ * @param message Message
+ * @param say Is Say
+ * @param email Is Email
+ * @param phone Is Phone
+ * @param attachmentfile Attachment file
+ * @param exc_add Exclude Address
+ * @throws IOException
+ */
+ public static void sendAlarm(ArrayList themes, AlarmType alarm_type,String subject,String message, boolean say, boolean email, boolean phone, String attachmentfile,String exc_add) throws IOException {
+
+ if(themes!=null && themes.size()>0 && message!=null && alarm_type!=null){
+
+ // ignore alarm ? :
+ String c_noalarm=getConfigValue("ignore.alarm");
+ if(c_noalarm!=null && c_noalarm.equalsIgnoreCase("true")) {
+ //do nothing
+ }else{
+
+ //String xml=constructXMLWithFile(themes,subject,message,say,email,phone,attachmentfile,exc_add);
+ String socketMessage=constructSocketMessageWithFile(themes,subject,message,say,email,phone,attachmentfile,exc_add);
+ //log.debug("Sending alarm:xml:"+xml);
+ //log.debug("Sending alarm:socketMessage:"+socketMessage);
+
+ // check whether dump XML to file or send to iMonitor API :
+
+ boolean isDump = Boolean.parseBoolean(getConfigValue("alarm.dump"));
+
+ if (isDump) {
+ // create folder if not exist. format : 'yyyyMMdd' (today's date)
+ String dumpFolder = getConfigValue("alarm.dump.folder");
+ SimpleDateFormat sdfDumpFolder = new SimpleDateFormat("yyyyMMdd");
+ dumpFolder = dumpFolder + sdfDumpFolder.format(new Date()) + "/"; // setup today folder
+ File dir = new File(dumpFolder);
+ dir.mkdirs();
+
+ // write dump file. format : 'HHmmss.xml' (HHmmss : current time)
+ SimpleDateFormat sdfFile = new SimpleDateFormat("HHmmssSSS");
+ PrintWriter writer = new PrintWriter(dumpFolder + sdfFile.format(new Date()) + ".xml", "UTF-8");
+ //writer.println(xml);
+ //writer.println(socketMessage);
+ writer.close();
+ }
+ else {
+ //sendXML(xml); // send to iMonitor
+ sendSocketMessage(socketMessage); // send to iMonitor
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Send phone alarm with list of theme and a message
+ * @param themes ThemeVO array list
+ * @param message Message
+ * @throws IOException
+ */
+ public static void sendAlarm(ArrayList themes, String message) throws IOException {
+ Alarm.sendAlarm(themes,AlarmType.PHONE,null,message,false,false,true,null,null);
+ }
+
+
+ /**
+ * Send phone alarm with a theme and a message
+ * @param theme Theme
+ * @param message Message
+ * @throws IOException
+ */
+ public static void sendAlarm(String theme, String message) throws IOException {
+ ArrayList themes = new ArrayList();
+ themes.add(new ThemeVO(theme));
+ Alarm.sendAlarm(themes,AlarmType.PHONE,null,message,false,false,true,null,null);
+ }
+
+
+ /**
+ * Construct XML with file attachment
+ * @param themes Themes
+ * @param subject Subject
+ * @param bodymsg Body message
+ * @param say Is say
+ * @param email Is email alert
+ * @param phone Is phone alert
+ * @param attachment Attachment
+ * @param exc_add Exclude Address
+ * @return XML
+ */
+ private static String constructXMLWithFile(List themes,String subject,String bodymsg,boolean say,boolean email,boolean phone, String attachment,String exc_add) {
+ subject = escapeChar(subject);
+ String xml="";
+
+ for (int i=0; i"+themeVO.getName()+"";
+ }
+ }
+
+ xml+=""+subject+"";
+ xml+="";
+ xml+="m ";
+ xml+=""+(say+"").toUpperCase()+" ";
+ xml+=""+(email+"").toUpperCase()+"";
+ xml+=""+(phone+"").toUpperCase()+"";
+ xml+="5";
+ xml+="15";
+ if(attachment!=null){
+ xml+=""+attachment+"";
+ }
+ if(exc_add!=null){
+ xml+=""+exc_add+"";
+ }
+ xml+="";
+ return xml;
+ }
+
+ /**
+ * Construct message with file attachment
+ * @param themes Themes
+ * @param subject Subject
+ * @param bodymsg Body message
+ * @param say Is say
+ * @param email Is email
+ * @param phone Is phone
+ * @param attachment Attachment
+ * @param exc_add Exclude Address
+ * @return XML
+ */
+ private static String constructSocketMessageWithFile(List themes,String subject,String bodymsg,boolean say,boolean email,boolean phone, String attachment,String exc_add) {
+ subject = escapeChar(subject);
+
+ String message = "";
+ for (int i=0; i";
+
+ // remove first char : '~'
+ message=message.substring(1, message.length());
+
+ /*
+ xml+="m ";
+ xml+="5";
+ xml+="15";
+ if(attachment!=null){
+ xml+=""+attachment+"";
+ }
+ if(exc_add!=null){
+ xml+=""+exc_add+"";
+ }
+ */
+
+ return message;
+ }
+
+ /**
+ * Send XML to iMonitor API
+ * @param xml XML
+ * @throws IOException
+ */
+ private static void sendXML(String xml) throws IOException {
+ try{
+ String url=getConfigValue("imonitor.url");
+
+ PostMethod post = new PostMethod(url);
+ try {
+ post.setRequestEntity(new StringRequestEntity(xml,"text/xml",null ));
+ post.setRequestHeader("Content-type", "text/xml; utf-8");
+ HttpClient httpclient = new HttpClient();
+ int result = httpclient.executeMethod(post);
+ } catch (IOException e) {
+ // e.printStackTrace();
+ throw e;
+ } finally {
+ post.releaseConnection();
+ }
+ }catch(Exception e){
+ e.printStackTrace();
+ throw e;
+ }
+ }
+
+ /**
+ * Send message via Socket to iMonitor API
+ * @param message Message
+ * @throws Exception
+ */
+ private static void sendSocketMessage(String socketMessage) throws IOException {
+ String ip = getConfigValue("imonitor.ip");
+ int port = Integer.parseInt(getConfigValue("imonitor.port"));
+ Socket socket = new Socket(ip, port);
+ OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
+ osw.write(socketMessage, 0, socketMessage.length());
+ osw.flush();
+ socket.close();
+ }
+
+ /**
+ * Escape XML characters
+ * @param str String
+ * @return String with escape characters
+ */
+ private static String escapeChar(String str) {
+ String result = null;
+ if (str != null) {
+ result = str.replaceAll("&", "&");
+ result = result.replaceAll("\"", """);
+ result = result.replaceAll("'", "'");
+ result = result.replaceAll("<", "<");
+ result = result.replaceAll(">", ">");
+ }
+ return result;
+ }
+
+
+ /**
+ * Get the value of a property defined in config file
+ * @param propertyName - the name or key of the property you want to retrieve
+ * @return the string value
+ * @throws IOException
+ */
+ private static String getConfigValue(String propertyName) throws IOException
+ {
+ Properties prop = new Properties();
+ String propFileName = "config_alarm.properties";
+
+ InputStream inputStream = Alarm.class.getClassLoader().getResourceAsStream(propFileName);
+
+ if (inputStream != null) {
+ prop.load(inputStream);
+ } else {
+ throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
+ }
+
+ // get the property value and print it out
+ String value = prop.getProperty(propertyName);
+ return value;
+ }
+
+}
+
+
diff --git a/lib-alarm/src/main/java/com/fourelementscapital/alarm/AlarmType.java b/lib-alarm/src/main/java/com/fourelementscapital/alarm/AlarmType.java
new file mode 100755
index 0000000..6b89b1d
--- /dev/null
+++ b/lib-alarm/src/main/java/com/fourelementscapital/alarm/AlarmType.java
@@ -0,0 +1,17 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.alarm;
+
+/**
+ * Enumeration class for type of the Alarm
+ */
+public enum AlarmType {
+ EMAIL, PHONE
+}
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/java/com/fourelementscapital/alarm/ThemeVO.java b/lib-alarm/src/main/java/com/fourelementscapital/alarm/ThemeVO.java
new file mode 100755
index 0000000..3aede46
--- /dev/null
+++ b/lib-alarm/src/main/java/com/fourelementscapital/alarm/ThemeVO.java
@@ -0,0 +1,40 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.alarm;
+
+import java.io.Serializable;
+
+/**
+ * Theme Value Object to store theme name used by Alarm
+ */
+public class ThemeVO implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Theme name
+ */
+ private String name;
+
+ /**
+ * Constructor with name parameter
+ */
+ public ThemeVO(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+}
+
+
diff --git a/lib-alarm/src/main/resources/codehelp/2113.html b/lib-alarm/src/main/resources/codehelp/2113.html
new file mode 100755
index 0000000..4dfde30
--- /dev/null
+++ b/lib-alarm/src/main/resources/codehelp/2113.html
@@ -0,0 +1,7 @@
+
+
+ - Windows peer couldn't start Rserve
+ - Make sure there is only one tomcat and Rserve process in the peer
+ - Restart tomcat and Rserve
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/resources/codehelp/2214.html b/lib-alarm/src/main/resources/codehelp/2214.html
new file mode 100755
index 0000000..688a323
--- /dev/null
+++ b/lib-alarm/src/main/resources/codehelp/2214.html
@@ -0,0 +1,8 @@
+
+
+ - Peer connection pool for managing multiple RServe connections are not working properly
+ - On unix peer, this may happen when Rserve is not started
+ - On windows, Rserve port used by someother program
+
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/resources/codehelp/2220.html b/lib-alarm/src/main/resources/codehelp/2220.html
new file mode 100755
index 0000000..d8a7f91
--- /dev/null
+++ b/lib-alarm/src/main/resources/codehelp/2220.html
@@ -0,0 +1,5 @@
+
+
+ - This is uncategorized error due to certain Runtime error messages on peer or Rengine/Rserve
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/resources/codehelp/2311.html b/lib-alarm/src/main/resources/codehelp/2311.html
new file mode 100755
index 0000000..06ab17b
--- /dev/null
+++ b/lib-alarm/src/main/resources/codehelp/2311.html
@@ -0,0 +1,7 @@
+
+
+ - Null Error message by RServe/REngine at the end of execution of script. According to RForge documentation, it is classified as unknow and something went wrong, Check http://www.rforge.net/Rserve/faq.html for more info
+ - Your script might not be reached end and could have been Runtime error in the middle
+ - Try running your script with low memory usage settings on your R
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/resources/codehelp/2312.html b/lib-alarm/src/main/resources/codehelp/2312.html
new file mode 100755
index 0000000..1cf2c0f
--- /dev/null
+++ b/lib-alarm/src/main/resources/codehelp/2312.html
@@ -0,0 +1,6 @@
+
+
+ - R script thrown Runtime exception
+ - Make sure runtime exceptions from Database,Network and File resources are caught and written in console
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/resources/codehelp/2315.html b/lib-alarm/src/main/resources/codehelp/2315.html
new file mode 100755
index 0000000..d9f20f7
--- /dev/null
+++ b/lib-alarm/src/main/resources/codehelp/2315.html
@@ -0,0 +1,8 @@
+
+
+ - If the script is taking more than specified time, then it will be removed from the queue not matter eventually successful or failure
+ - Consider increasing execution time out by clicking speaker icon above the live queue of the scheduler
+ - Code modified and the new code consumes more time than previous executions
+ - This will also happen when peer restarted or stopped while task is running
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/resources/codehelp/2316.html b/lib-alarm/src/main/resources/codehelp/2316.html
new file mode 100755
index 0000000..fdebe49
--- /dev/null
+++ b/lib-alarm/src/main/resources/codehelp/2316.html
@@ -0,0 +1,7 @@
+
+
+ - The task still in the queue because peer couldn't reach server to update the status of task and server removes it as later found no longer running in peer
+ - Peer was running memory intensive script or unix peer Rserve threads were fully utilized at that time
+ - Please check the queue history later to know the final status of the execution
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/resources/codehelp/2317.html b/lib-alarm/src/main/resources/codehelp/2317.html
new file mode 100755
index 0000000..0e788bb
--- /dev/null
+++ b/lib-alarm/src/main/resources/codehelp/2317.html
@@ -0,0 +1,5 @@
+
+
+ - No Room to Execute the Script because peer receives 2 tasks at the same time and accepts only one and the other sent back to server and it will be resent to different peer
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/resources/codehelp/2318.html b/lib-alarm/src/main/resources/codehelp/2318.html
new file mode 100755
index 0000000..eca4f6e
--- /dev/null
+++ b/lib-alarm/src/main/resources/codehelp/2318.html
@@ -0,0 +1,6 @@
+
+
+ - Task removed because peer says it is no longer running in peer
+ - This can happen if peer restarted
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/resources/codehelp/2319.html b/lib-alarm/src/main/resources/codehelp/2319.html
new file mode 100755
index 0000000..5700b88
--- /dev/null
+++ b/lib-alarm/src/main/resources/codehelp/2319.html
@@ -0,0 +1,6 @@
+
+
+ - Any run time exception message at peer side, usually this will be thrown when if there was problem in database connectivity, unexpected value, unchecked null vale and so on
+ - Make sure runtime exceptions from Database,Network and File resources are caught and written in console
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/resources/codehelp/2320.html b/lib-alarm/src/main/resources/codehelp/2320.html
new file mode 100755
index 0000000..2d97ae2
--- /dev/null
+++ b/lib-alarm/src/main/resources/codehelp/2320.html
@@ -0,0 +1,6 @@
+
+
+ - Any runtime exception message on server side,usually this will be thrown when there is problem in database connectivity, unexpected value, unchecked null vale and so on.
+ - Make sure runtime exceptions from Database,Network and File resources are caught and written in console
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/resources/codehelp/2321.html b/lib-alarm/src/main/resources/codehelp/2321.html
new file mode 100755
index 0000000..64e7e4d
--- /dev/null
+++ b/lib-alarm/src/main/resources/codehelp/2321.html
@@ -0,0 +1,5 @@
+
+
+ - This will happen when the next trigger time of the script arrived and still current triggered execution is waiting because of one or more dependecies not successfull.
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/main/resources/config_alarm.properties b/lib-alarm/src/main/resources/config_alarm.properties
new file mode 100755
index 0000000..b20b7eb
--- /dev/null
+++ b/lib-alarm/src/main/resources/config_alarm.properties
@@ -0,0 +1,12 @@
+ignore.alarm=false
+
+#imonitor.url=http://10.153.64.31:5001/iMonitor/Responder.aspx
+imonitor.ip=127.0.0.1
+imonitor.port=1777
+
+#dump XML to file instead of sending it to iMonitor API
+alarm.dump=false
+#alarm.dump=true
+#alarm.dump.folder=/temp/scheduler-alarm/
+
+
diff --git a/lib-alarm/src/main/resources/log4j2.xml b/lib-alarm/src/main/resources/log4j2.xml
new file mode 100755
index 0000000..b8d69f3
--- /dev/null
+++ b/lib-alarm/src/main/resources/log4j2.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/lib-alarm/src/test/java/com/fourelementscapital/alarm/LibAlarmTest.java b/lib-alarm/src/test/java/com/fourelementscapital/alarm/LibAlarmTest.java
new file mode 100755
index 0000000..f087f18
--- /dev/null
+++ b/lib-alarm/src/test/java/com/fourelementscapital/alarm/LibAlarmTest.java
@@ -0,0 +1,54 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.alarm;
+
+import java.util.ArrayList;
+import javax.swing.JOptionPane;
+import junit.framework.TestCase;
+
+/**
+ * lib-alarm unit test
+ */
+public class LibAlarmTest extends TestCase {
+
+ /**
+ * Test send alarm
+ */
+ public void testSendAlarm()
+ {
+
+ try{
+
+ ArrayList themes=new ArrayList();
+ themes.add(new ThemeVO("computing"));
+ themes.add(new ThemeVO("etrading"));
+
+ // Remove the comment tag to test. The code are commented out to prevent sending alarm when installing this lib :
+
+ // send alarm (default) :
+ //Alarm.sendAlarm( themes, AlarmType.EMAIL, "Test subject", "Test message", false, true, false, null, null);
+
+ // send alarm with list of theme & a message :
+ //Alarm.sendAlarm( themes, "Test message 2");
+
+ // send alarm with a theme & a message :
+ //Alarm.sendAlarm( "computing", "Test message 3");
+ //JOptionPane.showMessageDialog(null, "send socket message done");
+ assertTrue(true);
+ }catch(Exception e){
+ e.printStackTrace();
+ assertTrue(false);
+ }
+
+ }
+
+
+}
+
+
+
diff --git a/lib-auth/pom.xml b/lib-auth/pom.xml
new file mode 100755
index 0000000..fef3166
--- /dev/null
+++ b/lib-auth/pom.xml
@@ -0,0 +1,42 @@
+
+
+ 4.0.0
+
+ com.fourelementscapital
+ lib
+ ${revision}
+
+ com.fourelementscapital
+ lib-auth
+ jar
+ lib-auth
+ Wiki authentication, Superuser authentication, Get user themes access permission
+ http://www.fourelementscapital.com
+
+
+ mysql
+ mysql-connector-java
+
+
+ javax.servlet
+ servlet-api
+
+
+ org.kohsuke
+ libpam4j
+
+
+ commons-codec
+ commons-codec
+
+
+ org.apache.logging.log4j
+ log4j-api
+
+
+
+
+UTF-8
+
+
diff --git a/lib-auth/src/main/java/com/fourelementscapital/auth/DBManager.java b/lib-auth/src/main/java/com/fourelementscapital/auth/DBManager.java
new file mode 100755
index 0000000..011b608
--- /dev/null
+++ b/lib-auth/src/main/java/com/fourelementscapital/auth/DBManager.java
@@ -0,0 +1,148 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.auth;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * The DBManager class provides an Access Interface between the Database and Java.
+ * It can be used to get data from the database, insert new data and update existing data.
+ * The config file containing the details for the database hostname and credentials is located in the resources folder.
+ */
+class DBManager {
+
+ /**
+ * The database name for the current instance of DBManager
+ */
+ private String dbName;
+
+ /**
+ * The connection string for the database connection. Stored in config file
+ */
+ private String connectionString;
+
+ /**
+ * The resultSet which contains the returned results from the SQL Query of GetDatabase
+ */
+ ResultSet resultSet = null;
+
+ /**
+ * The connection object of the current connection.
+ */
+ private Connection conn = null;
+
+ /**
+ * Initialize the DBManager with the database name.
+ * @param dbName The name of the database e.x. trading, tradingRef, fundamentals
+ * @throws IOException
+ */
+ public DBManager(String dbName) throws IOException
+ {
+ this.dbName = dbName;
+ }
+
+ /**
+ * This function connects to the dbName database;
+ * @throws SQLException This is thrown incase we are not able to connect to the database;
+ * @throws ClassNotFoundException This is thrown incase the driver is not found on this machine
+ * @throws IOException This is thrown incase the config file if not found on this machine under resources folder
+ */
+ public void connect() throws SQLException, ClassNotFoundException, IOException
+ {
+ //String url = "jdbc:jtds:sqlserver://"+databaseServerAddress+";DatabaseName="+databaseName;
+ String driver = Utils.GetConfigValue("database_"+dbName.toLowerCase()+"_"+"driver");
+
+ Class.forName(driver);
+ conn = DriverManager.getConnection(Utils.GetConfigValue("database_"+dbName.toLowerCase()+"_"+"connstring"));
+ connectionString = conn.toString();
+ }
+
+ /**
+ * Closes the current Database connection.
+ * @throws SQLException
+ */
+ public void closeConnection() throws SQLException
+ {
+ if(!conn.isClosed())
+ conn.close();
+ if(resultSet!=null)
+ resultSet.close();
+ }
+
+ /**
+ * This function returns the result set of the SQL Query used by GetDatabase;
+ * @param query The SQL Query passed to it.
+ * @return
+ * @throws SQLException
+ */
+ private ResultSet executeQuery(String query) throws SQLException
+ {
+ Date start = new Date();
+ Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
+ resultSet = statement.executeQuery(query);
+ Date end = new Date();
+ long duration = (end.getTime() - start.getTime());
+ //Utils.Log("DEBUG: Query ("+query+") took "+duration+ " miliseconds");
+ return resultSet;
+ }
+
+ /**
+ * Used to query a database and access the resultant data in a ResultSet
+ * @param tableName The name of the database table to be accessed
+ * @param selectedFields A list of the values to be selected through the queries. new ArrayList();
+ * be passed to select all fields (*)
+ * @param queryParams A hashmap containing the selection filters in the format [column_name]=[value]
+ * @param customQuery Any additional parameters to be added after the Where clause. Could be a GROUP BY or ORDER BY
+ * @return The resulting data in a ResultSet
+ * @throws SQLException
+ */
+ public ResultSet GetDatabase(String tableName,ArrayList selectedFields, Map queryParams, String customQuery) throws SQLException
+ {
+ String queryBuilder = "";
+ if(selectedFields.size()==0)
+ {
+ selectedFields.add("*");
+ }
+
+ queryBuilder += "SELECT "+Utils.Join(selectedFields,",")+" FROM "+tableName;
+
+ if(queryParams != null && queryParams.size()>0)
+ {
+ queryBuilder += " WHERE ";
+ for (Map.Entry entry : queryParams.entrySet()) {
+
+ try{
+ Float f = Float.parseFloat(entry.getValue().toString());
+ queryBuilder += " "+entry.getKey() + " = "+entry.getValue()+" AND";
+ }
+ catch(Exception ex)
+ {
+ queryBuilder += " "+entry.getKey() + " = '"+entry.getValue()+"' AND";
+ }
+
+ }
+ if(customQuery!= null && customQuery!="")
+ queryBuilder += customQuery+" AND";
+ queryBuilder = queryBuilder.substring(0,queryBuilder.length()-3);
+ }
+ //System.out.println(queryBuilder);
+ return executeQuery(queryBuilder);
+ }
+
+}
+
+
+
\ No newline at end of file
diff --git a/lib-auth/src/main/java/com/fourelementscapital/auth/PAMAuthentication.java b/lib-auth/src/main/java/com/fourelementscapital/auth/PAMAuthentication.java
new file mode 100755
index 0000000..440b213
--- /dev/null
+++ b/lib-auth/src/main/java/com/fourelementscapital/auth/PAMAuthentication.java
@@ -0,0 +1,126 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.auth;
+
+import java.util.Set;
+
+import org.jvnet.libpam.PAM;
+import org.jvnet.libpam.PAMException;
+import org.jvnet.libpam.UnixUser;
+
+/**
+ * PAMAuthentication will authenticate user to local unix machine using PAM.
+ * This class is a wrapper of libpam4j, a Java/PAM bindings using JNA, to use internally in 4ECaps.
+ */
+public class PAMAuthentication {
+
+ /**
+ * Check whether user is exist
+ * @param username Username
+ * @return true if user is exist
+ */
+ public static boolean isExist(String username) {
+ return UnixUser.exists(username);
+ }
+
+ /**
+ * Get current user logged in Unix system
+ * @return username of user logged in
+ */
+ public static String getCurrentUserLoggedIn() {
+ return System.getProperty("user.name");
+ }
+
+ /**
+ * Get username of current user logged in
+ * @return username of user logged in
+ * @throws PAMException
+ */
+ public static String getUsername() throws PAMException {
+ UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
+ return ux.getUserName();
+ }
+
+ /**
+ * Get UID of current user logged in
+ * @return UID of user logged in
+ * @throws PAMException
+ */
+ public static int getUID() throws PAMException {
+ UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
+ return ux.getUID();
+ }
+
+ /**
+ * Get GID of current user logged in
+ * @return GID of user logged in
+ * @throws PAMException
+ */
+ public static int getGID() throws PAMException {
+ UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
+ return ux.getGID();
+ }
+
+ /**
+ * Get gecos (the real name) of current user logged in
+ * @return gecos of user logged in
+ * @throws PAMException
+ */
+ public static String getGecos() throws PAMException {
+ UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
+ return ux.getGecos();
+ }
+
+ /**
+ * Get home directory of current user logged in
+ * @return home directory of user logged in
+ * @throws PAMException
+ */
+ public static String getDir() throws PAMException {
+ UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
+ return ux.getDir();
+ }
+
+ /**
+ * Get the shell of current user logged in
+ * @return the shell of user logged in
+ * @throws PAMException
+ */
+ public static String getShell() throws PAMException {
+ UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
+ return ux.getShell();
+ }
+
+ /**
+ * Get the groups that user logged in belongs to
+ * @return the groups of user logged in
+ * @throws PAMException
+ */
+ public static Set getGroups() throws PAMException {
+ UnixUser ux = new UnixUser(getCurrentUserLoggedIn());
+ return ux.getGroups();
+ }
+
+ /**
+ * Authenticate user
+ * @param service Service
+ * @param username Username
+ * @param password Password
+ * @return authenticated user in UnixUser object
+ * @throws PAMException
+ */
+ public static UnixUser authenticate(String service, String username, String password) throws PAMException {
+ PAM p = new PAM(service);
+ return p.authenticate(username, password);
+ }
+
+
+}
+
+
+
diff --git a/lib-auth/src/main/java/com/fourelementscapital/auth/SuperUserAuthentication.java b/lib-auth/src/main/java/com/fourelementscapital/auth/SuperUserAuthentication.java
new file mode 100755
index 0000000..c2e39b4
--- /dev/null
+++ b/lib-auth/src/main/java/com/fourelementscapital/auth/SuperUserAuthentication.java
@@ -0,0 +1,177 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.auth;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.security.MessageDigest;
+
+import org.apache.commons.codec.binary.Hex;
+
+/**
+ * SuperUserAuthentication provides mechanism to store password into a file.
+ * This mechanism is implemented in superuser authentication of an application.
+ * The config file containing the path of saved password located in the resources folder.
+ */
+public class SuperUserAuthentication {
+
+ /**
+ * Private constructor to prevent instantiation.
+ */
+ private SuperUserAuthentication()
+ {
+ }
+
+ /**
+ * Password filename that will be created in the folder path.
+ */
+ private static String passwordFilename = "superuser.pwd";
+
+
+ /**
+ * Validate password whether it equals with the encrypted file, if file is not exist then set the password by creating it.
+ * @param pwd Password
+ * @return true if process succeed
+ * @throws Exception
+ */
+ public static boolean validateOrSet(String pwd) throws Exception {
+ File file=getPwdFile();
+ String encpwd=null;
+ boolean rtn=false;
+ if(file.exists()){
+ encpwd=readFile(file);
+ }
+ if(encpwd!=null && !encpwd.equals("")){
+ rtn=isValid(pwd,encpwd);
+ }else{
+ setPassword(pwd);
+ rtn=true;
+ }
+ return rtn;
+ }
+
+
+ /**
+ * Change password to a new one if password is valid
+ * @param pwd Password
+ * @param newpassword New password
+ * @return true if process succeed
+ * @throws Exception
+ */
+ public static boolean changePwd(String pwd,String newpassword) throws Exception {
+ boolean rtn=validateOrSet(pwd);
+
+ if(rtn){
+ //Thread.sleep(1000); //wait till it closes the stream ....
+ setPassword(newpassword);
+ }
+ return rtn;
+ }
+
+
+ /**
+ * Check whether password is valid, compared to encrypted password
+ * @param password Password
+ * @param encpass Encrypted password
+ * @return true if encrypted password equals salt password
+ * @throws Exception
+ */
+ private static boolean isValid(String password, String encpass) throws Exception {
+ String salt=encpass.split(":")[2];
+ String saltpass=":B:"+salt+":"+getMD5(salt+"-"+getMD5(password));
+ if(encpass.equals(saltpass)){
+ return true;
+ }else{
+ return false;
+ }
+ }
+
+
+ /**
+ * Get MD5 of source string
+ * @param source Source string
+ * @return MD5 string
+ * @throws Exception
+ */
+ private static String getMD5(String source) throws Exception {
+
+ byte[] bytesOfMessage = source.getBytes();
+
+ java.security.MessageDigest md = MessageDigest.getInstance("MD5");
+ byte[] thedigest = md.digest(bytesOfMessage);
+
+ final String result = new String(Hex.encodeHex(thedigest));
+ return result;
+ }
+
+
+ /**
+ * Set password to encrypted file
+ * @param plain_pwd Plain password
+ * @throws Exception
+ */
+ private static void setPassword(String plain_pwd) throws Exception {
+ BufferedWriter writer = null;
+ try {
+ String salt="d1e93dec";
+ String saltpass=":B:"+salt+":"+getMD5(salt+"-"+getMD5(plain_pwd));
+ File file=getPwdFile();
+ writer = new BufferedWriter(new FileWriter(file));
+ writer.write(saltpass);
+ }
+ finally {
+ if (writer != null) writer.close();
+ }
+
+ }
+
+
+ /**
+ * Get password file
+ * @return file
+ * @throws Exception
+ */
+ private static File getPwdFile() throws Exception {
+ String root = Utils.GetConfigValue("superuser_password_folder");
+ File file =new File(root + passwordFilename);
+ if ( !file.exists() ) {
+ file.createNewFile();
+ }
+ return file;
+ }
+
+
+ /**
+ * Read file
+ * @param path Path file
+ * @throws IOException
+ */
+ private static String readFile(File path) throws IOException {
+ StringBuilder contents = new StringBuilder();
+ BufferedReader input = null;
+ try {
+ input = new BufferedReader(new FileReader(path));
+ String line = input.readLine();
+ if (line != null) {
+ contents.append(line);
+ }
+ }
+ finally {
+ if (input != null) input.close();
+ }
+ return contents.toString();
+ }
+
+}
+
+
+
\ No newline at end of file
diff --git a/lib-auth/src/main/java/com/fourelementscapital/auth/SystemAuthentication.java b/lib-auth/src/main/java/com/fourelementscapital/auth/SystemAuthentication.java
new file mode 100755
index 0000000..2a62feb
--- /dev/null
+++ b/lib-auth/src/main/java/com/fourelementscapital/auth/SystemAuthentication.java
@@ -0,0 +1,30 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.auth;
+
+public class SystemAuthentication {
+
+ /**
+ * Get current user logged in Unix system
+ * @return username of user logged in
+ */
+ public static String getCurrentUserLoggedIn() {
+ return System.getProperty("user.name");
+ }
+
+ /**
+ * Check whether a user logged in to the system
+ * @return true if user logged in
+ */
+ public static boolean isUserLoggedIn() {
+ return (null != getCurrentUserLoggedIn() && !"".equals(getCurrentUserLoggedIn()));
+ }
+
+}
+
+
\ No newline at end of file
diff --git a/lib-auth/src/main/java/com/fourelementscapital/auth/UserThemeAccessPermission.java b/lib-auth/src/main/java/com/fourelementscapital/auth/UserThemeAccessPermission.java
new file mode 100755
index 0000000..38267fa
--- /dev/null
+++ b/lib-auth/src/main/java/com/fourelementscapital/auth/UserThemeAccessPermission.java
@@ -0,0 +1,147 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.auth;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+
+/**
+ * UserThemeAccessPermission provides functions to convert theme access permissions into 'rwx' permission group.
+ * Example : a user has 'X' permission in 'computing' theme. The 'computing' theme then will be included in 'rwx' permission group.
+ * Another Example : a user has 'U' permission in 'etrading' theme. The 'etrading' theme then will be included in 'rx' permission group.
+ */
+public class UserThemeAccessPermission {
+
+ /**
+ * Username
+ */
+ private String username;
+
+ /**
+ * 'rwx' permission group
+ */
+ private ArrayList rwx = new ArrayList();
+
+ /**
+ * 'rx' permission group
+ */
+ private ArrayList rx = new ArrayList();
+
+ /**
+ * 'r' permission group
+ */
+ private ArrayList r = new ArrayList();
+
+
+ /**
+ * Constructor. Creates a new UserThemeAccessPermission object
+ * @param un Username
+ */
+ public UserThemeAccessPermission(String un) {
+ this.username=un;
+ }
+
+ /**
+ * Get rwx permission group
+ * @return rwx list
+ */
+ public ArrayList getRwx() {
+ return rwx;
+ }
+
+ /**
+ * Get rx permission group
+ * @return rx list
+ */
+ public ArrayList getRx() {
+ return rx;
+ }
+
+ /**
+ * Get r permission group
+ * @return r list
+ */
+ public ArrayList getR() {
+ return r;
+ }
+
+ /**
+ * Add permission with user's themes
+ * @param themes
+ * @throws Exception
+ */
+ public void addPermissionWithThemes(Map themes) throws Exception {
+ try{
+ Map resolved = this.replacePermissions(themes);
+ for(Iterator it=resolved.keySet().iterator();it.hasNext();){
+ String theme=it.next();
+ String val=resolved.get(theme);
+ if(val!=null && val.trim().equalsIgnoreCase("rwx")) getRwx().add(theme);
+ if(val!=null && val.trim().equalsIgnoreCase("rx")) getRx().add(theme);
+ if(val!=null && val.trim().equalsIgnoreCase("r")) getR().add(theme);
+ }
+ } catch(Exception e) {
+ throw e;
+ }
+ }
+
+ /**
+ * Replace the permission letter with 'rwx'.
+ * @param data
+ * @return themes with 'rwx' permissions
+ * @throws Exception
+ */
+ public static Map replacePermissions(Map data) throws Exception {
+ HashMap perm = new HashMap();
+ perm.put("X","rwx");
+ perm.put("S","rwx");
+ perm.put("B","rwx");
+ perm.put("C","rwx");
+ perm.put("U","rx");
+ perm.put("N","r");
+ perm.put("M","rwx");
+ for(String key: data.keySet()){
+ data.put(key, perm.get(data.get(key)));
+ }
+ return data;
+ }
+
+ /**
+ * Overriding to make unique objects per username
+ * @param obj Instance of AuthUser or other object
+ * @return true if obj's username is equal with class' username
+ */
+ public boolean equals(Object obj ) {
+ if(obj instanceof UserThemeAccessPermission){
+ UserThemeAccessPermission other=(UserThemeAccessPermission)obj;
+ if(other.username.equals(this.username)){
+ return true;
+ }else{
+ return false;
+ }
+ }else{
+ return false;
+ }
+ }
+
+ /**
+ * Override toString() method
+ * @return username string
+ */
+ public String toString() {
+ return ""+this.username;
+ }
+
+
+}
+
+
+
diff --git a/lib-auth/src/main/java/com/fourelementscapital/auth/Utils.java b/lib-auth/src/main/java/com/fourelementscapital/auth/Utils.java
new file mode 100755
index 0000000..f31c6e3
--- /dev/null
+++ b/lib-auth/src/main/java/com/fourelementscapital/auth/Utils.java
@@ -0,0 +1,82 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.auth;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Properties;
+
+/**
+ * This class contains Static Utility functions
+ */
+class Utils {
+
+ /**
+ * Accepts an ArrayList of strings and then returns a delimiter separated string
+ * @param al The arraylist of strings
+ * @param delimiter The delimiter
+ * @return The delimiter separated string
+ */
+ protected static String Join(ArrayList al,String delimiter)
+ {
+ return al.toString().replaceAll("\\[|\\]", "").replaceAll(", ",delimiter);
+ }
+
+ /**
+ * Get the value of a property defined in config file
+ * @param propertyName - the name or key of the property you want to retrieve
+ * @return the string value
+ * @throws IOException
+ */
+ protected static String GetConfigValue(String propertyName) throws IOException
+ {
+ Properties prop = new Properties();
+ String propFileName = "config_auth.properties";
+
+ InputStream inputStream = Utils.class.getClassLoader().getResourceAsStream(propFileName);
+
+ if (inputStream != null) {
+ prop.load(inputStream);
+ } else {
+ throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
+ }
+
+ Date time = new Date(System.currentTimeMillis());
+
+ // get the property value and print it out
+ String value = prop.getProperty(propertyName);
+ return value;
+ }
+
+
+ /**
+ * Capitalize first char of a word.
+ * Example : 'this is text. another text' will be converted to 'This Is Text. Another Text'
+ * @param string
+ * @return string
+ */
+ protected static String capitalizeString(String string) {
+ char[] chars = string.toLowerCase().toCharArray();
+ boolean found = false;
+ for (int i = 0; i < chars.length; i++) {
+ if (!found && Character.isLetter(chars[i])) {
+ chars[i] = Character.toUpperCase(chars[i]);
+ found = true;
+ } else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
+ found = false;
+ }
+ }
+ return String.valueOf(chars);
+ }
+
+}
+
+
diff --git a/lib-auth/src/main/java/com/fourelementscapital/auth/WikiAuthentication.java b/lib-auth/src/main/java/com/fourelementscapital/auth/WikiAuthentication.java
new file mode 100755
index 0000000..972d186
--- /dev/null
+++ b/lib-auth/src/main/java/com/fourelementscapital/auth/WikiAuthentication.java
@@ -0,0 +1,176 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.auth;
+
+import java.security.MessageDigest;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Vector;
+
+import org.apache.commons.codec.binary.Hex;
+
+/**
+ * WikiAuthentication will check / validate user authentication to Wiki database.
+ * It also provide functions to get encrypted password of specific user & get list of Wiki users.
+ */
+public class WikiAuthentication {
+
+ public static final String SESSION_LOGGED_USER = "session^logged^user";
+
+ /**
+ * Private constructor to prevent instantiation.
+ */
+ private WikiAuthentication()
+ {
+ }
+
+ /**
+ * Validate Wiki User. If user_name is valid & password being encrypted equals value in database then it will return true.
+ * @param user_name
+ * @param password
+ * @return is user valid
+ * @throws Exception
+ */
+ public static boolean validateUser(String user_name, String password) throws Exception {
+ String encpass = getEncryptedPwd(user_name);
+ return isValid(password,encpass);
+ }
+
+ /**
+ * Validate Wiki User With Encrypted Password. If user_name is valid & encrypted password equals value in database then it will return true.
+ * @param user_name
+ * @param encryptedPassword
+ * @return is user valid
+ * @throws Exception
+ */
+ public static boolean validateUserEncryptedPassword(String user_name, String encryptedPassword) throws Exception {
+ String encpass = getEncryptedPwd(user_name);
+ if (encryptedPassword == null) {
+ return false;
+ }
+ return (encryptedPassword.equals(encpass));
+ }
+
+
+ /**
+ * Check whether password is valid, compare to encrypted password
+ * @param password Password
+ * @param encpass Encrypted password
+ * @return true if encrypted password equals salt password
+ * @throws Exception
+ */
+ private static boolean isValid(String password, String encpass) throws Exception {
+ if (encpass == null || password == null) return false;
+ String salt=encpass.split(":")[2];
+ String saltpass=":B:"+salt+":"+getMD5(salt+"-"+getMD5(password));
+ if(encpass.equals(saltpass)){
+ return true;
+ }else{
+ return false;
+ }
+ }
+
+
+ /**
+ * Get MD5 of source string
+ * @param source Source string
+ * @return MD5 string
+ * @throws Exception
+ */
+ private static String getMD5(String source) throws Exception {
+
+ byte[] bytesOfMessage = source.getBytes();
+
+ java.security.MessageDigest md = MessageDigest.getInstance("MD5");
+ byte[] thedigest = md.digest(bytesOfMessage);
+
+ final String result = new String(Hex.encodeHex(thedigest));
+ return result;
+ }
+
+
+ /**
+ * List / get all Wiki users. The fields returned are : user_name, user_real_name, user_password, user_email.
+ * @return users
+ * @throws Exception
+ */
+ public static Vector> listUsers() throws Exception {
+
+ Vector> rtn = null;
+
+ DBManager dbm = new DBManager("wiki");
+ dbm.connect();
+
+ //sql = "select user_name,user_real_name,user_password,user_email from user";
+
+ ArrayList selectedFields = new ArrayList();
+ selectedFields.add("user_name");
+ selectedFields.add("user_real_name");
+ selectedFields.add("user_password");
+ selectedFields.add("user_email");
+
+ ResultSet rs = dbm.GetDatabase("user", selectedFields, null, null);
+
+ rtn = new Vector>();
+
+ while(rs.next()){
+ String user_name=rs.getString("user_name");
+ String user_real_name=rs.getString("user_real_name");
+ String user_password=rs.getString("user_password");
+ String user_email=rs.getString("user_email");
+ HashMap h=new HashMap();
+ h.put("user_name",user_name );
+ h.put("user_real_name",user_real_name );
+ h.put("user_password",user_password );
+ h.put("user_email",user_email );
+ rtn.add(h);
+ }
+ dbm.closeConnection();
+
+ return rtn;
+ }
+
+
+ /**
+ * Get encrypted password of specific user
+ * @param user
+ * @return encrypted password
+ * @throws Exception
+ */
+ public static String getEncryptedPwd(String user) throws Exception {
+
+ if ((user == null) || user.equals("")) return null;
+
+ String rtn = null;
+
+ DBManager dbm = new DBManager("wiki");
+ dbm.connect();
+
+ //sql = "select CAST(user_password AS CHAR(10000) CHARACTER SET utf8) as pass from user where user_name=?"
+
+ ArrayList selectedFields = new ArrayList();
+ selectedFields.add("CAST(user_password AS CHAR(10000) CHARACTER SET utf8) as pass");
+
+ Map queryParams = new HashMap();
+ queryParams.put("user_name", Utils.capitalizeString(user));
+
+ ResultSet rs = dbm.GetDatabase("user", selectedFields, queryParams, null);
+
+ while(rs.next()){
+ rtn=rs.getString("pass");
+ }
+ dbm.closeConnection();
+
+ return rtn;
+ }
+
+}
+
+
diff --git a/lib-auth/src/main/java/com/fourelementscapital/auth/WikiAuthenticationServlet.java b/lib-auth/src/main/java/com/fourelementscapital/auth/WikiAuthenticationServlet.java
new file mode 100755
index 0000000..01f984d
--- /dev/null
+++ b/lib-auth/src/main/java/com/fourelementscapital/auth/WikiAuthenticationServlet.java
@@ -0,0 +1,99 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.auth;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * WikiAuthenticationServlet is a servlet to facilitate automatic Wiki authentication.
+ * How to use this servlet, see documentation : http://wiki.4ecap.com/4ECwiki/Lib-auth#Automatic_Wiki_Authentication.
+ */
+public class WikiAuthenticationServlet extends HttpServlet {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final String LOGOUT = "logout";
+
+
+ /**
+ * Handle post request, validate username & encrypted password by comparing them with Wiki database.
+ * If valid, generate session to be used throughout the app then redirect to app url.
+ * If not valid, redirect to wiki login url.
+ * @param request request
+ * @param response response
+ */
+ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+
+ try {
+
+ // get request parameters :
+ String username = request.getParameter("username");
+ String encryptedPassword = request.getParameter("encryptedPassword");
+ String redirectUrl = request.getParameter("redirectUrl");
+
+ // get wiki login url from config file
+ String wikiLoginUrl = Utils.GetConfigValue("wiki_login_url");
+
+ // if there's already session then redirect to app url
+ if (request.getSession().getAttribute(WikiAuthentication.SESSION_LOGGED_USER) != null) {
+ response.sendRedirect(redirectUrl);
+ }
+
+ // if there's null parameter then redirect to wiki login
+ else if (username == null || encryptedPassword == null || redirectUrl == null) {
+ response.sendRedirect(wikiLoginUrl);
+ }
+
+ // validate username & encrypted password, if valid then redirect to app url
+ else if (WikiAuthentication.validateUserEncryptedPassword(username, encryptedPassword)) {
+ // set session for app using lib-auth
+ request.getSession().setAttribute(WikiAuthentication.SESSION_LOGGED_USER, username);
+ response.sendRedirect(redirectUrl);
+ }
+
+ // else, redirect to wiki login
+ else {
+ response.sendRedirect(wikiLoginUrl);
+ }
+
+ }catch(Exception e){
+ e.printStackTrace();
+ }
+
+ }
+
+
+ /**
+ * Handle get request, logout (remove session) and redirect to a url.
+ * @param request request
+ * @param response response
+ */
+ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+
+ String method = request.getParameter("method");
+
+ // logout, remove session
+ if(method != null && method.equals(this.LOGOUT)) {
+ if (request.getSession().getAttribute(WikiAuthentication.SESSION_LOGGED_USER) != null) {
+ request.getSession().removeAttribute(WikiAuthentication.SESSION_LOGGED_USER);
+ }
+ }
+
+ // redirect to Wiki page
+ response.sendRedirect(Utils.GetConfigValue("wiki_login_url"));
+ }
+
+
+}
+
+
diff --git a/lib-auth/src/main/resources/config_auth.properties b/lib-auth/src/main/resources/config_auth.properties
new file mode 100755
index 0000000..a6ea781
--- /dev/null
+++ b/lib-auth/src/main/resources/config_auth.properties
@@ -0,0 +1,7 @@
+database_wiki_connstring=jdbc:mysql://wiki.4ecap.com/4EwikiDB1?user=4ecremoteuser&password=4ecrmt2011
+database_wiki_driver=com.mysql.jdbc.Driver
+
+wiki_login_url=http://wiki.4ecap.com
+
+superuser_password_folder=/tmp/
+#superuser_password_folder=d:\\tmp\\
\ No newline at end of file
diff --git a/lib-auth/src/main/resources/log4j2.xml b/lib-auth/src/main/resources/log4j2.xml
new file mode 100755
index 0000000..b8d69f3
--- /dev/null
+++ b/lib-auth/src/main/resources/log4j2.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/lib-auth/src/test/java/com/fourelementscapital/auth/LibAuthTest.java b/lib-auth/src/test/java/com/fourelementscapital/auth/LibAuthTest.java
new file mode 100755
index 0000000..9bff80b
--- /dev/null
+++ b/lib-auth/src/test/java/com/fourelementscapital/auth/LibAuthTest.java
@@ -0,0 +1,215 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.auth;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Vector;
+import javax.swing.JOptionPane;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+
+/**
+ * lib-auth unit test
+ */
+public class LibAuthTest extends TestCase {
+
+ private static final Logger log = LogManager.getLogger(LibAuthTest.class.getName());
+
+ /**
+ * Wiki authentication test : login, check login, get authenticated user, get user access.
+ */
+ public void testWikiAuthentication()
+ {
+ log.debug(">>>>>> testWikiAuthentication()");
+ try {
+
+ // wiki login :
+ String user = "bot";
+ String password = "bot2018";
+
+ boolean success= WikiAuthentication.validateUser(user, password); // validate wiki user
+ log.debug("validate wiki user : " + success);
+ JOptionPane.showMessageDialog(null, "validate wiki user success");
+
+ HashMap loginMap = new HashMap();
+ if(!success){
+ loginMap.put("message", "Invalid username or password");
+ Assert.assertTrue(false); // scenario : login must success
+ }else{
+ loginMap.put("authenticatedUser", user);
+ // example : get encrypted password and store it to map for further process
+ String pss = WikiAuthentication.getEncryptedPwd(user);
+ loginMap.put("encryptedPassword", pss);
+ }
+
+ // store validate user result to map
+ loginMap.put("loggedin", Boolean.toString(success));
+
+ // check whether user login / not :
+ boolean loggedin = Boolean.parseBoolean(loginMap.get("loggedin"));
+ log.debug("is user logged in : " + loggedin);
+ Assert.assertTrue(loggedin);
+
+ // get authenticated user :
+ String authenticatedUser = loginMap.get("authenticatedUser");
+ log.debug("get authenticatedUser : " + authenticatedUser);
+
+ // Get user access. Use dummy themes for testing purpose.
+ // To get themes from infrastructureDB : Map themes = infrastructureDB.getThemes4Users(user). It needs lib-db library.
+ Map themes= new HashMap();
+ themes.put("computing", "X");
+ themes.put("etrading", "U");
+ themes.put("execution", "N");
+ themes.put("bb", "B");
+
+ UserThemeAccessPermission userTheme = new UserThemeAccessPermission(user);
+ userTheme.addPermissionWithThemes(themes);
+ ArrayList rwxList = userTheme.getRwx();
+ log.debug("rwxList : ");
+ for (String rwx : rwxList) {
+ log.debug("- " + rwx);
+ }
+ Assert.assertTrue(rwxList.contains("computing") && rwxList.contains("bb")); // getRwx() must contains 'computing' & 'bb'
+
+ ArrayList rxList = userTheme.getRx();
+ log.debug("rxList : ");
+ for (String rx : rxList) {
+ log.debug("- " + rx);
+ }
+ Assert.assertTrue(rxList.contains("etrading")); // getRx() must contains 'etrading'
+
+ ArrayList rList = userTheme.getR();
+ log.debug("rList : ");
+ for (String r : rList) {
+ log.debug("- " + r);
+ }
+ Assert.assertTrue(rList.contains("execution")); // getR() must contains 'execution'
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ assertTrue( false );
+ }
+ }
+
+
+ /**
+ * Super user authentication test : validate / set / change password, check login, get authenticated user
+ */
+ public void testSuperUserAuthentication()
+ {
+ log.debug(">>>>>> testSuperUserAuthentication()");
+ try {
+
+ String user = "administrator";
+ String password = "password1";
+ String newpassword = "password1";
+
+ Map loginMap = new HashMap();
+ boolean success = false;
+
+ // if user is 'administrator' and newpassword is not null & not empty then it's a change password :
+ if(user.equalsIgnoreCase("administrator") && newpassword!=null && !newpassword.equals("")){
+
+ // Remove the comment tag to test. The code are commented out to prevent creating password file when installing this lib (edit properties file first) :
+ //success = SuperUserAuthentication.changePwd(password,newpassword);
+ //temporary var value when install this lib :
+ success = true;
+
+ //log.debug("change superuser password : " + newpassword);
+ //JOptionPane.showMessageDialog(null, "Change superuser password done. Password located in /tmp/superuser.pwd");
+ }
+ // else : validate if password is already set or set password if password has not been set :
+ else{
+
+ // Remove the comment tag to test. The code are commented out to prevent creating password file when installing this lib (edit properties file first) :
+ //success= SuperUserAuthentication.validateOrSet(password);
+ //temporary var value when install this lib :
+ success = true;
+
+ //log.debug("validate / set superuser password : " + password);
+ //JOptionPane.showMessageDialog(null, "validate/set superuser password");
+ }
+
+ if(!success){
+ loginMap.put("message", "Invalid username or password");
+ Assert.assertTrue(false); // scenario : login must success
+ }
+ else {
+ loginMap.put("authenticatedUser", user);
+ }
+ loginMap.put("loggedin", Boolean.toString(success)); // store validate superuser result to map
+
+ // check whether login / not :
+ boolean loggedin = Boolean.parseBoolean(loginMap.get("loggedin"));
+ log.debug("is superuser logged in : " + loggedin);
+ Assert.assertTrue(loggedin);
+
+ // get authenticated user :
+ String authenticated_user = loginMap.get("authenticatedUser");
+ log.debug("authenticated superuser : " + authenticated_user);
+
+ //Assert.assertTrue(true);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ /**
+ * List Wiki users test
+ */
+ public void testListWikiUsers()
+ {
+ log.debug(">>>>>> testListWikiUsers()");
+ try {
+ Vector> result = WikiAuthentication.listUsers();
+
+ log.debug("wiki user count : " + result.size());
+ JOptionPane.showMessageDialog(null, "Wiki user count: "+result.size());
+
+ for (int i=0; i h = (HashMap) result.get(i);
+/*
+ log.debug(">>>>>>>>>> user_name : " + h.get("user_name"));
+ log.debug(">>>>>>>>>> user_real_name : " + h.get("user_real_name"));
+ log.debug(">>>>>>>>>> user_password : " + h.get("user_password"));
+ log.debug(">>>>>>>>>> user_email : " + h.get("user_email"));
+*/
+ }
+ assertTrue( true );
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ assertTrue( false );
+ }
+ }
+
+
+ /**
+ * System authentication test
+ */
+ public void testSystemAuthentication()
+ {
+ log.debug(">>>>>> testSystemAuthentication()");
+ log.debug("SystemAuthentication.isUserLoggedIn() : " + SystemAuthentication.isUserLoggedIn());
+
+ assertTrue( SystemAuthentication.isUserLoggedIn() );
+ //assertTrue( true );
+ }
+
+}
+
+
\ No newline at end of file
diff --git a/lib-db/pom.xml b/lib-db/pom.xml
new file mode 100755
index 0000000..931714c
--- /dev/null
+++ b/lib-db/pom.xml
@@ -0,0 +1,53 @@
+
+ 4.0.0
+
+
+ com.fourelementscapital
+ lib
+ ${revision}
+
+
+ com.fourelementscapital
+ lib-db
+ jar
+ lib-db
+ Lower level DAL (Data Access Layer) for database call
+ http://www.fourelementscapital.com
+
+
+
+ org.apache.logging.log4j
+ log4j-api
+
+
+ commons-dbutils
+ commons-dbutils
+ 1.1
+
+
+
+ org.apache.commons
+ commons-jcs-core
+ 2.2
+
+
+
+ com.jolbox
+ bonecp
+
+
+ mysql
+ mysql-connector-java
+
+
+ com.microsoft.sqlserver
+ mssql-jdbc
+
+
+ org.apache.logging.log4j
+ log4j-core
+ 2.8.1
+
+
+
diff --git a/lib-db/src/main/java/com/fourelementscapital/db/AbstractTeamOrgDB.java b/lib-db/src/main/java/com/fourelementscapital/db/AbstractTeamOrgDB.java
new file mode 100755
index 0000000..cfe8b0c
--- /dev/null
+++ b/lib-db/src/main/java/com/fourelementscapital/db/AbstractTeamOrgDB.java
@@ -0,0 +1,345 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.db;
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import org.apache.commons.dbutils.BasicRowProcessor;
+
+
+
+/**
+ * This abstract class implements the methods that are related to Theme organisation tags
+ */
+public abstract class AbstractTeamOrgDB extends SuperDB{
+
+
+ /**
+ * Get tag table
+ * @return tag table
+ */
+ public abstract String getTagTable(); //tags
+
+ /**
+ * Get tag item table
+ * @return tag item table
+ */
+ public abstract String getTagItemTable(); //example: scheduler_tags
+
+ /**
+ * Get tag item id
+ * @return tag item id
+ */
+ public abstract String getTagItemId(); // example: scheduler_id or function_id;
+
+ /**
+ * Get tag item follow table
+ * @return tag item follow table
+ */
+ public abstract String getTagItemFollowTable(); //example: scheduler_tags
+
+
+ /**
+ * Returns list of All tags of the tool ( for example, if it was implemented for scheduler then it will return all scheduler themes)
+ * @return tags
+ * @throws Exception
+ */
+ public Vector getTags() throws Exception {
+ Vector rtn=new Vector();
+ PreparedStatement ps=this.connection().prepareStatement("select * FROM "+getTagTable()+" ORDER BY tagname");
+ ResultSet rs=ps.executeQuery();
+ while(rs.next()){
+ rtn.add(new BasicRowProcessor().toMap(rs));
+ }
+
+ //added by rams on 5-june-2012
+ rs.close();
+ ps.close();
+ return rtn;
+ }
+
+
+ /**
+ * Get tags details
+ * @param tags tag names
+ * @return tags
+ * @throws Exception
+ */
+ public Vector getTagsDetails(String tags[]) throws Exception {
+ Vector rtn=new Vector();
+ String stags=null;
+ for(int i=0;i tagids) throws Exception {
+
+ String query="DELETE FROM "+getTagItemTable()+" WHERE id IN (select * from (select a.id from "+getTagItemTable()+" as a left outer join "+getTagTable()+" as b on a.tag_id = b.id where "+getTagItemId()+"=? and left(b.tagname,3)<>'usr') temp_table ) ";
+ PreparedStatement ps=this.connection().prepareStatement(query);
+ ps.setInt(1, item_id);
+ ps.executeUpdate();
+ ps.close();
+
+
+ PreparedStatement ps1=this.connection().prepareStatement("INSERT INTO "+getTagItemTable()+"("+getTagItemId()+",tag_id) VALUES(?,?)");
+ for(Integer i:tagids){
+ ps1.setInt(1, item_id);
+ ps1.setInt(2, i);
+ ps1.executeUpdate();
+ }
+ ps1.close();
+ }
+
+ /**
+ * Update follower tag id
+ * @param item_id item id
+ * @param tagids tag ids
+ * @throws Exception
+ */
+ public void updateFollwerTagIds(int item_id, List tagids) throws Exception {
+
+ String query="DELETE FROM "+getTagItemFollowTable()+" WHERE id IN (select * from (select a.id from "+getTagItemFollowTable()+" as a left outer join "+getTagTable()+" as b on a.tag_id = b.id where "+getTagItemId()+"=? and left(b.tagname,3)<>'usr') temp_table ) ";
+ PreparedStatement ps=this.connection().prepareStatement(query);
+ ps.setInt(1, item_id);
+ ps.executeUpdate();
+ ps.close();
+
+
+ PreparedStatement ps1=this.connection().prepareStatement("INSERT INTO "+getTagItemFollowTable()+"("+getTagItemId()+",tag_id) VALUES(?,?)");
+ for(Integer i:tagids){
+ ps1.setInt(1, item_id);
+ ps1.setInt(2, i);
+ ps1.executeUpdate();
+ }
+ ps1.close();
+ }
+
+ /**
+ * Get theme tags
+ * @param item_id item id
+ * @return theme tags
+ * @throws Exception
+ */
+ public List getThemeTags(int item_id) throws Exception {
+
+ String q="select replace(b.tagname,'thm-','') as theme FROM "+getTagItemTable()+" as a ";
+ q+="left outer join "+getTagTable()+" as b on a.tag_id=b.id ";
+ q+="where a."+getTagItemId()+"=? ";
+ q+="and left(b.tagname,4)='thm-' ";
+
+ PreparedStatement ps=this.connection().prepareStatement(q);
+ ps.setInt(1, item_id);
+
+ ResultSet rs=ps.executeQuery();
+ ArrayList rtn=new ArrayList();
+ while(rs.next()){
+ rtn.add(rs.getString("theme"));
+ }
+ return rtn;
+ }
+
+ /**
+ * Get theme tag name
+ * @param tag_id tag id
+ * @return theme tag name
+ * @throws Exception
+ */
+ public String getThemeTagName(int tag_id) throws Exception {
+
+ String q="select replace(a.tagname,'thm-','') as theme FROM "+getTagTable()+" as a where id=?";
+
+
+ PreparedStatement ps=this.connection().prepareStatement(q);
+ ps.setInt(1, tag_id);
+
+ ResultSet rs=ps.executeQuery();
+ String rtn=null;
+ if(rs.next()){
+ rtn= rs.getString("theme");
+ }
+ return rtn;
+ }
+
+ /**
+ * Get theme names by item id
+ * @param item_id item id
+ * @return theme names
+ * @throws Exception
+ */
+ public ArrayList getThemeNames4Item(int item_id) throws Exception {
+ PreparedStatement ps=this.connection().prepareStatement("select b.tagname FROM "+getTagItemTable()+" as a left outer join "+getTagTable()+" as b on a.tag_id=b.id WHERE a."+getTagItemId()+"=? and left(b.tagname,4)<>'usr-'");
+ ps.setInt(1, item_id);
+ ResultSet rs=ps.executeQuery();
+ ArrayList rtn=new ArrayList();
+ while(rs.next()){
+ String tagname=rs.getString("tagname");
+ tagname=tagname.replaceAll("thm-", "");
+ rtn.add(tagname);
+ }
+ //added by rams on 5-june-2012
+ rs.close();
+ ps.close();
+ return rtn;
+ }
+
+
+ /**
+ * Get followers tag by item id
+ * @param item_id item id
+ * @return followers tag
+ * @throws Exception
+ */
+ public ArrayList getFollowTags4Item(int item_id) throws Exception {
+ PreparedStatement ps=this.connection().prepareStatement("select b.tagname FROM "+getTagItemFollowTable()+" as a left outer join "+getTagTable()+" as b on a.tag_id=b.id WHERE a."+getTagItemId()+"=? and left(b.tagname,4)<>'usr-'");
+ ps.setInt(1, item_id);
+ ResultSet rs=ps.executeQuery();
+ ArrayList rtn=new ArrayList();
+ while(rs.next()){
+ String tagname=rs.getString("tagname");
+ tagname=tagname.replaceAll("thm-", "");
+ rtn.add(tagname);
+ }
+ //added by rams on 5-june-2012
+ rs.close();
+ ps.close();
+ return rtn;
+ }
+
+
+ /**
+ * Get SVN user for Wiki user
+ * @param w_user wiki user
+ * @return svn user
+ * @throws Exception
+ */
+ public Map getSVNUser4WikiUser(String w_user) throws Exception {
+
+ PreparedStatement ps5=this.connection().prepareStatement("SELECT * FROM users where svn_username=?");
+
+ ps5.setString(1, w_user);
+ ResultSet rs5= ps5.executeQuery();
+ Map rtn=new HashMap();
+ if(rs5.next()){
+ rtn=new BasicRowProcessor().toMap(rs5);
+ }
+ //added by rams on 5-june-2012
+ rs5.close();
+ ps5.close();
+ return rtn;
+ }
+
+}
+
+
diff --git a/lib-db/src/main/java/com/fourelementscapital/db/BBSyncDB.java b/lib-db/src/main/java/com/fourelementscapital/db/BBSyncDB.java
new file mode 100755
index 0000000..9394688
--- /dev/null
+++ b/lib-db/src/main/java/com/fourelementscapital/db/BBSyncDB.java
@@ -0,0 +1,227 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.db;
+
+import java.sql.Date;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Vector;
+
+import com.fourelementscapital.db.vo.BBSyncTrigger;
+
+
+/**
+ * Abstract class implements methods related to BBSync
+ */
+public abstract class BBSyncDB extends SuperDB{
+
+ /**
+ * Connect database
+ */
+ public void connectDB() throws Exception {
+ super.connectDB(DB_NAME_BBSYNC);
+ }
+
+ /**
+ * List all bbsync
+ * @return bbsync
+ * @throws Exception
+ */
+ public abstract Vector listAll() throws Exception;
+
+ /**
+ * Get field mapping by bbsync id
+ * @param bbsyncid bbsync id
+ * @return field mapping
+ * @throws Exception
+ */
+ public abstract ArrayList fieldMapping4BBSync(int bbsyncid) throws Exception;
+
+ /**
+ * Get download query
+ * @param id bbsync id
+ * @return bbsync
+ * @throws Exception
+ */
+ public abstract Map getDownloadQuery(long id) throws Exception;
+
+ /**
+ * Get field mapping
+ * @return field mapping
+ * @throws Exception
+ */
+ public abstract Vector getFieldMapping() throws Exception;
+
+ /**
+ * Update triggered date
+ * @param id bbsync id
+ * @param start trigger start date
+ * @param end trigger end date
+ * @throws Exception
+ */
+ public abstract void updateTriggeredDate(int id, Timestamp start,
+ Timestamp end) throws Exception;
+
+ /**
+ * Delete field mapping
+ * @param id field mapping id
+ * @throws Exception
+ */
+ public abstract void deleteFieldMapping(int id) throws Exception;
+
+ /**
+ * Add field mapping
+ * @param dbfield field mapping db field
+ * @param bbfield field mapping bb field
+ * @throws Exception
+ */
+ public abstract void addFieldMapping(String dbfield, String bbfield)
+ throws Exception;
+
+ /**
+ * Update contract logs
+ * @param contract contracts
+ * @param marketsector market sector
+ * @param lastsync last sync
+ * @param scommodities scommodities
+ * @param fields contract fields
+ * @throws Exception
+ */
+ public abstract void updateContractLogs(Vector contract,String marketsector,
+ Timestamp lastsync, Map scommodities,Collection fields)
+ throws Exception;
+
+ /**
+ * Update securities logs
+ * @param contract contracts
+ * @param marketsector market sector
+ * @param lastsync last sync
+ * @param fields contract fields
+ * @throws Exception
+ */
+ public abstract void updateSecuritiesLogs(Vector contract,
+ String marketsector, Timestamp lastsync,Collection fields) throws Exception;
+
+ /**
+ * Get contract names to ref synchronized
+ * @param pendingonly is pending only
+ * @throws Exception
+ * @return contract info
+ */
+ public abstract Vector getContractNames2RefSync(boolean pendingonly)
+ throws Exception;
+
+ /**
+ * Get security names to ref synchronized
+ * @param pendingonly is pending only
+ * @throws Exception
+ * @return security info
+ */
+ public abstract Map getSecurityNames2RefSync(
+ boolean pendingonly) throws Exception;
+
+ /**
+ * Get security name to ref synchronized
+ * @param ticker ticker
+ * @throws Exception
+ * @return security info
+ */
+ public abstract Map getSecurityName2RefSync(String ticker) throws Exception ;
+
+ /**
+ * Update contract reference
+ * @param contractname contract name
+ * @param fielddata field data
+ * @throws Exception
+ */
+ public abstract void updateContractReference(String contractname,
+ Map fielddata) throws Exception;
+
+ /**
+ * Update security reference
+ * @param securityname security name
+ * @param marketsector market sector
+ * @param fielddata field data
+ * @throws Exception
+ */
+ public abstract void updateSecurityReference(String securityname,
+ String marketsector, Map fielddata)
+ throws Exception;
+
+ /**
+ * Add sync logs
+ * @param bbsyncid bbsync id
+ * @param start start time
+ * @param end end time
+ * @param message message
+ * @param status status
+ * @param manual_scheduler manual scheduler
+ * @throws Exception
+ */
+ public abstract void addSyncLogs(int bbsyncid, Timestamp start,
+ Timestamp end, String message, String status,
+ String manual_scheduler) throws Exception;
+
+ /**
+ * Remove schedule ticker
+ * @param bbsync_id bbsync id
+ * @param ticker contract
+ * @throws Exception
+ */
+ public abstract void removeScheduleTicker(int bbsync_id, String ticker)
+ throws Exception;
+
+ /**
+ * Save schedule
+ * @param id bbsync id
+ * @param name bbsync name
+ * @param mkt_secdb is market security db
+ * @param dateoption date option
+ * @param datefrom date from
+ * @param dateto date to
+ * @param datenumber date recent number
+ * @param fields bbsync fields
+ * @param contracts bbsync contracts
+ * @param t BBSync trigger
+ * @param marketsector market sector
+ * @param timezone timezone
+ * @return bbsync id
+ * @throws Exception
+ */
+ public abstract int saveSchedule(int id, String name, String mkt_secdb,
+ String dateoption, Date datefrom, Date dateto, int datenumber,
+ Vector fields, String contracts, BBSyncTrigger t,
+ String marketsector, String timezone) throws Exception;
+
+ public abstract void deleteQuery(int id) throws Exception;
+
+ /**
+ * Record started peer
+ * @param peername peer name
+ * @param sessionid session id
+ * @param time time
+ * @throws Exception
+ */
+ public abstract void peerStarted(String peername,long sessionid, java.util.Date time) throws Exception ;
+
+ /**
+ * Record stopped peer
+ * @param peername peer name
+ * @param sessionid session id
+ * @param time time
+ * @throws Exception
+ */
+ public abstract void peerStopped(String peername, long sessionid, java.util.Date time) throws Exception;
+
+
+
+}
+
+
diff --git a/lib-db/src/main/java/com/fourelementscapital/db/Config.java b/lib-db/src/main/java/com/fourelementscapital/db/Config.java
new file mode 100755
index 0000000..d7aac3e
--- /dev/null
+++ b/lib-db/src/main/java/com/fourelementscapital/db/Config.java
@@ -0,0 +1,147 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.db;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.MissingResourceException;
+import java.util.Properties;
+import java.util.ResourceBundle;
+
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.LogManager;
+
+
+/**
+ * This class populates the configuration value from property file
+ */
+class Config {
+
+ /**
+ * Configuration file
+ */
+ private static final String BUNDLE_NAME = "config_db"; //$NON-NLS-1$
+
+ /**
+ * windows peer configuration
+ */
+ private static final String PROPERTY_FILE_WIN = "peer_db_windows.properties"; //$NON-NLS-1$
+
+ /**
+ * unix peer/server configuration file
+ */
+ private static final String PROPERTY_FILE_UNIX = "peer_db_unix.properties"; //$NON-NLS-1$
+
+ public static String CONFIG_PROPERTY_LOCATION=null;
+
+ private static Properties confpro=null;
+
+ /**
+ * Private constructor
+ */
+ private Config() {
+ }
+
+
+ /**
+ * Get property value of specified key. Return '!key!' if not found.
+ * @param key key
+ * @return property value
+ */
+ protected static String getString(String key) {
+ if(CONFIG_PROPERTY_LOCATION==null){
+ try {
+ //return RESOURCE_BUNDLE.getString(key);
+ return getResourceBuddle().getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }else{
+ try {
+ String ky= getPeerProperty(key);
+ if(ky==null) throw new Exception();
+ else return ky;
+ } catch (Exception e) {
+ return '!' + key + '!';
+ }
+ }
+ }
+
+
+ private static ResourceBundle resourceBundle=null;
+
+
+ /**
+ * Get resources bundle
+ * @return resources bundle
+ */
+ private synchronized static ResourceBundle getResourceBuddle(){
+
+ if(resourceBundle==null){
+ resourceBundle=ResourceBundle.getBundle(BUNDLE_NAME);
+ LogManager.getLogger(Config.class.getName()).info("resourceBundle:"+resourceBundle);
+ }
+
+ return resourceBundle;
+ }
+
+
+ /**
+ * Get property value of specified key. Return null if not found.
+ * @param key key
+ * @return property value
+ */
+ protected static String getValue(String key) {
+ if(CONFIG_PROPERTY_LOCATION==null){
+ try {
+
+ return getResourceBuddle().getString(key);
+ } catch (MissingResourceException e) {
+ return null;
+ }
+ }else{
+ try {
+ return getPeerProperty(key);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+ }
+
+
+ /**
+ * Get peer property by key
+ * @param key key
+ * @return peer property
+ */
+ private static String getPeerProperty(String key) throws Exception {
+ try{
+ if(confpro==null){
+ String propertyfilename=PROPERTY_FILE_WIN;
+ if(System.getProperty("os.name").toLowerCase().equals("freebsd"))
+ propertyfilename=PROPERTY_FILE_UNIX;
+
+ if(System.getProperty("os.name").toLowerCase().contains("linux"))
+ propertyfilename=PROPERTY_FILE_UNIX;
+
+ String folder=CONFIG_PROPERTY_LOCATION;
+ folder=folder.endsWith(File.separator)?folder:folder+File.separator;
+ confpro=new Properties();
+ String filename=folder+"conf"+File.separator+propertyfilename;
+ confpro.load(new FileInputStream(filename));
+ }
+ return confpro.getProperty(key);
+ }catch(Exception e){
+ e.printStackTrace();
+ throw e;
+ }
+ }
+
+}
+
+
diff --git a/lib-db/src/main/java/com/fourelementscapital/db/ConstructQueryDB.java b/lib-db/src/main/java/com/fourelementscapital/db/ConstructQueryDB.java
new file mode 100755
index 0000000..34f3eb1
--- /dev/null
+++ b/lib-db/src/main/java/com/fourelementscapital/db/ConstructQueryDB.java
@@ -0,0 +1,48 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.db;
+
+import java.util.Map;
+
+/**
+ * Abstract class to construct query
+ */
+public abstract class ConstructQueryDB extends SuperDB{
+
+ /**
+ * Connect database
+ */
+ public void connectDB() throws Exception {
+ super.connectDB(DB_NAME_BBSYNC);
+ }
+
+ /**
+ * Construct date input query
+ * @param rtnobj return object
+ * @return query
+ */
+ public abstract String constructDateInputQuery(Map rtnobj);
+
+ /**
+ * Construct recent query
+ * @param field table field
+ * @param dateQuery date query
+ * @return query
+ */
+ public abstract String constructRecentQuery(String field, String dateQuery);
+
+ /**
+ * Construct queue history query
+ * @param rtnobj return object
+ * @return query
+ */
+ public abstract String constructQueueHistoryQuery(Map rtnobj);
+
+}
+
+
diff --git a/lib-db/src/main/java/com/fourelementscapital/db/ContractDB.java b/lib-db/src/main/java/com/fourelementscapital/db/ContractDB.java
new file mode 100755
index 0000000..bbd6243
--- /dev/null
+++ b/lib-db/src/main/java/com/fourelementscapital/db/ContractDB.java
@@ -0,0 +1,130 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.db;
+
+import java.sql.Connection;
+import java.util.List;
+import java.util.Vector;
+
+/**
+ * Abstract class implements methods related to Contract
+ */
+public abstract class ContractDB extends SuperDB{
+
+
+ /**
+ * Update records
+ * @param con connection
+ * @param records records
+ * @throws Exception
+ */
+ public abstract void updateRecords(Connection con,Vector records) throws Exception;
+
+ /**
+ * Add records
+ * @param con connection
+ * @param records records
+ * @throws Exception
+ */
+ public abstract void addRecords(Connection con,Vector records) throws Exception;
+
+ /**
+ * Create table
+ * @param con connection
+ * @param decimalpoint decimal point
+ * @throws Exception
+ */
+ public abstract void createTable(Connection con, int decimalpoint) throws Exception;
+
+ /**
+ * Update sval records
+ * @param con connection
+ * @param records records
+ * @throws Exception
+ */
+ public abstract void updateSValRecords(Connection con,Vector records) throws Exception;
+
+ /**
+ * Add sval records
+ * @param con connection
+ * @param records records
+ * @throws Exception
+ */
+ public abstract void addSValRecords(Connection con,Vector records) throws Exception;
+
+ /**
+ * Create sval table
+ * @param con connection
+ * @param decimalpoint decimal point
+ * @throws Exception
+ */
+ public abstract void createSValTable(Connection con, int decimalpoint) throws Exception;
+
+ /**
+ * Check s value field
+ * @param con connection
+ * @return record count
+ * @throws Exception
+ */
+ public abstract int checkSValueField(Connection con) throws Exception;
+
+ /**
+ * Count records
+ * @param con connection
+ * @return record count
+ * @throws Exception
+ */
+ public abstract int countRecords(Connection con) throws Exception;
+
+ /**
+ * Check whether s value field type exist
+ * @param con connection
+ * @return true if record exist
+ * @throws Exception
+ */
+ public abstract boolean checkSValueFieldTypeExist(Connection con) throws Exception;
+
+ /**
+ * Get contract titles by connection
+ * @param con connection
+ * @return contract titles
+ * @throws Exception
+ */
+ public abstract List getContractTitles(Connection con) throws Exception;
+
+ /**
+ * Get contract titles by connection & date query
+ * @param con connection
+ * @param datequery date query
+ * @return contract titles
+ * @throws Exception
+ */
+ public abstract List getContractTitles(Connection con, String datequery) throws Exception;
+
+ /**
+ * Update master table
+ * @param con connection
+ * @param mtable master table
+ * @param fieldname field name
+ * @throws Exception
+ */
+ public abstract void updateMasterTable(Connection con,String mtable,String fieldname) throws Exception;
+
+
+ /**
+ * Generate SQL XL Query Plain query
+ * @param fieldtable field table
+ * @param nmonths n months
+ * @param contractTitleList contract title list
+ * @return contract date
+ */
+ public abstract String generateSQLXLQueryPlainQuery(String fieldtable, int nmonths, List contractTitleList);
+
+}
+
+
diff --git a/lib-db/src/main/java/com/fourelementscapital/db/DBManager.java b/lib-db/src/main/java/com/fourelementscapital/db/DBManager.java
new file mode 100755
index 0000000..adcc361
--- /dev/null
+++ b/lib-db/src/main/java/com/fourelementscapital/db/DBManager.java
@@ -0,0 +1,273 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.db;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * The DBManager class provides an Access Interface between the Trading Database and Java.
+ * It can be used to get data from the database, insert new data and update existing data.
+ * The config file containing the details for the database hostname and credentials is located in the resources folder.
+ * @author Manas Maral Misra, Antonius Ari Wicaksono
+ *
+ */
+public class DBManager {
+ /**
+ * The database name for the current instance of DBManager
+ */
+ private String dbName;
+ /**
+ * The connection string for the database connection. Stored in config.lib-dal
+ */
+ private String connectionString;
+ /**
+ * The resultSet which contains the returned results from the SQL Query of GetDatabase
+ */
+ ResultSet resultSet = null;
+ /**
+ * The connection object of the current connection.
+ */
+ private Connection conn = null;
+
+ /**
+ * Initialize the DBManager with the database name.
+ * @param dbName The name of the database e.x. trading, tradingRef, fundamentals
+ * @throws IOException
+ */
+ public DBManager(String dbName) throws IOException
+ {
+ this.dbName = dbName;
+ }
+
+ /**
+ * This function connects to the dbName database;
+ * @throws SQLException This is thrown incase we are not able to connect to the database;
+ * @throws ClassNotFoundException This is thrown incase the driver is not found on this machine
+ * @throws IOException This is thrown incase the config.lib-dal if not found on this machine under resources folder
+ */
+ public void connect() throws SQLException, ClassNotFoundException, IOException
+ {
+ String connString = Utils.getConfig4E(".CONFIG4E_JDBC_CONNECTIONSTRING_" + dbName.toUpperCase());
+
+ String driver = "com.mysql.jdbc.Driver";
+
+ // if connString contains 'sqlserver'. i.e. 'jdbc:sqlserver://10.153.64.3:1433;databaseName=infrastructure;integratedSecurity=false;user=dbuser;password=dbuser'
+ if (connString.contains("sqlserver")) {
+ driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
+ }
+
+ Class.forName(driver);
+ conn = DriverManager.getConnection(connString);
+ connectionString = conn.toString();
+ }
+
+ /**
+ * This function returns the result set of the SQL Query used by GetDatabase;
+ * @param query The SQL Query passed to it.
+ * @return
+ * @throws SQLException
+ */
+ protected ResultSet executeQuery(String query) throws SQLException
+ {
+ Date start = new Date();
+ Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
+ resultSet = statement.executeQuery(query);
+ Date end = new Date();
+ long duration = (end.getTime() - start.getTime());
+ //Utils.Log("DEBUG: Query ("+query+") took "+duration+ " miliseconds");
+ return resultSet;
+ }
+ /**
+ * This function returns the result set of the SQL Query used by GetDatabase;
+ * @param query The SQL Query passed to it.
+ * @return
+ * @throws SQLException
+ */
+ protected void executeNonQuery(String query) throws SQLException
+ {
+ Date start = new Date();
+ Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
+ statement.execute(query);
+ Date end = new Date();
+ long duration = (end.getTime() - start.getTime());
+ //Utils.Log("DEBUG: Query ("+query+") took "+duration+ " miliseconds");
+
+ }
+ /**
+ * This function executes the Update query from UpdateDatabase
+ * @param query
+ * @throws SQLException
+ */
+ private void updateQuery(String query) throws SQLException
+ {
+ Date start = new Date();
+ Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
+ statement.executeUpdate(query);
+ Date end = new Date();
+ long duration = (end.getTime() - start.getTime());
+ System.out.println("DEBUG: Query took "+duration+ " miliseconds");
+ }
+ /**
+ * Closes the current Database connection.
+ * @throws SQLException
+ */
+ public void closeConnection()
+ {
+ try {
+ if(!conn.isClosed())
+ conn.close();
+ if(resultSet!=null)
+ resultSet.close();
+ } catch (SQLException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Used to query a database and access the resultant data in a ResultSet
+ * @param tableName The name of the database table to be accessed
+ * @param selectedFields A list of the values to be selected through the queries. new ArrayList();
+ * be passed to select all fields (*)
+ * @param queryParams A hashmap containing the selection filters in the format [column_name]=[value]
+ * @param customQuery Any additional parameters to be added after the Where clause. Could be a GROUP BY or ORDER BY
+ * @return The resulting data in a ResultSet
+ * @throws SQLException
+ */
+ public ResultSet getDatabase(String tableName,ArrayList selectedFields, Map queryParams, String customQuery) throws SQLException
+ {
+ String queryBuilder = "";
+ if(selectedFields.size()==0)
+ {
+ selectedFields.add("*");
+ }
+
+ queryBuilder += "SELECT "+Utils.Join(selectedFields,",")+" FROM "+tableName;
+
+ if(queryParams != null && queryParams.size()>0)
+ {
+ queryBuilder += " WHERE ";
+ for (Map.Entry entry : queryParams.entrySet()) {
+
+ try{
+ Float f = Float.parseFloat(entry.getValue().toString());
+ queryBuilder += " "+entry.getKey() + " = "+entry.getValue()+" AND";
+ }
+ catch(Exception ex)
+ {
+ queryBuilder += " "+entry.getKey() + " = '"+entry.getValue()+"' AND";
+ }
+
+ }
+ if(customQuery!= null && customQuery!="")
+ queryBuilder += customQuery+" AND";
+ queryBuilder = queryBuilder.substring(0,queryBuilder.length()-3);
+ }
+ //System.out.println(queryBuilder);
+ return executeQuery(queryBuilder);
+ }
+
+ /**
+ * Used to update a single cell in a table in the database.
+ * @param tableName The name of the database table to be accessed
+ * @param selectedFields
+ * @param queryParams A hashmap containing the selection filters in the format [column_name]=[value]
+ * @param selectionFieldValues A list of the values to be selected through the queries. new ArrayList();
+ * be passed to select all fields (*)
+ * @param newFieldsValues
+ * @throws SQLException
+ */
+ public void updateDatabase(String tableName,Map selectionFieldValues, Map newFieldsValues) throws SQLException
+ {
+ String queryBuilder = "UPDATE "+tableName+" SET ";
+
+ if(newFieldsValues.size()>0)
+ {
+ ArrayList al = new ArrayList();
+ for (Map.Entry entry : newFieldsValues.entrySet()) {
+ try{
+ Float f = Float.parseFloat(entry.getValue().toString());
+ al.add(entry.getKey()+" = "+entry.getValue());
+ }
+ catch(Exception ex)
+ {
+ al.add(entry.getKey()+" = '"+entry.getValue()+"'");
+ }
+ }
+ queryBuilder += Utils.Join(al, ",");
+ }
+
+ if(selectionFieldValues.size()>0)
+ {
+ queryBuilder += " WHERE ";
+ for (Map.Entry entry : selectionFieldValues.entrySet()) {
+
+ try{
+ Float f = Float.parseFloat(entry.getValue().toString());
+ queryBuilder += " "+entry.getKey() + " = "+entry.getValue()+" AND";
+ }
+ catch(Exception ex)
+ {
+ queryBuilder += " "+entry.getKey() + " = '"+entry.getValue()+"' AND";
+ }
+
+ }
+ queryBuilder = queryBuilder.substring(0,queryBuilder.length()-3);
+ }
+ //Utils.Log(queryBuilder);
+ updateQuery(queryBuilder);
+ }
+ /**
+ * Used to insert a new row in a table in the database.
+ * @param tableName The name of the table where the row has to be inserted
+ * @param fieldValues the hashmap of column names and values
+ * @throws SQLException
+ */
+ public void insertDatabase(String tableName,Map fieldValues,Map nonStringfieldValues) throws SQLException
+ {
+ String queryBuilder = "INSERT INTO "+tableName;
+ if(nonStringfieldValues==null) nonStringfieldValues = new HashMap();
+ if(fieldValues.size()>0)
+ {
+ queryBuilder += " ("+Utils.Join(new ArrayList(fieldValues.keySet()), ",");
+ if(!nonStringfieldValues.isEmpty())
+ queryBuilder +=","+Utils.Join(new ArrayList(nonStringfieldValues.keySet()), ",");
+ queryBuilder+= " ) VALUES ";
+ ArrayList ll = new ArrayList();
+ for (Iterator i = fieldValues.values().iterator(); i.hasNext();) {
+ ll.add(i.next().toString());
+
+ }
+ ArrayList ll2 = new ArrayList();
+ for (Iterator i = nonStringfieldValues.values().iterator(); i.hasNext();) {
+ ll2.add(i.next().toString());
+
+ }
+ queryBuilder += " ('"+Utils.Join(ll, "','")+"'";
+ if(!ll2.isEmpty())
+ queryBuilder += ","+Utils.Join(ll2, ",");
+ queryBuilder += ") ";
+ }
+ //Utils.Log(queryBuilder);
+
+ executeNonQuery(queryBuilder);
+
+ }
+}
+
+
diff --git a/lib-db/src/main/java/com/fourelementscapital/db/DBManagerDB.java b/lib-db/src/main/java/com/fourelementscapital/db/DBManagerDB.java
new file mode 100755
index 0000000..38e9ddb
--- /dev/null
+++ b/lib-db/src/main/java/com/fourelementscapital/db/DBManagerDB.java
@@ -0,0 +1,33 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.db;
+
+import java.util.List;
+
+/**
+ * Abstract class implements methods related to database manager
+ */
+public abstract class DBManagerDB extends SuperDB {
+
+ /**
+ * Connect database
+ */
+ public void connectDB() throws Exception {
+ super.connectDB(DB_NAME_BBSYNC);
+ }
+
+ /**
+ * List database groups
+ * @return database groups
+ * @throws Exception
+ */
+ public abstract List listDBGroups() throws Exception;
+}
+
+
+
\ No newline at end of file
diff --git a/lib-db/src/main/java/com/fourelementscapital/db/FlexiFieldDB.java b/lib-db/src/main/java/com/fourelementscapital/db/FlexiFieldDB.java
new file mode 100755
index 0000000..ee1e610
--- /dev/null
+++ b/lib-db/src/main/java/com/fourelementscapital/db/FlexiFieldDB.java
@@ -0,0 +1,99 @@
+/******************************************************************************
+*
+* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
+* All rights reserved.
+*
+******************************************************************************/
+
+package com.fourelementscapital.db;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import com.fourelementscapital.db.vo.FlexiField;
+
+/**
+ * Abstract class implements methods related to Flexi Field
+ */
+public abstract class FlexiFieldDB extends SuperDB {
+
+ /**
+ * Connect database
+ */
+ public void connectDB() throws Exception {
+ super.connectDB(DB_NAME_BBSYNC);
+ }
+
+ /**
+ * Get flexi fields
+ * @param tablename tablename string
+ * @return flexi fields
+ * @throws Exception
+ */
+ public abstract List getFlexiFields(String tablename) throws Exception;
+
+ /**
+ * Add flexi field
+ * @param ffield flexi field
+ * @throws Exception
+ */
+ public abstract void addFlexiField(FlexiField ffield) throws Exception;
+
+ /**
+ * Update flexi field
+ * @param id flexi field id
+ * @param ffield flexi field
+ * @throws Exception
+ */
+ public abstract void updateFlexiField(long id,FlexiField ffield) throws Exception;
+
+ /**
+ * Delete flexi field
+ * @param id flexi field id
+ * @throws Exception
+ */
+ public abstract void deleteFlexiField(long id) throws Exception;
+
+ /**
+ * Get flexi field data
+ * @param tablename table name
+ * @param idfield id field
+ * @param idvalue id
+ * @return flexi field data
+ * @throws Exception
+ */
+ public abstract Map getFlexiFieldData (String tablename, String idfield, String idvalue) throws Exception;
+
+ /**
+ * Get flexi field data for lucene token
+ * @param tablename table name
+ * @param idfield id field
+ * @param idvalue id
+ * @return flexi field data
+ * @throws Exception
+ */
+ public abstract Vector