* INITIAL POPULATIONS OF THIS REPO

This commit is contained in:
2021-12-23 13:04:01 +08:00
parent 3165defa2e
commit ed70cad6ea
182 changed files with 22964 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fourelementscapital</groupId>
<artifactId>lib-fileutils</artifactId>
<version>2.0</version>
<licenses>
<license>
<name>The software is only allowed to be used in Four Elements - no license is given to any other parties</name>
</license>
</licenses>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
+29
View File
@@ -0,0 +1,29 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.fourelementscapital</groupId>
<artifactId>lib</artifactId>
<version>${revision}</version>
</parent>
<groupId>com.fourelementscapital</groupId>
<artifactId>lib-fileutils</artifactId>
<packaging>jar</packaging>
<name>lib-fileutils</name>
<description>Common / general utilities</description>
<url>http://www.fourelementscapital.com</url>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,138 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.fileutils;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
/**
* Utility class to convert bean to properties and vice versa.
*/
public class BeanUtil {
/**
* Private constructor
*/
private BeanUtil(){
}
/**
* Converts a JavaBean to a collection of properties
* @param bean The JavaBean to convert
* @return A map of properties
*/
public static Map<String, Object> convertBeanToProperties(Object bean)
throws IntrospectionException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Map<String, Object> properties = new HashMap<String, Object>();
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) {
String name = p.getName();
Method reader = p.getReadMethod();
if (reader != null) {
Object value = reader.invoke(bean);
properties.put(name, value);
}
}
return properties;
}
/**
* Applies a collection of properties to a JavaBean.
* @param properties A map of the properties to set on the JavaBean
* @param bean The JavaBean to set the properties on
*/
public static void convertPropertiesToBean(Map<String, Object> properties, Object bean)
throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) {
String name = p.getName();
Object value = properties.get(name);
Method reader = p.getReadMethod();
Method writer = p.getWriteMethod();
// we only care about "complete" properties
if (reader != null && writer != null) {
if (value != null) {
Class<?> propertyType = writer.getParameterTypes()[0];
Class<?> valueType = value.getClass();
if (!propertyType.isAssignableFrom(valueType)) {
// convert string input values to property type
try {
if (valueType == String.class) {
value = ConvertUtils.convert((String) value, propertyType);
} else if (valueType == String[].class) {
value = ConvertUtils.convert((String[]) value, propertyType);
} else if (valueType == Object[].class) {
// best effort conversion
Object[] objectValues = (Object[]) value;
String[] stringValues = new String[objectValues.length];
for (int i = 0; i < objectValues.length; i++) {
stringValues[i] = objectValues[i] == null ?
null : objectValues[i].toString();
}
value = ConvertUtils.convert(stringValues, propertyType);
}
} catch (ConversionException e) {
throw new IllegalArgumentException("Conversion failed for " +
"property '" + name + "' with value '" + value + "'", e);
}
}
// We only write values that are present in the map. This allows
// defaults or previously set values in the bean to be retained.
writer.invoke(bean, value);
}
}
}
}
/**
* Compares two JavaBeans for equality by comparing their properties and the class of the beans.
* @param bean1 Bean to compare
* @param bean2 Bean to compare
* @return True if {@code bean2} has the same properties with the same values as {@code bean1} and if they share the same class.
*/
public static boolean equals(Object bean1, Object bean2)
throws IntrospectionException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
if (bean1.getClass() != bean2.getClass()) {
return false;
}
BeanInfo bean1Info =
Introspector.getBeanInfo(bean1.getClass(), Object.class);
for (PropertyDescriptor p : bean1Info.getPropertyDescriptors()) {
String name = p.getName();
Method reader = p.getReadMethod();
if (reader != null) {
Object value1 = reader.invoke(bean1);
Object value2 = reader.invoke(bean2);
if ((value1 != null && !value1.equals(value2)) ||
(value2 != null && !value2.equals(value1))) {
return false;
}
}
}
return true;
}
}
@@ -0,0 +1,88 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.fileutils;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Utility class to find specific string in files. Only works in Unix environment.
*/
public class FindStringInFiles {
/**
* Private constructor
*/
private FindStringInFiles(){
}
/**
* Search text
* @param word Text to search
* @param folder Folder where files contain string are located
* @param include_ext Include file extension of the file
* @return search result in Map
* @throws Exception
*/
public static Map search(String word, String folder, String include_ext) throws Exception {
Process process=null;
Runtime runtime = Runtime.getRuntime();
String command[]={"grep","-i","-n","-r","--exclude=*.svn-base","--include=*"+include_ext,word, folder};
process = runtime.exec(command);
BufferedReader br2 = new BufferedReader(new InputStreamReader(process.getInputStream()));
LinkedHashMap<String,ArrayList> rtn=new LinkedHashMap();
String line;
String content="";
while ((line = br2.readLine()) != null) {
if(line!=null && !line.trim().equals("") && line.contains(":") && line.split(":").length>2 ){
String[] arg=line.split(":");
String f,ln;
String occu="";
//windows
if(System.getProperty("os.name").toLowerCase().equals("freebsd")){
f=arg[0];
ln=arg[1];
if(arg.length>=3){
for(int i=2;i<arg.length;i++) occu+=" "+arg[i];
}
}else{
//unix
f=arg[0]+arg[1];
ln=arg[2];
if(arg.length>=4){
for(int i=3;i<arg.length;i++) occu+=" "+arg[i];
}
}
String filename=new File(f).getName();
if(rtn.get(filename)==null) rtn.put(filename, new ArrayList());
rtn.get(filename).add(ln+"|"+occu);
}
}
process.destroy();
return rtn;
}
}
@@ -0,0 +1,55 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.fileutils;
import java.util.Random;
/**
* Generate random string by specify string length.
*/
public class RandomString {
private static final char[] symbols = new char[36];
static {
for (int idx = 0; idx < 10; ++idx)
symbols[idx] = (char) ('0' + idx);
for (int idx = 10; idx < 36; ++idx)
symbols[idx] = (char) ('a' + idx - 10);
}
private static char[] buffer;
private static Random rand = new Random();
/**
* Private constructor
*/
private RandomString() {
}
/**
* Generate random string with length of the string as input parameter
* @param length Length of the generated string
* @return random string
*/
public static String getString(int length) {
if (length < 1) {
throw new IllegalArgumentException("length < 1: " + length);
}
buffer = new char[length];
for (int idx = 0; idx < buffer.length; ++idx) {
buffer[idx] = symbols[rand.nextInt(symbols.length)];
}
return new String(buffer);
}
}
@@ -0,0 +1,89 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.fileutils;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* Split string into List by checking separator in it
*/
public class SplitString {
/**
* Private constructor
*/
private SplitString(){
}
/**
* Get separator character. Check ',' or '\r\n'
* @param separator Separator char
* @return separator
*/
private static String getSeparatorChar(String str){
return (str.indexOf(",")>=0)?",":"\r\n";
}
/**
* Split string into List
* @param str String to be split
* @return split string in list
*/
public static List<String> split(String str){
List<String> rtn=new ArrayList<String>();
if(str!=null && !str.equals("")){
String pline=getSeparatorChar(str);
StringTokenizer st=new StringTokenizer(str,pline);
while(st.hasMoreTokens()){
rtn.add(st.nextToken());
}
}
return rtn;
}
/**
* Split string then convert to lower case
* @param str String to be split
* @return split string in list
*/
public static List<String> splitLowerCase(String str){
List<String> rtn=new ArrayList<String>();
if(str!=null && !str.equals("")){
String pline=getSeparatorChar(str);
StringTokenizer st=new StringTokenizer(str,pline);
while(st.hasMoreTokens()){
rtn.add(st.nextToken().toLowerCase());
}
}
return rtn;
}
/**
* Split string then trim
* @param str String to be split
* @return split string in list
*/
public static List<String> splitTrim(String str){
List<String> rtn = new ArrayList<String>();
if(str!=null && !str.equals("")){
String pline=getSeparatorChar(str);
StringTokenizer st=new StringTokenizer(str,pline);
while(st.hasMoreTokens()){
rtn.add(st.nextToken().trim());
}
}
return rtn;
}
}
@@ -0,0 +1,139 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.fileutils;
import java.util.Map;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class provide function to replace 'place holder' in template with values.
* Example : 'Name : [[name]], Address : [[address]].' will become 'Name : Jon, Address : Bali.'
*/
public class StringPlaceHolder {
public static final String PATTERN = "\\[\\[(.*?)\\]\\]"; // example : [[name]]
public static final String PATTERN_ATTR = "\\\"\\[\\[(.*?)\\]\\]\\\""; // example : \"[[name]]\"
/**
* Private constructor
*/
private StringPlaceHolder() {}
/**
* Get elements (strings) in the template that will be replaced by another string. Use custom pattern.
* @param template Template string
* @param patternAttrStr pattern to find attribute
* @return attributes
*/
public static Vector<String> getAttributePH(final String template, final String patternAttrStr){
Vector<String> v=new Vector<String>();
final StringBuffer sb = new StringBuffer();
final Pattern pattern =
Pattern.compile(patternAttrStr, Pattern.DOTALL);
final Matcher matcher = pattern.matcher(template);
while(matcher.find()){
final String key = matcher.group(1);
if(!v.contains(key)){
v.add(key);
}
}
return v;
}
/**
* Overloading method of getAttributePH() with default pattern attribute values.
* @param template Template string
* @return attributes
*/
public static Vector<String> getAttributePH(final String template) {
return getAttributePH(template, StringPlaceHolder.PATTERN_ATTR);
}
/**
* Get elements (strings) in the template that will be replaced by another string. Use custom pattern.
* The elements in the result found by getAttributePH() will be removed.
* @param template Template string
* @param patternAttrStr pattern to find attribute
* @return elements
*/
public static Vector<String> getElementPH(final String template, final String patternStr){
Vector<String> v=new Vector<String>();
final StringBuffer sb = new StringBuffer();
final Pattern pattern =
Pattern.compile(patternStr, Pattern.DOTALL);
final Matcher matcher = pattern.matcher(template);
while(matcher.find()){
final String key = matcher.group(1);
if(!v.contains(key)){
v.add(key);
}
}
v.removeAll(getAttributePH(template));
return v;
}
/**
* Overloading method of getElementPH() with default pattern values.
* @param template Template string
* @return elements
*/
public static Vector<String> getElementPH(final String template) {
return getElementPH(template, StringPlaceHolder.PATTERN);
}
/**
* Replace strings found by pattern in template with new input values. Use custom pattern.
* @param template Template string
* @param values Replacement values
* @param patternStr pattern to be replaced
* @return string from template with replaced strings
*/
public static String parse(final String template, final Map values, final String patternStr){
final StringBuffer sb = new StringBuffer();
final Pattern pattern =
Pattern.compile(patternStr, Pattern.DOTALL);
final Matcher matcher = pattern.matcher(template);
while(matcher.find()){
final String key = matcher.group(1);
if( values.get(key)!=null){
final String replacement = values.get(key).toString();
if(replacement == null){
matcher.appendReplacement(sb, "");
}else{
matcher.appendReplacement(sb, replacement);
}
}else{
matcher.appendReplacement(sb, "");
}
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* Overloading method of parse() with default pattern values.
* @param template Template string
* @param values Replacement values
* @return string from template with replaced strings
*/
public static String parse(final String template, final Map values){
return parse(template, values, StringPlaceHolder.PATTERN);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="CONSOLE" target="SYSTEM_OUT">
<PatternLayout pattern="%4p %d{HH:mm:ss,SSS} %C - %m%n" />
</Console>
</Appenders>
<Loggers>
<Root level="ERROR">
<AppenderRef ref="CONSOLE"/>
</Root>
</Loggers>
</Configuration>
@@ -0,0 +1,252 @@
/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/
package com.fourelementscapital.fileutils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import junit.framework.TestCase;
/**
* lib-fileutils unit test
*/
public class LibFileUtilsTest extends TestCase {
private static final Logger log = LogManager.getLogger(LibFileUtilsTest.class.getName());
/**
* Test BeanUtil functions
*/
public void testBeanUtil() {
log.debug(">>>>>> testBeanUtil()");
Map<String, Object> properties = new HashMap();
properties.put("id", 1);
properties.put("desc", "description");
SampleBean bean1 = new SampleBean();
try {
log.debug("convertPropertiesToBean() :");
BeanUtil.convertPropertiesToBean(properties, bean1);
if (1 == bean1.getId() && "description".equals(bean1.getDesc())) {
log.debug("New value from bean. bean1.getId() : '"
+ bean1.getId() + "', bean1.getDesc() : '"
+ bean1.getDesc() + "'");
assertTrue(true);
}
log.debug("convertBeanToProperties() :");
Map m = BeanUtil.convertBeanToProperties(bean1);
if (m != null) {
log.debug("New properties from bean conversion : " + m);
assertTrue(true);
}
log.debug("equals() :");
SampleBean bean2 = new SampleBean();
BeanUtil.convertPropertiesToBean(properties, bean2);
log.debug("Is bean1 & bean2 equals : "
+ BeanUtil.equals(bean1, bean2));
} catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
}
/**
* Bean class for testBeanUtilConvertPropertiesToBean() testing purpose
*/
private class SampleBean {
private int id;
private String desc;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
/**
* Test FindStringInFiles.search(). Only works in unix environment.
*/
public void testFindStringInFilesSearch() {
log.debug(">>>>>> testFindStringInFilesSearch()");
// Remove the comment tag to test. The code are commented out to prevent error on Windows OS when installing this lib :
/*
boolean isPass = false;
try {
// search 'log4j' word in : './*.properties' :
String path = "./";
String wordToSearch = "log4j"; String extension = ".properties";
Map r_result = FindStringInFiles.search(wordToSearch, path, extension);
if (r_result != null && r_result.size() > 0 ) {
log.debug("Search 'log4j' word in : './*.properties'. Result : " +
r_result.size() + " word(s) found."); isPass = true;
}
} catch (Exception e) {
e.printStackTrace();
}
assertTrue(isPass);
*/
assertTrue(true);
}
/**
* Test InputStringTokenParser
*/
public void testInputStringTokenParser() {
log.debug(">>>>>> testInputStringTokenParser()");
log.debug("parseFreeTextTokens() :");
boolean isPass = true;
String str = "Aaa,bBb,ccC";
List<String> a = SplitString.split(str);
if (a.size() == 3) {
if (!"Aaa".equals(a.get(0))) {
isPass = false;
}
;
if (!"bBb".equals(a.get(1))) {
isPass = false;
}
;
if (!"ccC".equals(a.get(2))) {
isPass = false;
}
;
} else {
isPass = false;
}
log.debug("'" + str + "' is parsed to : " + a);
assertTrue(isPass);
log.debug("parseFreeTextTokensLowerCase() :");
isPass = true;
str = "Aaa,bBb,ccC";
a = SplitString.splitLowerCase(str);
if (a.size() == 3) {
if (!"aaa".equals(a.get(0))) {
isPass = false;
}
;
if (!"bbb".equals(a.get(1))) {
isPass = false;
}
;
if (!"ccc".equals(a.get(2))) {
isPass = false;
}
;
} else {
isPass = false;
}
log.debug("'" + str + "' is parsed to : " + a);
assertTrue(isPass);
log.debug("parseFreeTextTokensTrim() :");
isPass = true;
str = "Aaa bBb , ccC DDD ";
a = SplitString.splitTrim(str);
if (a.size() == 2) {
if (!"Aaa bBb".equals(a.get(0))) {
isPass = false;
}
;
if (!"ccC DDD".equals(a.get(1))) {
isPass = false;
}
;
} else {
isPass = false;
}
log.debug("'" + str + "' is parsed to : " + a);
assertTrue(isPass);
}
/**
* Test ParseXMLPlaceHolder
*/
public void testParseXMLPlaceHolder() {
log.debug(">>>>>> testParseXMLPlaceHolder()");
boolean isPass = false;
log.debug("parse() :");
String template = "Name : [[name]], Address : [[address]].";
Map<String, String> m = new HashMap<String, String>();
m.put("name", "Jon");
m.put("address", "Bali");
String str = StringPlaceHolder.parse(template, m);
log.debug("parse result : '" + str + "'");
if ("Name : Jon, Address : Bali.".equals(str)) {
isPass = true;
}
assertTrue(isPass);
log.debug("getElementPH() :");
template = "Name : \"[[name]]\", Address : [[address]].";
Vector<String> v = StringPlaceHolder.getElementPH(template);
log.debug("getElementPH result : " + v);
if (v != null && v.size() > 0) {
isPass = true;
}
assertTrue(isPass);
log.debug("getAttributePH() :");
template = "Name : \"[[name]]\", Address : [[address]].";
v = StringPlaceHolder.getAttributePH(template);
log.debug("getAttributePH result : " + v);
if (v != null && v.size() > 0) {
isPass = true;
}
assertTrue(isPass);
}
/**
* Test RandomString
*/
public void testRandomString() {
log.debug(">>>>>> testRandomString()");
String str = RandomString.getString(10);
log.debug("Random string result : '" + str + "'");
if (!"".equals(str)) {
assertTrue(true);
} else {
assertTrue(false);
}
}
}