Thursday, October 15, 2020

Java Basic Util - Scaffold

 1 Exception scaffold to run business and convert all exception to BusinessException.


package basic.util.scaffold;


import basic.util.exception.BaseException;

import basic.util.exception.BusinessException;

import basic.util.function.IAction;


public class ExceptionContext {


public static void runOrThrowBusinessException(IAction action, String function) {

try {

action.run();

} catch (Exception exception) {

BusinessException.throwException(BaseException.Failed, BusinessException.ExceptionFailed, exception, function);

}

}

}

2 Transaction scaffold to run business in transaction or XA transaction.

package basic.util.scaffold;

import basic.util.function.IAction;
import basic.util.orm.EntityContext;
import basic.util.orm.EntityOperation;
import basic.util.orm.XAContext;

public class TransactionContext {

public static void runInTransaction(EntityContext entityContext, IAction action) {
try {
entityContext.beginTransaction();
action.run();
entityContext.commitTransaction();
} catch (Exception exception) {
entityContext.rollbackTransaction();
throw exception;
}
}
public static void runInXATransaction(IAction action) {
try {
XAContext.beginXA();
action.run();
XAContext.commitXA();
} catch (Exception exception) {
XAContext.rollbackXA();
throw exception;
}
}
public static void main(String[] args) {
TransactionContext transactionContext = new TransactionContext();
testCommit(transactionContext);
testRollback(transactionContext);

testXACommit(transactionContext);
testXARollback(transactionContext);
}

private static void testXACommit(TransactionContext transactionContext) {
EntityContext entityContext = new EntityContext("mssql");
EntityOperation operation = entityContext.getEntityOperation();
//entityContext.monitor(true);
EntityContext entityContext2 = new EntityContext("mssql2");
EntityOperation operation2 = entityContext2.getEntityOperation();
//entityContext2.monitor(true);
IAction action = () -> {
DataModel data = new DataModel();
data.setCode(1);
data.setValue("test code 1");
operation.add(data);
operation2.add(data);
data.setValue("test code 11");
operation.update(data);
operation2.update(data);
};
runInXATransaction(action);
operation.selectOne(DataModel.class, 1).ifPresent(object -> {
DataModel model = (DataModel) object;
System.out.println(model.getValue());
});
operation2.selectOne(DataModel.class, 1).ifPresent(object -> {
DataModel model = (DataModel) object;
System.out.println(model.getValue());
});
}
private static void testXARollback(TransactionContext transactionContext) {
EntityContext entityContext = new EntityContext("mssql");
EntityOperation operation = entityContext.getEntityOperation();
//entityContext.monitor(true);
EntityContext entityContext2 = new EntityContext("mssql2");
EntityOperation operation2 = entityContext2.getEntityOperation();
//entityContext2.monitor(true);
DataModel data = new DataModel();
data.setCode(1);
data.setValue("test code 1");
IAction action = () -> {
operation.delete(DataModel.class, data.getCode());
throw new RuntimeException("test exception");
};

try {
ExceptionContext.runOrThrowBusinessException(()->runInTransaction(entityContext, action), "testRollback");;
} catch (Exception exception) {
System.out.println(exception.getLocalizedMessage());
}
IAction action2 = () -> {
operation2.delete(DataModel.class, data.getCode());
throw new RuntimeException("test exception");
};

try {
ExceptionContext.runOrThrowBusinessException(()->runInTransaction(entityContext2, action2), "testRollback");;
} catch (Exception exception) {
System.out.println(exception.getLocalizedMessage());
}
operation.selectOne(DataModel.class, 1).ifPresent(object -> {
DataModel model = (DataModel) object;
System.out.println(model.getValue());
});
operation2.selectOne(DataModel.class, 1).ifPresent(object -> {
DataModel model = (DataModel) object;
System.out.println(model.getValue());
});
operation.delete(DataModel.class, data.getCode());
operation2.delete(DataModel.class, data.getCode());
}
private static void testCommit(TransactionContext transactionContext) {
EntityContext entityContext = new EntityContext("mssql");
EntityOperation operation = entityContext.getEntityOperation();
//entityContext.monitor(true);
IAction action = () -> {
DataModel data = new DataModel();
data.setCode(1);
data.setValue("test code 1");
operation.add(data);
data.setValue("test code 11");
operation.update(data);
};
runInTransaction(entityContext, action);
operation.selectOne(DataModel.class, 1).ifPresent(object -> {
DataModel model = (DataModel) object;
System.out.println(model.getValue());
});
}
private static void testRollback(TransactionContext transactionContext) {
EntityContext entityContext = new EntityContext("mssql");
EntityOperation operation = entityContext.getEntityOperation();
//entityContext.monitor(true);
DataModel data = new DataModel();
data.setCode(1);
data.setValue("test code 1");
IAction action = () -> {
operation.delete(DataModel.class, data.getCode());
throw new RuntimeException("test exception");
};

try {
ExceptionContext.runOrThrowBusinessException(()->runInTransaction(entityContext, action), "testRollback");;
} catch (Exception exception) {
System.out.println(exception.getLocalizedMessage());
}
operation.selectOne(DataModel.class, 1).ifPresent(object -> {
DataModel model = (DataModel) object;
System.out.println(model.getValue());
});
operation.delete(DataModel.class, data.getCode());
}
}

3 This is the value object used in test case.

package basic.util.scaffold;

import basic.util.orm.annotation.Column;
import basic.util.orm.annotation.Key;
import basic.util.orm.annotation.Table;

@Table(tableName="Test")
public class DataModel {
@Key(autoIncrement = Key.AutoIncrement.FALSE,column = @Column(columnName = "code")) 
private int code;
@Column(columnName = "value") 
private String value;
public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}
public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}
}

Monday, October 12, 2020

Java Basic Util - BasicUtil

 package basic.util;


import java.sql.Timestamp;

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Date;


import basic.util.exception.BaseException;


public class BasicUtil {

private static ArrayList<String> baseTypeList = new ArrayList<String>() {

private static final long serialVersionUID = 1L;

{

add("int");

add("double");

add("float");

add("long");

add("short");

add("boolean");

add("byte");

add("char");

add("void");

}

};


public static boolean isAnyNull(Object... values) {

if (values.length <= 0)

return true;


for (Object value : values) {

if (value == null) {

return true;

}

}


return false;

}

public static boolean isSystemClass(Class<?> clz) {   

        return clz != null && clz.getClassLoader() == null;   

    }

public static boolean isBasiType(String typeName) {   

return baseTypeList.contains(typeName);

    }

public static boolean isCollectionOrArray(Class<?> returnType) {

        boolean isCollection = Collection.class.isAssignableFrom(returnType);

        boolean isArray = returnType.isArray();

        return isCollection || isArray;

    }

public static Date parseStringToDate(String date) {

String parse = date.replaceFirst("[0-9]{4}([^0-9]?)", "yyyy$1");

parse = parse.replaceFirst("^[0-9]{2}([^0-9]?)", "yy$1");

parse = parse.replaceFirst("([^0-9]?)[0-9]{1,2}([^0-9]?)", "$1MM$2");

parse = parse.replaceFirst("([^0-9]?)[0-9]{1,2}( ?)", "$1dd$2");

parse = parse.replaceFirst("( )[0-9]{1,2}([^0-9]?)", "$1HH$2");

parse = parse.replaceFirst("([^0-9]?)[0-9]{1,2}([^0-9]?)", "$1mm$2");

parse = parse.replaceFirst("([^0-9]?)[0-9]{1,2}([^0-9]?)", "$1ss$2");

DateFormat format = new SimpleDateFormat(parse);


Date result = null;

try {

result = format.parse(date);

} catch (ParseException exception) {

BaseException.throwException(exception);

}

return result;

}

public static Date parseStringToTimestamp(String date) {

return new Timestamp(parseStringToDate(date).getTime());

}


}


Java Basic Util - StringUtil

package basic.util;


public class StringUtil {

public static boolean isAnyEmpty(String... values) {

if (values.length <= 0)

return true;


for (String value : values) {

if (value == null || value.isEmpty()) {

return true;

}

}


return false;

}

public static String turnFirstUp(String str) {

/*char[] ch = str.toCharArray();

if (ch[0] >= 'a' && ch[0] <= 'z') {

ch[0] = (char) (ch[0] - 32);

}

return new String(ch);*/

if (isAnyEmpty(str)) return str;

return str.substring(0, 1).toUpperCase() + str.substring(1);

}

public static String turnFirstLow(String str) {

if (isAnyEmpty(str)) return str;

return str.substring(0, 1).toLowerCase() + str.substring(1);

}


public static String underlineToBigCamel(String str) {

return underlineToSmallCamel(turnFirstUp(str));

}


public static String underlineToSmallCamel(String str) {

if (str == null || "".equals(str.trim())) {

return "";

}

int len = str.length();

StringBuilder sb = new StringBuilder(len);

for (int i = 0; i < len; i++) {

char c = str.charAt(i);

if (c == '_') {

if (++i < len) {

sb.append(Character.toUpperCase(str.charAt(i)));

}

} else {

sb.append(c);

}

}

return sb.toString();

}

}


Java Basic Util - CopyUtil

package basic.util;


import java.lang.reflect.Field;

import java.math.BigInteger;

import java.time.LocalDateTime;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.HashMap;

import java.util.List;

import java.util.Map;


public class CopyUtil {

public static void copy(Object src, Object dest) {

Map<String, Object> srcMap = getSourceValues(src);

populateDestination(dest, srcMap);

}


private static void populateDestination(Object dest, Map<String, Object> srcMap) {

List<Field> fieldList = getAllFields(dest);


for (Field fd : fieldList) {

if (srcMap.get(fd.getName()) == null) continue;

try {

fd.setAccessible(true);

fd.set(dest, srcMap.get(fd.getName()));

} catch (Exception e) {

e.printStackTrace();

}

}

}


private static Map<String, Object> getSourceValues(Object src) {

Map<String, Object> srcMap = new HashMap<String, Object>();

List<Field> fieldList = getAllFields(src);


for (Field fd : fieldList) {

try {

fd.setAccessible(true);

srcMap.put(fd.getName(), fd.get(src));

} catch (Exception e) {

e.printStackTrace();

}

}

return srcMap;

}


private static List<Field> getAllFields(Object src) {

List<Field> fieldList = new ArrayList<>();


Class<?> tempClass = src.getClass();

while (tempClass != null) {

fieldList.addAll(Arrays.asList(tempClass.getDeclaredFields()));

tempClass = tempClass.getSuperclass();

}

return fieldList;

}

public static void main(String[] args) {

CopyUtil copyUtil = new CopyUtil();

Child child = copyUtil.new Child();


child.setBigInt(new BigInteger("123456"));

child.setDate(LocalDateTime.now());

child.setInteger(21);

child.setString("test");

child.setFnum(11.11f);

child.setDnum(22.22d);

child.setCharacter("parent string");

Child another = copyUtil.new Child();

CopyUtil.copy(child, another);

System.out.println("BigInt:" + another.getBigInt());

System.out.println("Date:" + another.getDate());

System.out.println("Character:" + another.getCharacter());

System.out.println(another.getInteger());

System.out.println(another.getString());

System.out.println(another.getFnum());

System.out.println(another.getDnum());

}


class Parent {

private BigInteger bigInt;


private LocalDateTime date;


private String character;


public BigInteger getBigInt() {

return bigInt;

}


public void setBigInt(BigInteger bigInt) {

this.bigInt = bigInt;

}


public LocalDateTime getDate() {

return date;

}


public void setDate(LocalDateTime date) {

this.date = date;

}


public String getCharacter() {

return character;

}


public void setCharacter(String character) {

this.character = character;

}

}


class Child extends Parent {

private int integer;

private float fnum;

private double dnum;

private String string;


public int getInteger() {

return integer;

}


public void setInteger(int integer) {

this.integer = integer;

}


public String getString() {

return string;

}


public void setString(String string) {

this.string = string;

}


public float getFnum() {

return fnum;

}


public void setFnum(float fnum) {

this.fnum = fnum;

}


public double getDnum() {

return dnum;

}


public void setDnum(double dnum) {

this.dnum = dnum;

}

}

}


Java Basic Util - FileUtil

 package basic.util;


import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.util.Properties;


import basic.util.exception.BaseException;

import basic.util.exception.BusinessException;


public class FileUtil {


public static void savePropertiesToFile(Properties prop, String path) {

ensureFolderExist(path);

try (OutputStream output = new FileOutputStream(path)) {

prop.store(output, null);

} catch (IOException exception) {

BaseException.throwException(BaseException.NotLoaded, exception, "Setting File", path);

}

}


public static void appendPropertiesToFile(Properties prop, String path) {

Properties propTosave = loadFileToProperties(path);

for (String key : prop.stringPropertyNames()) {

propTosave.setProperty(key, prop.getProperty(key));

}


savePropertiesToFile(propTosave, path);

}


public static Properties loadFileToProperties(String path) {

Properties prop = new Properties();

try (InputStream input = new FileInputStream(path)) {

prop.load(input);

} catch (IOException exception) {

BaseException.throwException(BusinessException.NotLoaded, exception, "Setting File", path);

}

return prop;

}


public static boolean isFileExist(String path) {

File file = new File(path);

return file.exists();

}


public static String readFile(String path) {

ensureFileExist(path);

StringBuilder builder = new StringBuilder();

try (BufferedReader br = new BufferedReader(new FileReader(path))) {

String line = br.readLine();

while (line != null) {

builder.append(line);

builder.append(System.lineSeparator());

line = br.readLine();

}

} catch (FileNotFoundException exception) {

BaseException.throwException(BaseException.NotFound, exception, "Setting File", path);

} catch (IOException exception) {

BaseException.throwException(BaseException.NotLoaded, exception, "Setting File", path);

}


return builder.toString();


}


public static void saveFile(String content, String path) {

ensureFolderExist(path);

try (OutputStreamWriter pw = new OutputStreamWriter(new FileOutputStream(path))) {

pw.write(content);

} catch (FileNotFoundException exception) {

BaseException.throwException(BaseException.NotFound, "Setting File", path);

} catch (IOException exception) {

BaseException.throwException(BaseException.Failed, exception, "Save file", "Setting File", path);

}

}

public static void appendFile(String content, String path) {

ensureFileExist(path);

try (OutputStreamWriter pw = new OutputStreamWriter(new FileOutputStream(path, true))) {

pw.write(content);

} catch (FileNotFoundException exception) {

BaseException.throwException(BaseException.NotFound, exception, "Setting File", path);

} catch (IOException exception) {

BaseException.throwException(BaseException.Failed, exception,"Save file", "Setting File", path);

}

}

public static String readJsonFile(String path) {

String content = readFile(path);

        return "[" + content + "]";

}

public static void saveJsonFile(String content, String path) {

if (StringUtil.isAnyEmpty(content)) return;

saveFile(removeBracket(content), path);

}

public static void appendJsonFile(String content, String path) {

if (StringUtil.isAnyEmpty(content)) return;

File file = new File(path);

if (file.length() > 0) appendFile("," + removeBracket(content), path);

else appendFile(removeBracket(content), path);

}


private static String removeBracket(String value) {

String result = value;

if (result.substring(0, 1).equals("["))

result=result.substring(1);

if (result.substring(result.length() - 1, result.length()).equals("]"))

result=result.substring(0, result.length() - 1);

return result;

}

public static void ensureFolderExist(String path) {

File file = new File(path);

if (!file.getParentFile().exists()) {

file.getParentFile().mkdirs();

}

}


public static void ensureFileExist(String path) {

File file = new File(path);

if (!file.getParentFile().exists()) {

file.getParentFile().mkdirs();

}


if (!file.exists()) {

try {

file.createNewFile();

} catch (IOException exception) {

BaseException.throwException(exception);

}

}

}


public static File getFile(String path) {

ensureFolderExist(path);


File file = new File(path);

if (!file.exists()) {

try {

file.createNewFile();

} catch (IOException exception) {

BaseException.throwException(BaseException.Failed, "Create", "File", path);

}

}

return file;

}

public static void main(String[] args) {

ensureFileExist("C:/abcd/aa.txt");

}

}


Java Basic Util - ViewLoader

 package basic.util;


import java.io.IOException;

import java.util.Locale;

import java.util.Optional;


import basic.util.exception.BaseException;

import basic.util.resource.ResourceUtil;

import javafx.fxml.FXMLLoader;

import javafx.scene.layout.Pane;


public class ViewLoader {


final public static String MenuBarPath = "/com/atlastool/view/MenuBar.fxml";

final public static String SettingPath = "/com/atlastool/view/Setting.fxml";

public static Optional<Pane> load(String path, Locale locale) {

FXMLLoader fxmlLoader = new FXMLLoader();

        fxmlLoader.setResources(ResourceUtil.getResourceBundle());

Pane pane = null;

try {

pane = (Pane) fxmlLoader.load(ViewLoader.class

.getResource(path).openStream());

pane.setUserData(fxmlLoader.getController());

} catch (IOException exception) {

BaseException.throwException(BaseException.NotLoaded, exception, "Fxml File", path);

} catch (NullPointerException exception) {

BaseException.throwException(BaseException.NotFound, exception, "Fxml File", path);

}

return Optional.ofNullable(pane);

}

}


Java Basic Util - RegexUtil

 package basic.util;


import java.util.regex.Matcher;

import java.util.regex.Pattern;


public class RegexUtil {

public final static String IpRegEx = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";

public final static String PortRegEx = "^()([1-9]|[1-5]?[0-9]{2,4}|6[1-4][0-9]{3}|65[1-4][0-9]{2}|655[1-2][0-9]|6553[1-5])$";

public final static String UrlRegEx = "^(ht|f)tp(s?)\\:\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*(:(0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\'\\/\\\\\\+&%\\$#_]*)?$";

public static boolean validate(String value, String regex) {

Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(value);

return  matcher.matches(); 

}

}


Sunday, October 11, 2020

Java Basic Util - MQTT

1

 package basic.util.mqtt;


import java.io.UnsupportedEncodingException;

import java.nio.charset.Charset;

import java.util.Properties;


import org.eclipse.paho.mqttv5.client.IMqttToken;

import org.eclipse.paho.mqttv5.client.MqttCallback;

import org.eclipse.paho.mqttv5.client.MqttClient;

import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;

import org.eclipse.paho.mqttv5.client.MqttDisconnectResponse;

import org.eclipse.paho.mqttv5.common.MqttException;

import org.eclipse.paho.mqttv5.common.MqttMessage;

import org.eclipse.paho.mqttv5.common.packet.MqttProperties;


import basic.util.FileUtil;

import basic.util.StringUtil;

import basic.util.exception.BaseException;

import basic.util.log.Log;


public class MqttHandler {

private static final String CharSetUTF8 = "UTF-8";

private volatile MqttClient mqttClient; 

private volatile MqttMessage mqttMessage;

private Properties settingProperties;

public MqttHandler(Properties prop) {

settingProperties = prop;

}

private void setSettingProperties(Properties settingProperties) {

this.settingProperties = settingProperties;

}

public void startClient() {

    try {

        //mqttClient = new MqttClient("tcp://mqtt.eclipse.org:1883", "test1");

     String host = settingProperties.getProperty("DataHost");

     String port = settingProperties.getProperty("DataPort");

     if (StringUtil.isAnyEmpty(host, port)) 

     BaseException.throwException("Host or port is invalid for mqtt.");

    

     mqttClient = new MqttClient("tcp://" + host + ":" + port, "test1");

    } catch (MqttException exception) {

     BaseException.throwException(exception);

    }

    

    MqttConnectionOptions options = new MqttConnectionOptions();

    String userName = settingProperties.getProperty("DataUserName");

    String password = settingProperties.getProperty("DataPassword");

    if (!StringUtil.isAnyEmpty(userName, password)) {

     options.setUserName(userName);

     try {

options.setPassword(password.getBytes(CharSetUTF8));

} catch (UnsupportedEncodingException exception) {

BaseException.throwException(exception);

}

    }

         

    options.setConnectionTimeout(5); 

   // options.setCleanSession(getCleanSession());

    options.setKeepAliveInterval(10);

    options.setAutomaticReconnect(true); 

    try {

        mqttClient.setCallback(new BtcMqttCallback());

        mqttClient.connect(options);

        subscribe();

    } catch (Exception exception) {

     close();

     BaseException.throwException(exception);

    }

}

public void restartClient() {

close();

startClient();

}

public void restartClient(Properties settings) {

setSettingProperties(settings);

restartClient();

}

public void close() {

if (isConnected()) {

try {

mqttClient.disconnect();

mqttClient.close(true);

} catch (MqttException exception) {

Log.severe(exception);

}

}

}

public boolean isConnected() {

if (mqttClient != null && mqttClient.isConnected()) return true;

else return false;

}

public void sendToMqtt(String data) {

if (!isConnected()) BaseException.throwException("Connection to mqtt has been closed.");

    try {

        if (mqttMessage == null) {

            mqttMessage = new MqttMessage();

            mqttMessage.setQos(getQos());

            //mqttMessage.setRetained(true);

        }

        mqttMessage.setPayload(data.getBytes(CharSetUTF8)); 

        mqttClient.publish(settingProperties.getProperty("DataTopic"), mqttMessage);

    } catch (Exception exception) {

     BaseException.throwException(exception);

    }

}


private int getQos() {

String qos = settingProperties.getProperty("DataQos");

if (StringUtil.isAnyEmpty(qos)) return 0;

else return Integer.parseInt(qos);

}

public class BtcMqttCallback implements MqttCallback {    

@Override

public void authPacketArrived(int arg0, MqttProperties properties) {

//Log.info("auth Packet Arrived:" + properties.getUserProperties());

}

@Override

public void deliveryComplete(IMqttToken token) {

Log.info("delivery Complete:" + token.isComplete());

}

@Override

public void disconnected(MqttDisconnectResponse response) {

Log.info(response.getReasonString());

}

@Override

public void mqttErrorOccurred(MqttException exception) {

Log.severe(exception);

}

@Override

public void connectComplete(boolean reconnect, String serverURI) {

Log.info("connectComplete() reconnect:" + reconnect + " serverURI:" + serverURI);

        subscribe();

}

@Override

public void messageArrived(String topic, MqttMessage message) throws Exception {

        String msg = new String(message.getPayload(), Charset.forName(CharSetUTF8));

        Log.info( "messageArrived() topic:" + topic);

        Log.info(msg);

        FileUtil.saveJsonFile(msg, settingProperties.getProperty("DataFilePath"));

}

}

private void subscribe() {

    try {

        int[] Qos = {getQos()};

        String[] topic1 = {settingProperties.getProperty("DataTopic")};

        mqttClient.subscribe(topic1, Qos);

    } catch (Exception exception) {

     BaseException.throwException(exception);

    }

}

public static void main(String[] args) {

//Properties prop = SettingController.getSetting();

//MqHandler mqHandler = new MqHandler(prop);

//mqHandler.startClient();

}

}


2 Can use MQTTBox-win to test.

Java Basic Util - NIO.2 - Socket Handler

 1

package basic.util.socket;


public class BaseSocketHandler {

private int port;

private boolean isReady;


public BaseSocketHandler(int port) {

this.port = port;

}

protected int getPort(){

return port;

}

protected void setPort(int port){

this.port = port;

}

public boolean isReady() {

return isReady;

}


public void setReady(boolean isReady) {

this.isReady = isReady;

}

public static void main(String[] args) {

System.out.println(Command.ready);

}


}

2
package basic.util.socket;

import java.io.IOException;

import basic.util.log.Log;

public class ServerSocketHandler extends BaseSocketHandler {
private ServerSocket serverSocket;
    public ServerSocketHandler(int port) {
    super(port);       
    }  
    
    public void run() {
    //ServerSocket serverSocket = new ServerSocket(getPort());
    serverSocket = new ServerSocket(getPort());
    serverSocket.run(this);
    }
    
    public void reRun() {
    close();
    run();
    }
    
public void reRun(int port) {
this.setPort(port);
reRun();
}
    
    public boolean isListening() {
    if (serverSocket != null && serverSocket.getListener() != null && serverSocket.getListener().isOpen()) return true;
    else return false;
    }

    public void close() {
if (isListening()) {
    try {
    serverSocket.getListener().close();
} catch (IOException exception) {
Log.severe(exception);
}
    }
}
    
    public String getDataFilePath() {
    //return SettingController.getSetting().getProperty(SettingController.DataFilePath); 
    return "C:/data.txt";
    }
    
    public String getDoneResultFilePath() {
    //return SettingController.getSetting().getProperty(SettingController.DoneFilePath);   
    return "C:/result.txt";
    }
}

3
package basic.util.socket;

import basic.util.exception.BaseException;
import basic.util.log.Log;

public class BaseClientSocketHandler extends BaseSocketHandler {
final private String serverHost;
private BaseException throwable;

public BaseClientSocketHandler(String serverHost, int port) {
super(port);
this.serverHost = serverHost;
}

public String getServerHost() {
return serverHost;
}
public Throwable getThrowable() {
return throwable;
}

public void retainThrowable(String message, Throwable throwable, String... parameters) {
this.throwable = new BaseException(message, throwable, parameters);
Log.severe(throwable);
}
protected void throwWhenException() {
if (getThrowable() != null) {
throw throwable;
}
}
protected void waitAsyncDone() {
try {
while (!isReady()) {
Thread.sleep(10);
}
} catch (InterruptedException exception) {
BaseException.throwException("Current thread is interrupted", exception);
}
}
}

4
package basic.util.socket;

public class ClientSocketHandler extends BaseClientSocketHandler {
    public ClientSocketHandler(String serverHost, int port) {
    super(serverHost, port);
    }

private ClientSocket getClientSocket() {
return new ClientSocket(getServerHost(), getPort());
}
    
public void transferFile(Command cmd, String path) {
setData(path);
ClientSocket clientSocket = getClientSocket();
    clientSocket.run(this, cmd);
waitAsyncDone();
throwWhenException();
}
public void sendData(Command cmd, String data) {
setData(data);
ClientSocket clientSocket = getClientSocket();
    clientSocket.run(this, cmd);
waitAsyncDone();
throwWhenException();
}
private String data;
public String getData() {
    return data;   
    }
private void setData(String data) {
    this.data = data;   
    }
}

Java Basic Util - NIO.2 - Socket Channel

 1

package basic.util.socket;


import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.AsynchronousSocketChannel;

import java.nio.channels.FileChannel;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.Future;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.TimeoutException;


import basic.util.FileUtil;

import basic.util.log.Log;


public class BaseSocket {

protected static final String AccessChannelFailed = "{0} to {1}:{2} failed";

protected static final String ExceptionWrong = "Exception.Wrong";

protected static final int ReadTimeOut = 20;


// Allocate a byte buffer (4K)

public static final int BufferSize = 4 * 1024;

final private int port;

public BaseSocket(int port) {

        this.port = port;

}

protected int getPort(){

return port;

}

protected static String readBufferData(ByteBuffer byteBuffer, int bytesRead) {

// Make the buffer ready to read

byteBuffer.flip();


// Convert the buffer into a line

byte[] lineBytes = new byte[bytesRead];

byteBuffer.get(lineBytes, 0, bytesRead);

byteBuffer.clear();

String line = new String(lineBytes);

return line;

}

protected static String readFromSocket(AsynchronousSocketChannel channel, ByteBuffer byteBuffer)

throws InterruptedException, ExecutionException, TimeoutException {

int bytesRead;

StringBuilder builder = new StringBuilder();

byteBuffer.clear();

bytesRead = channel.read(byteBuffer).get(ReadTimeOut, TimeUnit.SECONDS);

while (bytesRead != -1) {

String line = readBufferData(byteBuffer, bytesRead);


if (Command.Bye.getValue().equals(line)) {

break;

}

System.out.println("Message: " + line);

builder.append(line);

// Read the next line

bytesRead = channel.read(byteBuffer).get(ReadTimeOut, TimeUnit.SECONDS);

}

return builder.toString();

}

protected static void writeChannel(AsynchronousSocketChannel channel, String value) throws InterruptedException {

Future<Integer> future = channel.write( ByteBuffer.wrap(value.getBytes() ) );

while(!future.isDone()) {

    Thread.sleep(1);

}

}

protected void closeChannel(AsynchronousSocketChannel channel) {

try {

// Close the connection if we need to

if (channel != null && channel.isOpen()) {

channel.close();

}

} catch (IOException e1) {

e1.printStackTrace();

}

}

protected static void readToFile(AsynchronousSocketChannel channel, ByteBuffer byteBuffer, String path)

throws InterruptedException, ExecutionException, TimeoutException, IOException,

FileNotFoundException {

File file = FileUtil.getFile(path); 

int bytesRead;

try (FileOutputStream fos = new FileOutputStream(file);

FileChannel outChannel = fos.getChannel();) {


//byteBuffer.clear();

bytesRead = channel.read(byteBuffer).get(ReadTimeOut, TimeUnit.SECONDS);

while (bytesRead != -1) {

byteBuffer.flip();

byte[] lineBytes = new byte[bytesRead];

byteBuffer.get(lineBytes, 0, bytesRead);

String line = new String(lineBytes);

System.out.println("bytesRead:" + bytesRead); 

System.out.println("data:" + line);

if (Command.Bye.getValue().equals(line)) {

break;

}

//outChannel.write(byteBuffer);

outChannel.write(ByteBuffer.wrap( lineBytes ));

byteBuffer.clear();

// Read the next line

bytesRead = channel.read(byteBuffer).get(ReadTimeOut, TimeUnit.SECONDS);

}

}

}

protected static void readFromFile(AsynchronousSocketChannel channel, ByteBuffer byteBuffer, String path)

throws InterruptedException {

File file = FileUtil.getFile(path);

int bytesRead;

try (FileInputStream fis = new FileInputStream(file);

FileChannel inChannel = fis.getChannel();) {

byteBuffer.clear();

bytesRead = inChannel.read(byteBuffer);

while (bytesRead != -1) {

byteBuffer.flip();


byte[] lineBytes = new byte[bytesRead];

byteBuffer.get(lineBytes, 0, bytesRead);

String line = new String(lineBytes);

System.out.println("data:" + line);

//channel.write(ByteBuffer.wrap(lineBytes));

writeChannel(channel, line);


byteBuffer.clear();

bytesRead = inChannel.read(byteBuffer);

}

} catch (IOException exception) {

Log.severe(exception);

}

}

}

2
package basic.util.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import basic.util.exception.BaseException;
import basic.util.log.Log;

public class ServerSocket extends BaseSocket {
private AsynchronousServerSocketChannel listener;
public AsynchronousServerSocketChannel getListener() {
return listener;
}
public ServerSocket(int port) {
super(port);
}

public void run(ServerSocketHandler serverSocket) {
try {
// Create an AsynchronousServerSocketChannel that will listen on port 5000
listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(getPort()));
} catch (IOException exception) {
BaseException.throwException(exception);
}
// Listen for a new request
listener.accept(serverSocket, new CompletionHandler<AsynchronousSocketChannel, ServerSocketHandler>() {

@Override
public void completed(AsynchronousSocketChannel channel, ServerSocketHandler attachment) {
try {
Log.info("Connect from: " + channel.getRemoteAddress());
} catch (IOException e) {
Log.severe(e);
}
// Accept the next connection
listener.accept(null, this);

// Ready for the client
channel.write(ByteBuffer.wrap(Command.ready.getValue().getBytes()));

// Allocate a byte buffer (4K) to read from the client
ByteBuffer byteBuffer = ByteBuffer.allocate(BufferSize);
try {
// Read the first line
int bytesRead = channel.read(byteBuffer).get(ReadTimeOut, TimeUnit.SECONDS);
String cmd = readBufferData(byteBuffer, bytesRead);
                    Command.match(cmd).ifPresent(command -> command.serverAction(channel, byteBuffer, attachment));
/*if (Command.getServerData.getValue().equals(cmd)) {
readFromFile(channel, byteBuffer, attachment.getDataFilePath());
} else if (Command.sendServerResult.getValue().equals(cmd)) {
String content = readFromSocket(channel, byteBuffer);
FileUtil.appendJsonFile(content, attachment.getDoneResultFilePath());
}*/
} catch (InterruptedException | ExecutionException exception) {
Log.severe(exception);
} catch (TimeoutException exception) {
channel.write(ByteBuffer.wrap(Command.Bye.getValue().getBytes()));
Log.severe(exception);
}

System.out.println("End of conversation");
closeChannel(channel);
}

@Override
public void failed(Throwable exception, ServerSocketHandler handler) {
// Close this channel would cause AsynchronousCloseException
// directly return to avoid noise
if (exception instanceof AsynchronousCloseException) return;
Log.severe(exception);
}
});
}
}

3
package basic.util.socket;

import java.io.IOException;
import java.nio.channels.AsynchronousSocketChannel;

public class BaseClientSocket extends BaseSocket {
final private String host;

private AsynchronousSocketChannel channel;
public BaseClientSocket(String host, int port) {
super(port);
this.host = host;
}

protected String getHost() {
return host;
}

protected AsynchronousSocketChannel getChannel() {
return channel;
}
protected void openChannel() {
try {
channel = AsynchronousSocketChannel.open();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void closeChannel() {
closeChannel(getChannel());
}
}

4
package basic.util.socket;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;
import java.text.MessageFormat;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import basic.util.log.Log;

public class ClientSocket extends BaseClientSocket implements CompletionHandler<Void, ClientSocketHandler> {
private static final String RetrieveFromServer = "Button.RetrieveFromServer";
private Command command;
public ClientSocket(String serverHost, int port) {
super(serverHost, port);
}
public Command getCommand() {
return command;
}

public void run(ClientSocketHandler clientSocketHandler, Command command) {
this.command = command;
openChannel();
getChannel().connect(new InetSocketAddress(getHost(), getPort()), clientSocketHandler, this);
}

@Override
public void completed(Void result, ClientSocketHandler attachment) {
Log.info("Connected to: " + getHost() + "  " + getPort());
ByteBuffer byteBuffer = ByteBuffer.allocate(BufferSize);

try {
// Read the first line
int bytesRead = getChannel().read(byteBuffer).get(ReadTimeOut, TimeUnit.SECONDS);

String readyCommand = readBufferData(byteBuffer, bytesRead);
if (Command.ready.getValue().equals(readyCommand)) {
writeChannel(getChannel(), command.getValue());
Command.match(command.getValue()).ifPresent(command -> command.clientAction(getChannel(), byteBuffer, attachment));
/*if (Command.getServerData.getValue().equals(command.getValue())) {
readToFile(getChannel(), byteBuffer, attachment.getData());
} else if (Command.sendServerResult.getValue().equals(command.getValue())) {
writeChannel(getChannel(), attachment.getData());
writeChannel(getChannel(), Command.Bye.getValue());
}*/
} else {
    String msg = MessageFormat.format(ExceptionWrong, "Command", readyCommand);
attachment.retainThrowable(AccessChannelFailed, new Exception(msg), RetrieveFromServer, getHost(), Integer.toString(getPort()));
}
} catch (InterruptedException | ExecutionException exception) {
attachment.retainThrowable(AccessChannelFailed, exception, RetrieveFromServer, getHost(), Integer.toString(getPort()));
} catch (TimeoutException exception) {
getChannel().write( ByteBuffer.wrap(Command.Bye.getValue().getBytes() ) );
attachment.retainThrowable(AccessChannelFailed, exception, RetrieveFromServer, getHost(), Integer.toString(getPort()));
} /*catch (IOException exception) {
attachment.retainThrowable(BusinessException.Failed, BusinessException.ExceptionFailed, exception, "Write", "Data File", attachment.getData());
} */

attachment.setReady(true);
closeChannel();
}
@Override
public void failed(Throwable exception, ClientSocketHandler attachment) {
attachment.retainThrowable(AccessChannelFailed, exception, RetrieveFromServer, getHost(), Integer.toString(getPort()));
closeChannel();
attachment.setReady(true);
}
}