基本機能
simpl
simpl-file-format
simpl-web
その他
Getting Started
第01章 サービスロケータ機能
使用クラス |
---|
my.simpl.S |
my.simpl.SReleasable |
① 直接インスタンスをバインディングする。
S s = S.of();
s.bindInstance("start", new Date());
s.bindInstance(String.class, "bindInstance");
s.bindInstance(Integer.class, "all_data_count", 100);
s.bindInstance(Integer.class, "page_count", 20);
s.bindInstance(Double.class, "doller_mount", 20.12);
System.out.println(s.impl("start"));
System.out.println(s.impl(String.class));
System.out.println(s.impl(Integer.class, "all_data_count"));
System.out.println(s.impl(Integer.class, "page_count"));
System.out.println(s.impl(Double.class, "doller_mount"));
>実行結果:
>Wed Jul 10 11:22:23 JST 2024
>bindInstance
>100
>20
>20.12
② クラスを指定して、インスタンスをバインディングする。
S s = S.of();
s.bindType(String.class);
s.bindType(Template.class, Velocity.class);
s.bindType(Template.class, "Thymeleaf", Thymeleaf.class);
System.out.println(s.impl(String.class).equals(""));
System.out.println(s.impl(Template.class));
System.out.println(s.impl(Template.class, "Thymeleaf"));
>実行結果:
>true
>my.simpl.template.Thymeleaf@5cb0d902
>my.simpl.template.Velocity@5b37e0d2
③ ラムダ式をバインディングする。
S s = S.of();
ThrowsRunnable<Throwable> runnable = () -> {
System.out.println("Hello Lamda!");
};
s.bindLambda(ThrowsRunnable.class, runnable);
try {
s.impl(ThrowsRunnable.class).run();
} catch (Throwable e) {
}
ThrowsRunnable<Throwable> runnable2 = () -> {
System.out.println("Hello Lamda Car!");
};
s.bindLambda(ThrowsRunnable.class, "car", runnable2);
try {
s.impl(ThrowsRunnable.class, "car").run();
} catch (Throwable e) {
}
>実行結果:
>Hello Lamda!
>Hello Lamda Car!
④ サプライヤーを指定して、インスタンスをバインディングする。
※インスタンスはキャッシュされない(デフォルトの挙動)
S s = S.of();
ThrowsSupplier<Object, Throwable> supplier = () -> {
return new Object();
};
s.bindSupplier(Object.class, supplier);
System.out.println(s.impl(Object.class));
System.out.println(s.impl(Object.class));
s.bindSupplier(Object.class, "sup", supplier);
System.out.println(s.impl(Object.class, "sup"));
>実行結果:
>java.lang.Object@568db2f2
>java.lang.Object@378bf509
※キャッシュされないので、2回取得したインスタンスが異なる
>java.lang.Object@5fd0d5ae
⑤ インスタンスのキャッシュ、終了時の自動クローズを指定してサプライヤをバインディングする。
※インスタンスのキャッシュや自動クローズの指定ができる
SReleasable s = SReleasable.of();
ThrowsSupplier<Instance<Object>, Throwable> supplier = () -> {
Object obj = new Object();
// 第2引数はキャッシュするかを指定する(true :キャッシュする、false : キャッシュしない」
// 第3引数はsのclose時にインスタンスのcloseが必要かどうかを指定する。(true : クローズする false:クローズしない)
Instance<Object> ins = Instance.of(obj, true, false);
return ins;
};
s.bindWetSupplier(Object.class, supplier);
System.out.println(s.impl(Object.class));
System.out.println(s.impl(Object.class));
>実行結果:
>java.lang.Object@378bf509
>java.lang.Object@378bf509
※キャッシュ指定をしたため、2回取得した結果のインスタンスは、同じものが返却されている
SReleasable s = SReleasable.of();
BufferedReader sr = new BufferedReader(StringReader("ワイシャツ"));
s.bindInstance("GoodsName", sr, true);
try {
System.out.println(s.impl("GoodsName").readLine());
// バインディングしたインスタンスをクローズします
s.close();
} catch (Exception e) {
e.printStackTrace();
}
>実行結果:
>ワイシャツ
⑥ バインディングしたインスタンスを削除する
S s = S.of();
s.bindInstance("GoodsName", "ワイシャツ");
System.out.println(s.impl("GoodsName"));
// nullをバインディングすると、インスタンスが削除される
s.bindInstance("GoodsName", null);
System.out.println(s.impl("GoodsName"));
s.bindInstance(String.class, "Car", "Honda");
System.out.println(s.impl(String.class, "Car"));
// nullをバインディングすると、インスタンスが削除される
s.bindInstance(String.class, "Car", null);
System.out.println(s.impl(String.class, "Car"));
>実行結果:
>ワイシャツ
>null
>Honda
>null
⑦ Utilityを利用する
※各メソッドの詳細は第12章を参照
S s = S.of();
//evl
System.out.println(s.util().evl("", "default"));
>実行結果:
>default
第02章 ログ出力機能
使用クラス |
---|
my.simpl.S |
① デフォルト(System.outとSystem.err)機能でログを出力する。
S s = S.of();
// ログ出力を一括オンに設定する
s.enableLogAll();
s.debug("debug");
s.info("info");
s.warn("warn");
s.error("error");
s.fatal("fatal");
>実行結果:
>debug
>info
>warn
>error
>fatal
②ログ出力を個別にバインドする
S s = S.of();
// ログ出力を個別にオンに設定する
s.enableLogDebug(System.out);
s.enableLogInfo(System.out);
s.enableLogWarn(System.out);
s.enableLogError(System.err);
s.enableLogFatal(System.err);
s.debug("debug");
s.info("info");
s.warn("warn");
s.error("error");
s.fatal("fatal");
>実行結果:
>debug
>info
>warn
>error
>fatal
③ SLF4Jを使用してログを出力する。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SimplTest implements Utility {
public static void main(String[] args) {
SimplTest st = new SimplTest();
st.testLog();
}
public void testLog() {
S s = S.of();
Logger logger = LoggerFactory.getLogger(SimplTest.class);
s.bindLogStream(
logger.isErrorEnabled() ? printStream(message -> logger.error(message)) : null,
logger.isErrorEnabled() ? printStream(message -> logger.error(message)) : null,
logger.isWarnEnabled() ? printStream(message -> logger.warn(message)) : null,
logger.isInfoEnabled() ? printStream(message -> logger.info(message)) : null,
logger.isDebugEnabled() ? printStream(message -> logger.debug(message)) : null);
s.debug("debug");
s.info("info");
s.warn("warn");
s.error("error");
s.fatal("fatal");
}
}
>実行結果:
>14:46:13.980 [main] DEBUG my.simpl.SimplTest - debug
>14:46:13.997 [main] INFO my.simpl.SimplTest - info
>14:46:13.998 [main] WARN my.simpl.SimplTest - warn
>14:46:13.999 [main] ERROR my.simpl.SimplTest - error
>14:46:13.999 [main] ERROR my.simpl.SimplTest - fatal
第03章 JSON、CSV関連機能
使用クラス |
---|
my.simpl.Data |
① JSON文字列を作成する。
Data data = Data.of();
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("id1", "value1");
map.put("id2", "value2");
//MapをJSON文字列へ変換
String json = data.toJsonString(map);
System.out.println(json);
Map<String, String> map2 = new LinkedHashMap<String, String>();
map2.put("id10", "value10");
Map<String, String> map3 = new LinkedHashMap<String, String>();
map3.put("id11", "value11");
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
list.add(map2);
list.add(map3);
//ListをJSON文字列へ変換
String json2 = data.toJsonString(list);
System.out.println(json2);
>実行結果:
>{"id1":"value1","id2":"value2"}
>[{"id10":"value10"},{"id11":"value11"}]
② JSON文字列を解析する
Data data = Data.of();
InputStream inputStream = new ByteArrayInputStream("{\"id1\":\"value1\",\"id2\":\"value2\"}".getBytes());
//Mapとして読み込み
Map<String, Object> map = data.parseJsonAsMap(inputStream);
System.out.println(map.get("id1"));
System.out.println(map.get("id2"));
InputStream inputStream2 = new ByteArrayInputStream("[{\"id10\":\"value10\"},{\"id11\":\"value11\"}]".getBytes());
//Listとして読み込み
List<Object> list = data.parseJsonAsList(inputStream2);
System.out.println(list.get(0));
System.out.println(list.get(1));
>実行結果:
>value1
>value2
>{id10=value10}
>{id11=value11}
③ CSV文字列を作成する。
ヘッダーありのCSV文字列を作成
//CSV出力データの準備
List<Map<String, String>> csvMap = new ArrayList<Map<String, String>>();
Map<String, String> csvMap1 = new LinkedHashMap<>();
csvMap1.put("FirstName", "Tom");
csvMap1.put("LastName", "Cruise");
csvMap1.put("Age", "18");
Map<String, String> csvMap2 = new LinkedHashMap<>();
csvMap2.put("FirstName", "Taylor");
csvMap2.put("LastName", "Swift");
csvMap2.put("Age", "19");
csvMap.add(csvMap1);
csvMap.add(csvMap2);
//CSVデータの出力
Data data = Data.of();
OutputStream outputStream = new ByteArrayOutputStream();
data.writeCsvWithHeader(outputStream, csvMap);
System.out.print(outputStream);
>実行結果:
>FirstName,LastName,Age
>Tom,Cruise,18
>Taylor,Swift,19
ヘッダーなしのCSV文字列を作成
//CSV出力データの準備
List<Map<String, String>> csvMap = new ArrayList<Map<String, String>>();
Map<String, String> csvMap1 = new LinkedHashMap<>();
csvMap1.put("FirstName", "Tom");
csvMap1.put("LastName", "Cruise");
csvMap1.put("Age", "18");
Map<String, String> csvMap2 = new LinkedHashMap<>();
csvMap2.put("FirstName", "Taylor");
csvMap2.put("LastName", "Swift");
csvMap2.put("Age", "19");
csvMap.add(csvMap1);
csvMap.add(csvMap2);
//CSVデータの出力
Data data = Data.of();
OutputStream outputStream = new ByteArrayOutputStream();
data.writeCsvWithoutHeader(outputStream, csvMap);
System.out.print(outputStream);
>実行結果:
>Tom,Cruise,18
>Taylor,Swift,19
④ CSV文字列を解析する
キー(カラム名)、値(カラム値)のMap形式で読み込む
//CSVデータのInputStreamを準備
String csvString = "FirstName,LastName,Age\r\nTom,Cruise,18\r\nTaylor,Swift,19";
InputStream inputStream = new ByteArrayInputStream(csvString.getBytes());
Data data = Data.of();
//CSVデータの読み込み
data.readCsvWithHeader(inputStream, (csvData) -> {
System.out.println(csvData);
System.out.println(csvData.get("FirstName"));
return true;
});
try {
inputStream.close();
} catch (IOException e) {
}
>実行結果:
>{FirstName=Tom, LastName=Cruise, Age=18}
>Tom
>{FirstName=Taylor, LastName=Swift, Age=19}
>Taylor
値(カラム値)を文字列配列で読み込む
//CSVデータのInputStreamの準備
String csvString = "Tom,Cruise,18\r\nTaylor,Swift,19";
InputStream inputStream = new ByteArrayInputStream(csvString.getBytes());
//CSVデータの読み込み
Data data = Data.of();
data.readCsvWithoutHeader(inputStream, (csvData) -> {
System.out.println(csvData[0] + "," + csvData[1] + "," + csvData[2]);
return true;
});
>実行結果:
>Tom,Cruise,18
>Taylor,Swift,19
第04章 テンプレート機能
使用クラス |
---|
my.simpl.template.Thymeleaf |
my.simpl.template.Velocity |
① Thymeleafテンプレートを使用する。
Thymeleaf tl = new Thymeleaf();
Map<String, Object> contextMap = new HashMap<String, Object>();
contextMap.put("message", "new message");
String template = "<h3 th:text='${message}'>hello!!</h3>";
String result = tl.eval(template, tl.context(contextMap));
System.out.println(result);
>実行結果:
><h3>new message</h3>
② Velocityテンプレートを使用する。
Velocity tl = new Velocity();
Map<String, Object> contextMap = new HashMap<String, Object>();
contextMap.put("goodsNames", "ワイシャツ");
String template = "商品名:$goodsNames";
String result = tl.eval(template, tl.context(contextMap));
System.out.println(result);
>実行結果:
>商品名:ワイシャツ
第05章 データベースアクセス機能
使用クラス |
---|
my.simpl.jdbc.jdbc |
① Insert/Update/Delete文を実行する。
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Oracle用
// Jdbc jdbc = new Jdbc.Oracle();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
Connection conn = jdbc.conn("localhost",3306,"simpldb","simpl","simpl123");
Statement statement = conn.createStatement();
statement.executeUpdate("CREATE TABLE test1 (" +
" col1 VARCHAR(45) NOT NULL," +
" col2 VARCHAR(45) DEFAULT NULL," +
" PRIMARY KEY (col1)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8");
//Insert文を実行する。
System.out.println(jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val1\",\"val2\");",(stmt) -> {}));
//Update文を実行する。
System.out.println(jdbc.execute(conn,"UPDATE test1 SET col1='col5' WHERE col1='val1'",(stmt) -> {}));
//Delete文を実行する。
System.out.println(jdbc.execute(conn,"DELETE FROM simpldb.test1;",(stmt) -> {}));
statement.executeUpdate("DROP TABLE simpldb.test1;");
statement.close();
>実行結果
>1
>1
>1
② Select文を実行する。
・1レコード(Map<String, Object>)を返す。
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Oracle用
// Jdbc jdbc = new Jdbc.Oracle();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
Connection conn = jdbc.conn("localhost",32786,"simpldb","simpl","simpl123");
Statement statement = conn.createStatement();
statement.executeUpdate("CREATE TABLE test1 (" +
" col1 VARCHAR(45) NOT NULL," +
" col2 VARCHAR(45) DEFAULT NULL," +
" PRIMARY KEY (col1)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8");
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val1\",\"val2\");",(stmt) -> {});
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val3\",\"val4\");",(stmt) -> {});
Map<String, Object> result = new LinkedHashMap<String, Object>();
//Select文を実行する。
result = jdbc.readRecord(conn, "SELECT * FROM test1 WHERE col1='val3'");
System.out.println(result.get("col1"));
System.out.println(result.get("col2"));
jdbc.execute(conn,"DELETE FROM simpldb.test1;",(stmt) -> {});
>実行結果
>val3
>val4
・レコードリスト(List<Map<String, Object>>)を返す。
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Oracle用
// Jdbc jdbc = new Jdbc.Oracle();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
Connection conn = jdbc.conn("localhost",32786,"simpldb","simpl","simpl123");
Statement statement = conn.createStatement();
statement.executeUpdate("CREATE TABLE test1 (" +
" col1 VARCHAR(45) NOT NULL," +
" col2 VARCHAR(45) DEFAULT NULL," +
" PRIMARY KEY (col1)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8");
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val1\",\"val2\");",(stmt) -> {});
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val3\",\"val4\");",(stmt) -> {});
List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
//Select文を実行する。
results = jdbc.readList(conn, "SELECT * FROM test1");
System.out.println(results.get(0));
System.out.println(results.get(1));
jdbc.execute(conn,"DELETE FROM simpldb.test1;",(stmt) -> {});
>実行結果
>{col1=val1, col2=val2}
>{col1=val3, col2=val4}
・単一の値を返す。
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Oracle用
// Jdbc jdbc = new Jdbc.Oracle();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
Connection conn = jdbc.conn("localhost",32786,"simpldb","simpl","simpl123");
Statement statement = conn.createStatement();
statement.executeUpdate("CREATE TABLE test1 (" +
" col1 VARCHAR(45) NOT NULL," +
" col2 VARCHAR(45) DEFAULT NULL," +
" PRIMARY KEY (col1)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8");
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val1\",\"val2\");",(stmt) -> {});
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val3\",\"val4\");",(stmt) -> {});
Object result = new Object();
//Select文を実行する。
result = jdbc.readScalar(conn, "SELECT * FROM test1");
System.out.println(result);
jdbc.execute(conn,"DELETE FROM simpldb.test1;",(stmt) -> {});
>実行結果
>val1
・単一の値リストを返す。
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Oracle用
// Jdbc jdbc = new Jdbc.Oracle();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
Connection conn = jdbc.conn("localhost",32786,"simpldb","simpl","simpl123");
Statement statement = conn.createStatement();
statement.executeUpdate("CREATE TABLE test1 (" +
" col1 VARCHAR(45) NOT NULL," +
" col2 VARCHAR(45) DEFAULT NULL," +
" PRIMARY KEY (col1)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8");
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val1\",\"val2\");",(stmt) -> {});
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val3\",\"val4\");",(stmt) -> {});
List<Object> results = new ArrayList<Object>();
//Select文を実行する。
results = jdbc.readScalarList(conn, "SELECT * FROM test1");
System.out.println(results.get(0));
System.out.println(results.get(1));
jdbc.execute(conn,"DELETE FROM simpldb.test1;",(stmt) -> {});
>実行結果
>val1
>val3
・レコードを1件ずつ読み込む
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Oracle用
// Jdbc jdbc = new Jdbc.Oracle();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
Connection conn = jdbc.conn("localhost",32786,"simpldb","simpl","simpl123");
Statement statement = conn.createStatement();
statement.executeUpdate("CREATE TABLE test1 (" +
" col1 VARCHAR(45) NOT NULL," +
" col2 VARCHAR(45) DEFAULT NULL," +
" PRIMARY KEY (col1)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8");
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val1\",\"val2\");",(stmt) -> {});
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val3\",\"val4\");",(stmt) -> {});
jdbc.handleCursor(conn, "SELECT * FROM test1",(result) ->{
System.out.println("col1:"+result.get("col1")+";"+"col2:"+result.get("col2"));
});
jdbc.execute(conn,"DELETE FROM simpldb.test1;",(stmt) -> {});
>実行結果
>col1:val1;col2:val2
>col1:val3;col2:val4
・単一の値を1件ずつ読み込む。
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Oracle用
// Jdbc jdbc = new Jdbc.Oracle();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
Connection conn = jdbc.conn("localhost",32786,"simpldb","simpl","simpl123");
Statement statement = conn.createStatement();
statement.executeUpdate("CREATE TABLE test1 (" +
" col1 VARCHAR(45) NOT NULL," +
" col2 VARCHAR(45) DEFAULT NULL," +
" PRIMARY KEY (col1)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8");
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val1\",\"val2\");",(stmt) -> {});
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"val3\",\"val4\");",(stmt) -> {});
jdbc.handleScalarCursor(conn, "SELECT * FROM test1",(result) ->{
System.out.println("col1:"+result);
});
jdbc.execute(conn,"DELETE FROM simpldb.test1;",(stmt) -> {});
>実行結果
>col1:val1
>col1:val3
第06章 SQL文字列組立機能
使用クラス |
---|
my.simpl.jdbc.Sql |
① SELECT文の組立
//以下、DBに合わせてコメントを切り替えてください。
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Oracle用
// Jdbc jdbc = new Jdbc.Oracle();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
Sql sql = jdbc.query();
・別名指定(エイリアス)
Expr ex = sql.selectDistinct("col3").from("table2").where(sql.isNull("col4"));
System.out.println(sql
.select(sql.as(ex,"alias_col1"),sql.as("col2","alias_col2"))
.from(sql.as("table1","t1"))
.where(sql.eq("col1","val1")).expr());
>実行結果:
>select ( select distinct col3 from table2 where a is null ) as alias_col1, col2 as alias_col2 from table1 as t1 where col1 = ?
・外部結合
strSql = sql.select("col1","col2")
.from("test1")
.leftJoin("test2", Expr.of("test1.col1 = test2.col1")).expr();
System.out.println(strSql);
>実行結果:
>select col1, col2 from test1 left join test2 on test1.col1 = test2.col1
・内部結合
strSql = sql.select("col1","col2")
.from("test1")
.innerJoin("test2", Expr.of("test1.col1 = test2.col1")).expr();
System.out.println(strSql);
>実行結果:
>select col1, col2 from test1 inner join test2 on test1.col1 = test2.col1
・グループ化
String strSql = sql.select("col1","col2")
.from("test1")
.where(sql.eq("col1","val1"),sql.eq("col3","val3"))
.groupBy("col1").expr());
System.out.println(strSql);
>実行結果:
>select col1, col2 from test1 where col1 = ? and col3 = ? group by col1
HAVING句を利用した場合
String strSql = sql.select("col1","col2")
.from("test1")
.where(sql.eq("col1","val1"),sql.eq("col3","val3"))
.groupBy("col1").having(sql.gt("col1",100)).expr());
System.out.println(strSql);
>実行結果:
>select col1, col2 from test1 where col1 = ? and col3 = ? group by col1 having col1 > ?
・DISTINCT
System.out.println(sql.selectDistinct("col3").from("table1").where(sql.eq("col1","val1")).expr());
>実行結果:
select distinct col3 from table1 where col1 = ?
・取得件数制限
MySQLの場合
strSql = sql.select("col1","col2")
.from("test1")
.where(sql.eq("col1","val1"),sql.eq("col3","val3"))
.limit(10,0).expr();
System.out.println(strSql);
>実行結果:
>select col1, col2 from test1 where col1 = ? and col3 = ? limit 0, 10
Postgresの場合
strSql = sql.select("col1","col2")
.from("test1")
.where(sql.eq("col1","val1"),sql.eq("col3","val3"))
.limit(10,0).expr();
System.out.println(strSql);
>実行結果:
>select col1, col2 from test1 where col1 = ? and col3 = ? limit 10 offset 0
Oracleの場合
strSql = sql.select("col1","col2","rownum")
.from("test1")
.where(sql.eq("col1","val1"),sql.eq("col3","val3"))
.limit(10,0).expr();
System.out.println(strSql);
>実行結果:
>select * from (select col1, col2, rownum from test1 where col1 = ? and col3 = ?) where rownum > 0 and rownum <= 10
SQLServerの場合
strSql = sql.select("col1","col2")
.from("test1")
.where(sql.eq("col1","val1"),sql.eq("col3","val3"))
.limit(10,0).expr();
System.out.println(strSql);
>実行結果:
>select col1, col2 from test1 where col1 = ? and col3 = ? offset 0 rows fetch next 10 rows only
・ソート
ソートオプション未指定
strSql = sql.select("col1","col2")
.from("test1")
.where("col1='col1'")
.orderBy("col1").expr();
System.out.println(strSql);
>実行結果:
>select col1, col2 from test1 where col1='col1' order by col1
昇順オプション
strSqlAsc = sql.select("col1","col2")
.from("test1")
.where("col1='col1'")
.orderBy(sql.asc("col1")).expr();
System.out.println(strSqlAsc);
>実行結果:
>select col1, col2 from test1 where col1='col1' order by col1 asc
降順オプション
strSqlDesc = sql.select("col1","col2")
.from("test1")
.where("col1='col1'")
.orderBy(sql.desc("col1")).expr();
System.out.println(strSqlDesc);
>実行結果:
>select col1, col2 from test1 where col1='col1' order by col1 desc
・集計関数
カウント
System.out.println(sql.select(sql.count("*")).from("table").expr());
>実行結果:
>select count ( * ) from table
最大値
System.out.println(sql.select(sql.max("col1")).from("table").expr());
>実行結果:
>select max ( col1 ) from table
最小値
System.out.println(sql.select(sql.min("col1")).from("table").expr());
>実行結果:
>select min ( col1 ) from table
平均値
System.out.println(sql.select(sql.avg("col1")).from("table").expr());
>実行結果:
>select avg ( col1 ) from table
・EXISTS述語
String strSql = sql.select("col1").from("table")
.where(sql.exists(
sql.select("col1")
.from("table2")
.where("table2.col1 = table.col1")
)
).expr();
System.out.println(strSql);
>実行結果:
>select col1 from table where exists ( select col1 from table2 where table2.col1 = table.col1 )
・NOT EXISTS述語
strSql = sql.select("col1").from("table")
.where(sql.notExists(
sql.select("col1")
.from("table2")
.where("table2.col1 = table.col1")
)
).expr();
System.out.println(strSql);
>実行結果:
>select col1 from table where not exists ( select col1 from table2 where table2.col1 = table.col1 )
・IN述語
List<String> args = new ArrayList<String>();
args.addAll(Arrays.asList("東京","大阪"));
Expr ex = sql.in("prefectures",args);
System.out.println(sql.select("prefectures","city").from("m_address").where(ex).expr());
>実行結果:
>select prefectures, city from m_address where prefectures in ( ?, ? )
>宿%
・NOT IN述語
List<String> args = new ArrayList<String>();
args.addAll(Arrays.asList("東京","大阪"));
Expr ex = sql.notIn("prefectures",args);
System.out.println(sql.select("prefectures","city").from("m_address").where(ex).expr());
>実行結果:
>select prefectures, city from m_address where prefectures not in ( ?, ? )
・LIKE述語
前方一致
ex = sql.likePrefix("city","宿");
System.out.println(sql.select("prefectures","city").from("m_address").where(ex).expr());
System.out.println(ex.args().iterator().next().toString());
>実行結果:
>select prefectures, city from m_address where city like ?
>宿%
部分一致
ex = sql.likeContain("city","宿");
System.out.println(sql.select("prefectures","city").from("m_address").where(ex).expr());
System.out.println(ex.args().iterator().next().toString());
>実行結果:
>select prefectures, city from m_address where city like ?
>%宿%
後方一致
ex = sql.likeSuffix("city","宿");
System.out.println(sql.select("prefectures","city").from("m_address").where(ex).expr());
System.out.println(ex.args().iterator().next().toString());
>実行結果:
>select prefectures, city from m_address where city like ?
>%宿
ワイルドカードを任意で設定する
ex = sql.like("city","_宿");
System.out.println(sql.select("prefectures","city").from("m_address").where(ex).expr());
System.out.println(ex.args().iterator().next().toString());
>実行結果:
>select prefectures, city from m_address where city like ?
>_宿
・NOT LIKE述語
前方一致
ex = sql.notLikePrefix("prefectures","島");
System.out.println(sql.select("prefectures","city").from("m_address").where(ex).expr());
System.out.println(ex.args().iterator().next().toString());
>実行結果:
>select prefectures, city from m_address where prefectures not like ?
>島%
部分一致
ex = sql.notLikeContain("prefectures","島");
System.out.println(sql.select("prefectures","city").from("m_address").where(ex).expr());
System.out.println(ex.args().iterator().next().toString());
>実行結果:
>select prefectures, city from m_address where prefectures not like ?
>%島%
後方一致
ex = sql.notLikeSuffix("prefectures","島");
System.out.println(sql.select("prefectures","city").from("m_address").where(ex).expr());
System.out.println(ex.args().iterator().next().toString());
>実行結果:
>select prefectures, city from m_address where prefectures not like ?
>%島
ワイルドカードを任意で設定する
ex = sql.notLike("prefectures","島_");
System.out.println(sql.select("prefectures","city").from("m_address").where(ex).expr());
System.out.println(ex.args().iterator().next().toString());
>実行結果:
>select prefectures, city from m_address where prefectures not like ?
>島_
・比較述語
等号
System.out.println(sql.select("col1").from("table").where(sql.eq("col1","val1")).expr());
>実行結果:
>select col1 from table where col1 = ?
不等号
System.out.println(sql.select("col1").from("table").where(sql.notEq("col1","val1")).expr());
>実行結果:
>select col1 from table where col1 <> ?
大なり
System.out.println(sql.select("col1").from("table").where(sql.gt("col1","val1")).expr());
>実行結果:
>select col1 from table where col1 > ?
小なり
System.out.println(sql.select("col1").from("table").where(sql.lt("col1","val1")).expr());
>実行結果:
>select col1 from table where col1 < ?
以上
System.out.println(sql.select("col1").from("table").where(sql.ge("col1","val1")).expr());
>実行結果:
>select col1 from table where col1 >= ?
以下
System.out.println(sql.select("col1").from("table").where(sql.le("col1","val1")).expr());
>実行結果:
>select col1 from table where col1 <= ?
・IS NULL演算子
System.out.println(sql.select("col2","col3").from("table1").where(sql.isNull("col1")).expr());
>実行結果:
select col2, col3 from table1 where col1 is null
・IS NOT NULL演算子
System.out.println(sql.select("col2","col3").from("table1").where(sql.isNotNull("col1")).expr());
>実行結果:
select col2, col3 from table1 where col1 is not null
② INSERT文の組立
・単一行のINSERT
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Oracle用
// Jdbc jdbc = new Jdbc.Oracle();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
Sql sql = jdbc.query();
String strSql = sql.insertInto("table")
.columns("col1", "col2")
.values("col1value", "col2value").expr();
System.out.println(strSql);
>実行結果:
>insert into table( col1, col2 ) values ( ?, ? )
・BULK INSERT
MySQL、Postgres、SQLServerの場合
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
String[] colmuns = new String[] {"col1","col2","col3","col4"};
List<Object[]> valus = new ArrayList<>();
valus.add(new Object[]{"val1","val2","val3","val4"});
valus.add(new Object[]{"val11","val12","val13","val14"});
Sql sql = jdbc.query();
String strSql2 = sql.insertInto("table1")
.columns(colmuns)
.values(valus)
.expr();
System.out.println(strSql2);
>実行結果:
>insert into table1( col1, col2, col3, col4 ) values ( ?, ?, ?, ? ), ( ?, ?, ?, ? )
Oracleの場合
// Oracle用
Jdbc jdbc = new Jdbc.Oracle();
String[] colmuns = new String[] {"col1","col2","col3","col4"};
List<Object[]> valus = new ArrayList<>();
valus.add(new Object[]{"val1","val2","val3","val4"});
valus.add(new Object[]{"val11","val12","val13","val14"});
Sql sql = jdbc.query();
String strSql2 = sql.insertInto("table1")
.columns(colmuns)
.values(valus)
.expr();
System.out.println(strSql2);
>実行結果:
>insert all into table1( col1, col2, col3, col4 ) values ( ?, ?, ?, ? ) into table1( col1, col2, col3, col4 ) values ( ?, ?, ?, ? ) select * from dual
③ UPDATE文の組立
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Oracle用
// Jdbc jdbc = new Jdbc.Oracle();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
ThrowsSupplier<Map<Column<?>, Object>, Throwable> valueSupplier=new ThrowsSupplier<Map<Column<?>,Object>, Throwable>() {
@Override
public Map<Column<?>, Object> get() throws Throwable {
Column<String> col = new Column.Default<>("col2", String.class, null);
Map<Column<?>, Object> mapUpd = new LinkedHashMap<>();
mapUpd.put(col, "val2");
return mapUpd;
}
};
String strSql = jdbc.query().update("table")
.set(valueSupplier)
.where("col1 = 'val1'").expr();
System.out.println(strSql);
>実行結果:
>update table set col2 = ? where col1 = 'col1'
④ UPSERT文の組立
・MySQLの場合(onDuplicateで生成)
// MySQLの場合
Jdbc jdbc = new Jdbc.MySQL();
String user = "user@simpl.my";
Connection conn = jdbc.conn("localhost",3306,"simpldb",user,"simpl123");
LocalDateTime now = LocalDateTime.now();
// カラム名
String[] insertColumns = new String[] {
"product_cd", "brand_cd", "product_name", "delete_flg",
"created_by", "created_at", "updated_by", "updated_at", "update_count"
};
// インサートデータ
List<Object[]> records = new ArrayList<>();
records.add(new Object[] {
"A-001", "SMP", "商品名", "0",
user, now, user, now, 0
});
// アップデート時の更新データ
// ※EXCLUDED表を使わない列を含む場合はMapで定義する
Map<String, Object> updateColumns =
map(
"product_name", Expr.of("product_name"),
"delete_flg", Expr.of("delete_flg"),
"updated_by", Expr.of("updated_by"),
"updated_at", Expr.of("updated_at"),
"update_count", Expr.of("tableName" + ".update_count + 1")
);
// ユニークカラム
String[] uniqueColumns = new String[] { "product_cd", "brand_cd" };
// クエリ実行
jdbc.execute(conn,
q -> q.insertInto("m_product")
.columns(insertColumns)
.values(records)
.adjust(q.onDuplicate(updateColumns, uniqueColumns)));
// クエリ出力
System.out.println(jdbc.queryMySQL().insertInto("m_product")
.columns(insertColumns)
.values(records)
.adjust(jdbc.queryMySQL().onDuplicate(updateColumns, uniqueColumns)));
>実行結果:
>insert into m_product( product_cd, brand_cd, product_name, delete_flg, created_by, created_at, updated_by, updated_at, update_count ) values ( ?, ?, ?, ?, ?, ?, ?, ?, ? ) on duplicate key update product_name = product_name, delete_flg = delete_flg, updated_by = updated_by, updated_at = updated_at, update_count = tableName.update_count + 1
・Postgresの場合(onDuplicateで生成)
// Postgresの場合
Jdbc jdbc = new Jdbc.Postgres();
String user = "user@simpl.my";
Connection conn = jdbc.conn("localhost",3306,"simpldb",user,"simpl123");
LocalDateTime now = LocalDateTime.now();
// カラム名
String[] insertColumns = new String[] {
"product_cd", "brand_cd", "product_name", "delete_flg",
"created_by", "created_at", "updated_by", "updated_at", "update_count"
};
// インサートデータ
List<Object[]> records = new ArrayList<>();
records.add(new Object[] {
"A-001", "SMP", "商品名", "0",
user, now, user, now, 0
});
// アップデート時の更新データ
// ※EXCLUDED表を使わない列を含む場合はMapで定義する
Map<String, Object> updateColumns =
map(
"product_name", Expr.of("EXCLUDED.product_name"),
"delete_flg", Expr.of("EXCLUDED.delete_flg"),
"updated_by", Expr.of("EXCLUDED.updated_by"),
"updated_at", Expr.of("EXCLUDED.updated_at"),
"update_count", Expr.of("tableName" + ".update_count + 1")
);
// ユニークカラム
String[] uniqueColumns = new String[] { "product_cd", "brand_cd" };
// クエリ実行
jdbc.execute(conn,
q -> q.insertInto("m_product")
.columns(insertColumns)
.values(records)
.adjust(q.onDuplicate(updateColumns, uniqueColumns)));
// クエリ出力
System.out.println(jdbc.queryPostgres().insertInto("m_product")
.columns(insertColumns)
.values(records)
.adjust(jdbc.queryPostgres().onDuplicate(updateColumns, uniqueColumns)));
>実行結果:
>insert into table( product_cd, brand_cd, product_name, delete_flg, created_by, created_at, updated_by, updated_at, update_count ) values ( ?, ?, ?, ?, ?, ?, ?, ?, ? ) on conflict (product_cd, brand_cd) do update set product_name = EXCLUDED.product_name, delete_flg = EXCLUDED.delete_flg, updated_by = EXCLUDED.updated_by, updated_at = EXCLUDED.updated_at, update_count = tableName.update_count + 1
・Oracleの場合(merge intoで生成)
// Oracleの場合
Jdbc jdbc = new Jdbc.Oracle();
String user = "user@simpl.my";
Connection conn = jdbc.conn("localhost",3306,"simpldb",user,"simpl123");
LocalDateTime now = LocalDateTime.now();
// カラム名
String[] insertColumns = new String[] {
"product_cd", "brand_cd", "product_name", "delete_flg",
"created_by", "created_at", "updated_by", "updated_at", "update_count"
};
// インサートデータ
List<Object[]> records = new ArrayList<>();
records.add(new Object[] {
"A-001", "SMP", "商品名", "0",
user, now, user, now, 0
});
// アップデート時の更新データ
Map<String, Object> updateColumns =
map(
"product_name", Expr.of("product_name"),
"delete_flg", Expr.of("delete_flg"),
"updated_by", Expr.of("updated_by"),
"updated_at", Expr.of("updated_at"),
"update_count", Expr.of("tableName" + ".update_count + 1")
);
// ユニークカラム
String[] uniqueColumns = new String[] { "product_cd", "brand_cd" };
// クエリ実行
jdbc.execute(conn,
q -> q.insertInto("m_product")
.columns(insertColumns)
.values(records)
.adjust(q.onDuplicate(updateColumns, uniqueColumns)));
// クエリ出力
System.out.println(jdbc.queryOracle().insertInto("m_product")
.columns(insertColumns)
.values(records)
.adjust(jdbc.queryOracle().onDuplicate(updateColumns, uniqueColumns)));
>実行結果:
>merge into m_product source using ( select ? product_cd, ? brand_cd, ? product_name, ? delete_flg, ? created_by, ? created_at, ? updated_by, ? updated_at, ? update_count from dual ) dest on (source.product_cd = dest.product_cd and source.brand_cd = dest.brand_cd) when matched then update set product_name = product_name, delete_flg = delete_flg, updated_by = updated_by, updated_at = updated_at, update_count = tableName.update_count + 1 when not matched then insert (product_cd, brand_cd, product_name, delete_flg, created_by, created_at, updated_by, updated_at, update_count) values (dest.product_cd, dest.brand_cd, dest.product_name, dest.delete_flg, dest.created_by, dest.created_at, dest.updated_by, dest.updated_at, dest.update_count)
・SQLServerの場合(merge intoで生成)
// SQLServerの場合
Jdbc jdbc = new Jdbc.SQLServer();
String user = "user@simpl.my";
Connection conn = jdbc.conn("localhost",3306,"simpldb",user,"simpl123");
LocalDateTime now = LocalDateTime.now();
// カラム名
String[] insertColumns = new String[] {
"product_cd", "brand_cd", "product_name", "delete_flg",
"created_by", "created_at", "updated_by", "updated_at", "update_count"
};
// インサートデータ
List<Object[]> records = new ArrayList<>();
records.add(new Object[] {
"A-001", "SMP", "商品名", "0",
user, now, user, now, 0
});
// アップデート時の更新データ
Map<String, Object> updateColumns =
map(
"product_name", Expr.of("product_name"),
"delete_flg", Expr.of("delete_flg"),
"updated_by", Expr.of("updated_by"),
"updated_at", Expr.of("updated_at"),
"update_count", Expr.of("tableName" + ".update_count + 1")
);
// ユニークカラム
String[] uniqueColumns = new String[] { "product_cd", "brand_cd" };
// クエリ実行
jdbc.execute(conn,
q -> q.insertInto("m_product")
.columns(insertColumns)
.values(records)
.adjust(q.onDuplicate(updateColumns, uniqueColumns)));
// クエリ出力
System.out.println(jdbc.querySQLServer().insertInto("m_product")
.columns(insertColumns)
.values(records)
.adjust(jdbc.querySQLServer().onDuplicate(updateColumns, uniqueColumns)));
>実行結果:
>merge into m_product source using ( select ? product_cd, ? brand_cd, ? product_name, ? delete_flg, ? created_by, ? created_at, ? updated_by, ? updated_at, ? update_count) dest on (source.product_cd = dest.product_cd and source.brand_cd = dest.brand_cd) when matched then update set product_name = product_name, delete_flg = delete_flg, updated_by = updated_by, updated_at = updated_at, update_count = tableName.update_count + 1 when not matched then insert (product_cd, brand_cd, product_name, delete_flg, created_by, created_at, updated_by, updated_at, update_count) values (dest.product_cd, dest.brand_cd, dest.product_name, dest.delete_flg, dest.created_by, dest.created_at, dest.updated_by, dest.updated_at, dest.update_count);
⑤ DELETE文の組立
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Oracle用
// Jdbc jdbc = new Jdbc.Oracle();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
String strSql = jdbc.query()
.deleteFrom("test1")
.where("col1='col1'").expr();
System.out.println(strSql);
>実行結果:
>delete from test1 where col1='col1'
⑥データベースアクセス機能との組み合わせ
// MySQL用
Jdbc jdbc = new Jdbc.MySQL();
// Oracle用
// Jdbc jdbc = new Jdbc.Oracle();
// Postgres用
// Jdbc jdbc = new Jdbc.Postgres();
// SQLServer用
// Jdbc jdbc = new Jdbc.SQLServer();
Connection conn = jdbc.conn("localhost",32786,"simpldb","simpl","simpl123");
jdbc.execute(conn,"DELETE FROM simpldb.test1;",(stmt) -> {});
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"col1\",\"col2\");",(stmt) -> {});
jdbc.execute(conn,"INSERT INTO simpldb.test1(col1,col2)VALUES(\"col3\",\"col4\");",(stmt) -> {});
List<Map<String,Object>> results = jdbc.readList(conn,sql -> sql.select("*").from("test1"));
System.out.println(results.get(0));
System.out.println(results.get(1));
jdbc.execute(conn,"DELETE FROM simpldb.test1;",(stmt) -> {});
>実行結果:
>{col1=col1, col2=col2}
>{col1=col3, col2=col4}
第07章 Validator機能
使用クラス |
---|
my.simpl.Validator |
my.simpl.Rule |
① 必須チェック
Map<String, String> msgs = new HashMap<String, String>();
msgs.put("E0001", "{0} is null");
Validator validator = new Validator() {
};
Rule<String> stringRule = validator
.stringRule("val", S.of().bindInstance(Map.class, "messages", new LinkedHashMap<>()))
.withRequired(true)
.withMessageSupplier((messageMap) -> {
return format(msgs.get("E0001"), messageMap.get("label"));
});
Map<Object, Object> data = new LinkedHashMap<Object, Object>();
data.put("val", "");
Map<String, List<String>> errors = validator.validate(data, new Rule[] { stringRule });
System.out.println(errors.get("val").get(0));
>実行結果
>val is null
② 文字列の長さ(最大、最小、同じ長さ、違う長さ)チェック
Map<String, String> msgs = new HashMap<String, String>();
msgs.put("E0001", "{0} lenth is more than {1}");
msgs.put("E0002", "{0} lenth is less than {1}");
msgs.put("E0003", "{0} lenth is not {1}");
msgs.put("E0004", "{0} lenth is {1}");
Validator validator = new Validator() {};
Rule<String> stringMaxLengthRule = validator
.stringRule("val1", S.of().bindInstance(Map.class, "messages", new LinkedHashMap<>()))
.withMaxLength(10)
.withMessageSupplier((messageMap) -> {
return format(msgs.get("E0001"), messageMap.get("label"),messageMap.get("max"));
});
Rule<String> stringMinLengthRule = validator
.stringRule("val2", S.of().bindInstance(Map.class, "messages", new LinkedHashMap<>()))
.withMinLength(5)
.withMessageSupplier((messageMap) -> {
return format(msgs.get("E0002"), messageMap.get("label"),messageMap.get("min"));
});
Rule<String> stringSameLengthRule = validator
.stringRule("val3", S.of().bindInstance(Map.class, "messages", new LinkedHashMap<>()))
.withSameLength(6)
.withMessageSupplier((messageMap) -> {
return format(msgs.get("E0003"), messageMap.get("label"),messageMap.get("same"));
});
Rule<String> stringNotSameLengthRule = validator
.stringRule("val4", S.of().bindInstance(Map.class, "messages", new LinkedHashMap<>()))
.withNotSameLength(4)
.withMessageSupplier((messageMap) -> {
return format(msgs.get("E0004"), messageMap.get("label"),messageMap.get("notsame"));
});
Map<Object, Object> data = new LinkedHashMap<Object, Object>();
data.put("val1", "aaaaaaaaaaa");
data.put("val2", "aaa");
data.put("val3", "aaaaa");
data.put("val4", "aaaa");
Map<String, List<String>> errors = validator.validate(data, new Rule[] { stringMaxLengthRule, stringMinLengthRule,
stringSameLengthRule, stringNotSameLengthRule });
System.out.println(errors.get("val1").get(0));
System.out.println(errors.get("val2").get(0));
System.out.println(errors.get("val3").get(0));
System.out.println(errors.get("val4").get(0));
>実行結果
>val1 lenth is more than 10
>val2 lenth is less than 5
>val3 lenth is not 6
>val4 lenth is 4
③ 数値の範囲(最大、最小、同じ値、違う値)チェック
Map<String, String> msgs = new HashMap<String, String>();
msgs.put("E0001", "{0} value is more than {1}");
msgs.put("E0002", "{0} value is less than {1}");
msgs.put("E0003", "{0} value is not {1}");
msgs.put("E0004", "{0} value is {1}");
Validator validator = new Validator() {};
Rule<Integer> intMaxLengthRule = validator
.intRule("val1", S.of().bindInstance(Map.class, "messages", new LinkedHashMap<>()))
.withMaxValue(100)
.withMessageSupplier((messageMap) -> {
return format(msgs.get("E0001"), messageMap.get("label"),messageMap.get("max"));
});
Rule<Integer> intMinLengthRule = validator
.intRule("val2", S.of().bindInstance(Map.class, "messages", new LinkedHashMap<>()))
.withMinValue(5)
.withMessageSupplier((messageMap) -> {
return format(msgs.get("E0002"), messageMap.get("label"),messageMap.get("min"));
});
Rule<Integer> intSameLengthRule = validator
.intRule("val3", S.of().bindInstance(Map.class, "messages", new LinkedHashMap<>())).withSameValue(25)
.withMessageSupplier((messageMap) -> {
return format(msgs.get("E0003"), messageMap.get("label"),messageMap.get("same"));
});
Rule<Integer> intNotSameLengthRule = validator
.intRule("val4", S.of().bindInstance(Map.class, "messages", new LinkedHashMap<>())).withNotSameValue(20)
.withMessageSupplier((messageMap) -> {
return format(msgs.get("E0004"), messageMap.get("label"),messageMap.get("notsame"));
});
Map<Object, Object> data = new LinkedHashMap<Object, Object>();
data.put("val1", 101);
data.put("val2", 4);
data.put("val3", 26);
data.put("val4", 20);
Map<String, List<String>> errors = validator.validate(data,new Rule[] { intMaxLengthRule, intMinLengthRule, intSameLengthRule, intNotSameLengthRule });
System.out.println(errors.get("val1").get(0));
System.out.println(errors.get("val2").get(0));
System.out.println(errors.get("val3").get(0));
System.out.println(errors.get("val4").get(0));
>実行結果
>val1 value is more than 100
>val2 value is less than 5
>val3 value is not 25
>val4 value is 20
④ カスタマイズチェック
Map<String, String> msgs = new HashMap<String, String>();
msgs.put("E0001", "{0} is more than {1}");
Validator validator = new Validator() {};
Rule<Integer> intCustomRule = validator
.intRule("val1", S.of().bindInstance(Map.class, "messages", new LinkedHashMap<>()))
.withCustomPredicate((intVal, errors) -> {
if (intVal > 100) {
errors.add(format(msgs.get("E0001"), intVal,100));
return false;
}
return true;
});
Map<Object, Object> data = new LinkedHashMap<Object, Object>();
data.put("val1", 101);
System.out.println(validator.validate(data, new Rule[] { intCustomRule }).get("val1").get(0));
>実行結果
>101 is more than 100
⑤ 正規表現を利用したチェック
Map<String, String> msgs = new HashMap<String, String>();
msgs.put("E0001", "{0} is not alphabet");
Validator validator = new Validator() {};
Rule<String> stringRule = validator
.stringRule("val", S.of().bindInstance(Map.class, "messages", new LinkedHashMap<>()))
.withRegEx("^[A-Za-z]+$")
.withMessageSupplier((messageMap) -> {
return format(msgs.get("E0001"), messageMap.get("value"));
});
Map<Object, Object> data = new LinkedHashMap<Object, Object>();
data.put("val", 10);
System.out.println(validator.validate(data, new Rule[] { stringRule }).get("val").get(0));
>実行結果
>10 is not alphabet
第08章 キャッシュ機能
使用クラス |
---|
my.simpl.kvs.RedisServer |
① キャッシュサーバに接続する
※デフォルトとして、ローカルホストの「6379」に接続する。
// nullの場合、デフォルトとして、localhostの6379に接続する
RedisServer rs = new RedisServer(null);
// 下記のようにホストとポートを設定する
Map<String, String> configMap = new HashMap<String, String>();
configMap.put("host", "192.168.3.2");
configMap.put("port", "6379");
RedisServer rs = new RedisServer(configMap);
② 値をキャッシュさせる。
期限なしのキャッシュ
RedisServer rs = new RedisServer(null);
rs.set("key", "value");
try {
rs.close();
} catch (Exception e) {
}
期限有りのキャッシュ
RedisServer rs = new RedisServer(null);
// 第3引数に秒単位で設定する。
rs.set("key", "value", 300);
try {
rs.close();
} catch (Exception e) {
}
③ キャッシュされた値を取得する。
RedisServer rs = new RedisServer(null);
rs.set("key", "value");
System.out.println(rs.get("key"));
try {
rs.close();
} catch (Exception e) {
}
>実行結果:
>value
④ キャッシュされた値を削除する。
RedisServer rs = new RedisServer(null);
rs.set("key", "value");
System.out.println("キャッシュ後=" + rs.get("key"));
rs.del("key");
System.out.println("削除後=" + rs.get("key"));
try {
rs.close();
} catch (Exception e) {
}
>実行結果:
>キャッシュ後=value
>削除後=null
第09章 メール送受信機能
使用クラス |
---|
my.simpl.net.mail.Smtp |
my.simpl.net.mail.Imap |
① メール送信
Smtp smtp = new Smtp();
// 送信属性を設定する
Function<MailSender, Properties> propsFunction = (sender) -> {
// メールサーバ、ポート、送信時の認証が必要な場合、ユーザIDとパスワードも設定する。
Properties config = sender.props("localhost", 25, null, null, (props) -> {
// 上記以外の引数を設定する
props.put("mail.smtp.connectiontimeout", "10000");
props.put("mail.smtp.timeout", "10000");
});
return config;
};
// 送信メールの中身(複数件メールを一緒に送信できる)
BiFunction<MailSender, Session, Iterable<MimeMessage>> messageFunction = (sender, session) -> {
Iterable<MimeMessage> mms = new Iterable<MimeMessage>() {
@Override
public Iterator<MimeMessage> iterator() {
MimeMessage mm1 = new MimeMessage(session);
try {
mm1.setRecipients(MimeMessage.RecipientType.TO, "test@localhost");
mm1.setFrom(new InternetAddress("from@localhost"));
mm1.setSubject("mail send subject");
mm1.setText("mail send text");
} catch (MessagingException e) {
}
// 添付ファイルがあるメール
MimeMessage mm2 = new MimeMessage(session);
try {
mm2.setRecipients(MimeMessage.RecipientType.TO, "test@localhost");
mm2.setFrom(new InternetAddress("from@localhost"));
mm2.setSubject("mail send with Attachment");
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText("mail text");
MimeBodyPart mbp2 = new MimeBodyPart();
File attachmentFile = new File("C:\\work\\report.csv");
FileDataSource fds = new FileDataSource(attachmentFile);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(MimeUtility.encodeWord(fds.getName()));
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
mm2.setContent(mp);
} catch (MessagingException | UnsupportedEncodingException e) {
}
List<MimeMessage> mmList = new ArrayList<MimeMessage>();
mmList.add(mm1);
mmList.add(mm2);
return mmList.iterator();
}
};
return mms;
};
// 成功時のハンドル
Consumer<MimeMessage> successHandler = (message) -> {
return;
};
// 送信失敗時のハンドル
BiConsumer<MimeMessage, Throwable> failureHandler = (message, e) -> {
// 送信失敗時の処理を行う。
// 例えば送信内容を出力する
System.out.println(message);
};
// 例外発生時のハンドル
Consumer<Throwable> handler = (e) -> {
// 例外発生時の処理を行う。
// 例えば例外内容を出力する
e.printStackTrace();
};
smtp.send(propsFunction, messageFunction, successHandler, failureHandler, handler);
第10章 Webアプリケーション機能
使用クラス |
---|
my.simpl.web.* |
① Webアプリサーバを起動する。
Server server = new Server() {};
App app = server.server(8080, "localhost", "app", param -> {
param.write("Hello SimplFramework");
}, pathHandler -> {
return pathHandler;
});
// Webアプリを起動する
app.start();
>実行結果:
>「http://localhost:8080/app」にアクセスすると「Hello SimplFrameWork!」がブラウザに表示される。
② クライアントからデータを取得する。
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Data to Server</title>
</head>
<body>
<form th:action="@{index.html}" th:object="${user}" method="post">
<h2>Please sign in</h2>
<fieldset>
<label>User Name</label>
<input type="text" name="username" th:required="required" th:autofocus="autofocus" th:text="${username}" /> <br/>
<label>Password</label>
<input type="password" name="password" th:required="required" th:text="${password}"/> <br />
<input type="submit" value="Sign In" />
</fieldset>
</form>
</body>
</html>
Java側のサンプルソース
String templateFilePath = Paths.get(new File("").getAbsolutePath(), "/template").toString();
Server server = new Server() {
};
App app = server.server(8080, "localhost", "app", param -> {
String path = param.requestPath();
if (path.equals("/"))
path = "index.html";
Res res = null;
if (endsWith(path, ".html")) {
Path filePath = Paths.get(templateFilePath, path);
if (Files.exists(filePath)) {
Map<String, Object> context = null;
if (param.params().isEmpty()) {
context = new LinkedHashMap<String, Object>();
} else {
// クライアントからデータを取得する
String username = param.reqVal("username", String.class);
String pwd = param.reqVal("password", String.class);
context = map("username",String.join(",", username),"password",String.join(",", pwd));
System.out.println(context);
}
res = Template.of(context,
() -> bufferedReader(quiet(() -> Files.newInputStream(filePath)).get(), "utf8"), "thymeleaf");
}
}
if(res == null) res = Echo.of(404);
res.flush(param);
}, pathHandler -> {
return pathHandler;
});
app.start();
>実行結果:
>「http://localhost:8080/app/index.html」にアクセス、「User Name」と「Password」を入力、「Sign In」ボタンを押下、入力の文字がブラウザに表示される。
>サーバコンソール出力:{username=user, password=pass}
③ クライアントにデータを返却する。
・テンプレートを使用して画面を返却する。
・APIを使用して、データのみクライアントへ返却する。
・Echoを使用して、HTTPステータスとメッセージをクライアントへ返却する。
・画面をリダイレクトさせる。
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<div>
<form th:action="@{login.html}" th:object="${user}" method="post">
<h2>Please sign in</h2>
<fieldset>
<label>User Name</label>
<input type="text" name="username" th:required="required" th:autofocus="autofocus" /> <br/>
<label>Password</label>
<input type="password" name="password" th:required="required" /> <br />
<input type="submit" value="Sign In" />
</fieldset>
</form>
</div>
</body>
</html>
login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<div>
<h2>Login</h2>
<label>User Name:</label>
<label th:text="${username}"></label><br/>
<label>Password:</label>
<label th:text="${password}"></label>
</div>
</body>
</html>
welcome.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>welcome</title>
</head>
<body>
<div>
<h2>welcome</h2>
</div>
</body>
</html>
Java側のサンプルソース
String templateFilePath = Paths.get(new File("").getAbsolutePath(), "/template").toString();
String staticFilePath = Paths.get(new File("").getAbsolutePath(), "/static").toString();
Server server = new Server() {
};
App app = server.server(8080, "localhost", "app", param -> {
String path = param.requestPath();
if (path.equals("/"))
path = "index.html";
Res res = null;
if (endsWith(path, ".html")) {
Path filePath = Paths.get(templateFilePath, path);
if (Files.exists(filePath)) {
if (endsWith(path, "login.html")) {
Map<String, Object> context = map("username",
String.join(",", param.reqVal("username", String.class)), "password",
String.join(",", param.reqVal("password", String.class)));
// ・テンプレートを使用して画面を返却する。
res = Template.of(context,
() -> bufferedReader(quiet(() -> Files.newInputStream(filePath)).get(), "utf8"), "thymeleaf");
} else {
Map<String, Object> context = new LinkedHashMap<String, Object>();
res = Template.of(context,
() -> bufferedReader(quiet(() -> Files.newInputStream(filePath)).get(), "utf8"), "thymeleaf");
}
}
} else if (endsWith(path, ".do")) {
// ・APIを使用して、データのみクライアントへ返却する。
res = Api.of().data(200,"OK", map("val", 1200));
} else if (startsWith(path, "/css/") || startsWith(path, "/js/") || startsWith(path, "/img/")) {
Path filePath = Paths.get(staticFilePath, path);
if (Files.exists(filePath)) res = Download.of().content(filePath);
} else {
// ・画面をリダイレクトさせる。
res = Redirect.of("welcome.html");
}
// ・Echoを使用して、HTTPステータスとメッセージをクライアントへ返却する。
if(res == null) res = Echo.of(404);
res.flush(param);
}, pathHandler -> {
return pathHandler;
});
app.start();
>実行結果:
>「http://localhost:8080/app/index.html」にアクセス、「User Name」と「Password」を入力、「Sign In」ボタンを押下、login画面を遷移して、入力の文字がブラウザに表示される。
>「http://localhost:8080/app/aaa」にアクセス、welcome画面を遷移する。
④ ファイルをアップロード/ダウンロードする
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<div>
<form action="upload.html" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">upload</button>
</form>
<form action="download.html" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="text" name="folderpath">
<button type="submit">download</button>
</form>
</div>
</body>
</html>
upload.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>File</title>
</head>
<body>
<label>Uplaod Success</label>
</body>
</html>
download.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>File</title>
</head>
<body>
<label>Download Success</label>
</body>
</html>
Java側のサンプルソース
String templateFilePath = Paths.get(new File("").getAbsolutePath(), "/template").toString();
Server server = new Server() {
};
App app = server.server(8080, "localhost", "app", param -> {
String path = param.requestPath();
if (path.equals("/"))
path = "index.html";
Res res = null;
Path filePath = Paths.get(templateFilePath, path);
if (endsWith(path, "index.html")) {
Map<String, Object> context = new LinkedHashMap();
res = Template.of(context,
() -> bufferedReader(quiet(() -> Files.newInputStream(filePath)).get(), "utf8"), "thymeleaf");
} else if (path.indexOf("upload.html") > 0) {
Map<String, Object> context = new LinkedHashMap();
Map<String, List<Part>> files = param.files();
for (Part file : files.get("file")) {
try {
// アップロードされたファイルを保存する
Files.write(Paths.get(new File("").getAbsolutePath()+"/"+file.getSubmittedFileName()), file.getInputStream().readAllBytes());
res = Template.of(context,
() -> bufferedReader(quiet(() -> Files.newInputStream(filePath)).get(), "utf8"),
"thymeleaf");
} catch (IOException e) {
e.printStackTrace();
}
}
res = Template.of(context,
() -> bufferedReader(quiet(() -> Files.newInputStream(filePath)).get(), "utf8"), "thymeleaf");
}else if (path.indexOf("download.html") > 0) {
Map<String, Object> context = new LinkedHashMap();
Map<String, List<Part>> files = param.files();
for (Part file : files.get("file")) {
try {
// ファイルをダウンロード
res = Download.of().content(file.getInputStream(), file.getSubmittedFileName());
} catch (IOException e) {
e.printStackTrace();
}
}
res = Template.of(context,
() -> bufferedReader(quiet(() -> Files.newInputStream(filePath)).get(), "utf8"), "thymeleaf");
}
if (res == null)
res = Echo.of(404);
res.flush(param);
}, pathHandler -> {
return pathHandler;
});
app.start();
>実行結果:
>「http://localhost:8080/app/index.html」にアクセス、アップロードしたいファイルを選択、「upload」ボタンを押下、ファイルをアップロード。
>「http://localhost:8080/app/index.html」にアクセス、ダウンロードしたいファイルを選択、「download」ボタンを押下、ファイルをダウンロード。
第11章 HTTPアクセス機能
使用クラス |
---|
my.simpl.net.Http |
① GETアクセス
Http http = new Http() {
@Override
public HttpTransport httpTransport() {
HttpTransport transport = null;
try {
transport = GoogleNetHttpTransport.newTrustedTransport();
} catch (GeneralSecurityException | IOException e) {
}
return transport;
}
};
http.get("http://127.0.0.1:8080/app?name=SimplFramework", (httpRequest) -> {
System.out.println(httpRequest.getUrl());
System.out.println(httpRequest.getRequestMethod());
HttpResponse res = httpRequest.execute();
BufferedReader br = new BufferedReader(new InputStreamReader(res.getContent()));
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
});
>実行結果
>http://127.0.0.1:8080/app?name=SimplFramework
>GET
><h3>hello,SimplFramework!!</h3>
② POSTアクセス
Http http = new Http() {
@Override
public HttpTransport httpTransport() {
HttpTransport transport = null;
try {
transport = GoogleNetHttpTransport.newTrustedTransport();
} catch (GeneralSecurityException | IOException e) {
}
return transport;
}
};
http.post("http://127.0.0.1:8080/app?name=SimplFramework Post",http.content("contentText"), (httpRequest) -> {
System.out.println(httpRequest.getUrl());
System.out.println(httpRequest.getRequestMethod());
HttpResponse res = httpRequest.execute();
BufferedReader br = new BufferedReader(new InputStreamReader(res.getContent()));
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
});
>実行結果
>http://127.0.0.1:8080/app?name=SimplFramework%20Post
>POST
><h3>hello,SimplFramework Post!!</h3>
③ PUTアクセス
Http http = new Http() {
@Override
public HttpTransport httpTransport() {
HttpTransport transport = null;
try {
transport = GoogleNetHttpTransport.newTrustedTransport();
} catch (GeneralSecurityException | IOException e) {
}
return transport;
}
};
http.put("http://127.0.0.1:8080/app?name=SimplFramework Put",http.content("contentText"), (httpRequest) -> {
System.out.println(httpRequest.getUrl());
System.out.println(httpRequest.getRequestMethod());
HttpResponse res = httpRequest.execute();
BufferedReader br = new BufferedReader(new InputStreamReader(res.getContent()));
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
});
>実行結果
>http://127.0.0.1:8080/app?name=SimplFramework%20Put
>PUT
><h3>hello,SimplFramework Put!!</h3>
④ DELETEアクセス
Http http = new Http() {
@Override
public HttpTransport httpTransport() {
HttpTransport transport = null;
try {
transport = GoogleNetHttpTransport.newTrustedTransport();
} catch (GeneralSecurityException | IOException e) {
}
return transport;
}
};
http.delete("http://127.0.0.1:8080/app?name=SimplFramework Delete", (httpRequest) -> {
System.out.println(httpRequest.getUrl());
System.out.println(httpRequest.getRequestMethod());
HttpResponse res = httpRequest.execute();
BufferedReader br = new BufferedReader(new InputStreamReader(res.getContent()));
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
});
>実行結果
>http://127.0.0.1:8080/app?name=SimplFramework%20Delete
>DELETE
><h3>hello,SimplFramework Delete!!</h3>
第12章 AWS S3接続機能
使用クラス |
---|
my.simpl.aws.S3Client |
① S3を利用するための準備を行う
Utility util = new Utility() {};
Map<String,String> configMap =
util.map("accessKey","XXXXXXXXXXXXXX"
,"secretKey","XXXXXXXXXXXXXXXX"
,"region","ap-southeast-2"
,"bucket","simpl-testbucket");
S3Client s3 = new S3Client(configMap);
>実行結果:
S3へ接続される
② ファイルのアップロードを行う
s3.saveS3Object("simpl-testbucket", "S3test_up.txt", new File("/work/S3test_up.txt"));
>実行結果:
S3へ
S3test_up.txt
が転送される
③ ファイルの存在チェックを行う
S3URL s3url = new S3URL();
System.out.println(s3.existsS3Object(s3url.of("simpl-testbucket", "S3test_up.txt")));
>実行結果:
>true
④ ファイルのダウンロードを行う
s3.download("simpl-testbucket", "S3test_up.txt", "/work/S3test.txt");
>実行結果:
ローカルPCの
C:\work配下にファイル名
S3test.txt
としてダウンロードされている
⑤ S3上でファイルのコピーを行う
s3.copyS3Object("simpl-testbucket", "S3test_up.txt", "S3test_cp.txt");
>実行結果:
S3へ
S3test_cp.txt
が作成されている
⑥ S3上のファイル削除を行う
s3.deleteS3Object("simpl-testbucket", "S3test_up.txt");
>実行結果:
S3上から
S3test_up.txt
が削除される
第13章 ユーティリティ機能
使用クラス |
---|
my.simpl.Utility |
・対象がnullの場合にデフォルト値を返却する
Utility utility = new Utility() {};
System.out.println(utility.nvl(null, "default"));
System.out.println(utility.nvl("nvl", "default"));
>実行結果:
>default
>nvl
・対象が空の場合にデフォルト値を返却する
Utility utility = new Utility() {};
System.out.println(utility.evl("", "default"));
System.out.println(utility.evl("evl", "default"));
>実行結果:
>default
>evl
・真偽対象がTrueの場合に、指定された処理を実行する
int predicateCount = 0;
Supplier<Boolean> predicate = () -> true;
ThrowsRunnable<Throwable> handler = new ThrowsRunnable<Throwable>() {
@Override
public void run() throws Throwable {
predicateCount++;
}
};
Utility utility = new Utility() {};
//predicateがtrueのため、handlerが実行される
utility.ifPredicate(predicate, handler);
System.out.println(predicateCount);
predicate = () -> false;
predicateCount = 0;
//predicateがfalseのため、handlerは実行されない
utility.ifPredicate(predicate, handler);
System.out.println(predicateCount);
>実行結果:
>1
>0
・対象が存在する場合に、指定された処理を実行する
int predicateCount = 0;
String presentCount = null;
ThrowsRunnable<Throwable>handler = new ThrowsRunnable<Throwable>() {
@Override
public void run() throws Throwable {
presentCount++;
}
};
Utility utility = new Utility() {};
//targetがnullのため、handlerが実行されない
utility.ifPresent(target, handler);
System.out.println(presentCount);
//targetが存在するため、handlerが実行される
target = "TargetExistence";
utility.ifPresent(target, handler);
System.out.println(presentCount);
>実行結果:
>0
>1
・対象がnullでも空でもない場合に、指定された処理を実行する
Utility utility = new Utility() {};
utility.ifNotEmpty("", () -> {
System.out.println("val is empty");
});
utility.ifNotEmpty("not empty", () -> {
System.out.println("val is not empty");
});
>実行結果:
>val is not empty
・配列であることをチェックする
Utility utility = new Utility() {};
String helloString = "hello";
System.out.println(utility.isArray(helloString));
char[] EmptyArray = null;
System.out.println(utility.isArray(EmptyArray));
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
System.out.println(utility.isArray(helloArray));
>実行結果:
>false
>false
>true
・対象が空でないことをチェックする
Utility utility = new Utility() {};
String[] args = { "1", "3" };
System.out.println(utility.isNotEmpty(args));
args = null;
System.out.println(utility.isNotEmpty(args));
args = new String[0];
System.out.println(utility.isNotEmpty(args));
>実行結果:
>true
>false
>false
・対象が空であることをチェックする
Utility utility = new Utility() {};
String[] args = { "1", "3" };
System.out.println(utility.isEmpty(args));
args = null;
System.out.println(utility.isEmpty(args));
args = new String[0];
System.out.println(utility.isEmpty(args));
>実行結果:
>false
>true
>true
・数値の大小チェックをする
第1引数=第2引数 の場合
Utility utility = new Utility() {};
System.out.println(utility.equal(new BigDecimal("5.32"), new BigDecimal("10.32")));
System.out.println(utility.equal(new BigDecimal("10.32"), new BigDecimal("10.32")));
System.out.println(utility.equal(new BigDecimal("10.32"), new BigDecimal("9.32")));
>実行結果:
>false
>true
>false
第1引数≧第2引数 の場合
Utility utility = new Utility() {};
System.out.println(utility.greaterEqual(new BigDecimal("5.32"), new BigDecimal("10.32")));
System.out.println(utility.greaterEqual(new BigDecimal("10.32"), new BigDecimal("10.32")));
System.out.println(utility.greaterEqual(new BigDecimal("10.32"), new BigDecimal("9.32")));
>実行結果:
>false
>true
>true
第1引数>第2引数 の場合
Utility utility = new Utility() {};
System.out.println(utility.greaterThan(new BigDecimal("5.32"), new BigDecimal("10.32")));
System.out.println(utility.greaterThan(new BigDecimal("10.32"), new BigDecimal("10.32")));
System.out.println(utility.greaterThan(new BigDecimal("10.32"), new BigDecimal("9.32")));
>実行結果:
>false
>false
>true
第1引数≦第2引数 の場合
Utility utility = new Utility() {};
System.out.println(utility.lessEqual(new BigDecimal("5.32"), new BigDecimal("10.32")));
System.out.println(utility.lessEqual(new BigDecimal("10.32"), new BigDecimal("10.32")));
System.out.println(utility.lessEqual(new BigDecimal("10.32"), new BigDecimal("9.32")));
>実行結果:
>true
>true
>false
第1引数<第2引数 の場合
Utility utility = new Utility() {};
System.out.println(utility.lessThan(new BigDecimal("5.32"), new BigDecimal("10.32")));
System.out.println(utility.lessThan(new BigDecimal("10.32"), new BigDecimal("10.32")));
System.out.println(utility.lessThan(new BigDecimal("10.32"), new BigDecimal("9.32")));
>実行結果:
>true
>false
>false
・数字の最大値を返却する
Utility utility = new Utility() {};
System.out.println(utility.max(new BigDecimal("5.32"), new BigDecimal("10.32"), new BigDecimal("8.32")));
>実行結果:
>10.32
・数字の最小値を返却する
Utility utility = new Utility() {};
System.out.println(utility.min(new BigDecimal("11.32"), new BigDecimal("10.32"), new BigDecimal("8.32")));
>実行結果:
>8.32
文字列操作
・文字のトリムを行う
Utility utility = new Utility() {};
//左トリム
System.out.println(utility.ltrim(" left "));
//右トリム
System.out.println(utility.rtrim(" right "));
//左右トリム
System.out.println(utility.trim(" all "));
>実行結果:
>left
>right
>all
・開始文字の判定を行う
Utility utility = new Utility() {};
System.out.println(utility.startsWith("start", "st"));
System.out.println(utility.startsWith("start", "tar"));
//大文字小文字を区別しない場合
System.out.println(utility.startsWithIgnoreCase("start", "St"));
>実行結果:
>true
>false
>true
・終了文字の判定を行う
Utility utility = new Utility() {};
System.out.println(utility.endsWith("endwith", "with"));
System.out.println(utility.endsWith("endwith", "end"));
//大文字小文字を区別しない場合
System.out.println(utility.endsWithIgnoreCase("endwith", "wiTH"));
>実行結果:
>true
>false
>true
・正規表現を使った文字列の一致チェックをする
Utility utility = new Utility() {};
System.out.println(utility.isMatch("〒[0-9]{3}-[0-9]{4}", "〒418-0011"));
>実行結果:
>true
・文字結合
Utility utility = new Utility() {};
// 文字列で返却
String concatStr = utility.concat("simple ", "framework ","!!!");
System.out.println(concatStr);
// StringBuilderで返却
StringBuilder builder = utility.buildConcat("simple ", "framework ","!!!");
System.out.println(builder);
// 引数StringBuilderに対して指定の文字列を結合し、StringBuilderで返却
StringBuilder arg1 = new StringBuilder("BuildAppend ");
StringBuilder builder2 = utility.buildAppend(arg1, "simple ", "framework ","!!!");
System.out.println(builder2);
>実行結果:
>simple framework !!!
>simple framework !!!
>BuildAppend simple framework !!!
・文字結合(指定文字列間にセパレータを挿入)
Utility utility = new Utility() {};
String separator = "\\";
String arg1 = "c:";
String arg2 = "work";
String arg3 = "simpl";
// 文字間にseparatorを追加して結合
System.out.println(utility.combine(separator, arg1, arg2, arg3));
// 引数StringBuilderに対して指定の文字列とseparatorを追加して結合
StringBuilder sbBuilder = new StringBuilder("https:");
System.out.println(utility.buildCombine(separator, sbBuilder, args2, ignoreChars).toString());
>実行結果:
>c:\work\simpl
>https:\c:\work\simpl
・文字列分割
Utility utility = new Utility() {};
String target = "a.txt;b.txt;c.txt";
// 対象文字列から指定したデリミタで分割をする
String[] result = utility.split(target, ";");
System.out.println(result[0]);
System.out.println(result[1]);
System.out.println(result[2]);
>実行結果:
>a.txt
>b.txt
>c.txt
・指定の文字数までの範囲で繰り返し文字列を結合する
Utility utility = new Utility() {};
String seed = "あいうえおかき";
System.out.println(utility.concatToLength(seed, 50));
>実行結果:
>あいうえおかきあいうえおかきあいうえおかきあいうえおかきあいうえおかきあいうえおかきあいうえおかき
・カンマ編集をする
Utility utility = new Utility() {};
System.out.println(utility.toComma(1000000));
>実行結果:
>1,000,000
・URLを生成する
// ”/”で文字列を結合する
Utility utility = new Utility() {};
Object[] args =new Object[]{"http://","my","simpl.test"};
System.out.println(utility.url(args));
// クエリ文字列を生成する
String url = "https://simpl.test/index.html";
Object[] args = new Object[4];
args[0] = "user";
args[1] = "simpl";
args[2] = "pwd";
args[3] = "****";
// 指定したURLにクエリ文字列を追加する
System.out.println(utility.withQueryString(url, args));
// クエリ文字列のみを生成する
System.out.println(queryString(args));
>実行結果:
>http://my/simpl.test
>https://simpl.test/index.html?user=simpl&pwd=****
>user=simpl&pwd=****
・渡された内容を1文字ずつ処理する
Utility utility = new Utility() {};
utility.forEachGraph("abcde", (str)->{
System.out.print(str = str + ",");
});
>実行結果:
>a,b,c,d,e,
・ひらがなをカタカナに変換する
Utility utility = new Utility() {};
System.out.println(utility.hiraganaToKatakana("Hello!今日は!こんにちは!コンニチハ!"));
>実行結果:
>Hello!今日ハ!コンニチハ!コンニチハ!
・すべての文字を大文字に変換する
Utility utility = new Utility() {};
System.out.println(utility.toUpper("testdata"));
>実行結果:
>TESTDATA
・すべての文字を小文字に変換する
Utility utility = new Utility() {};
System.out.println(utility.toLower("TESTDATA"));
>実行結果:
>testdata
・文字列の先頭を小文字に変換する
Utility utility = new Utility() {};
System.out.println(utility.toCamel("TESTDATA"));
>実行結果:
>tESTDATA
・文字列の先頭を大文字に変換する
Utility utility = new Utility() {};
System.out.println(utility.toPascal("testdata"));
>実行結果:
>Testdata
・指定したバイト数で文字列を切り詰める
Utility utility = new Utility() {};
System.out.println(utility.truncateBytes("testdata1",4));
>実行結果:
>testAbc
切り詰め後に指定した文字列を結合する
Utility utility = new Utility() {};
// 指定バイト数は結合する文字列のバイト数を含む
System.out.println(utility.truncateBytes("testdata1",7,"Abc"));
>実行結果:
>testAbc
・指定した文字列の文字数をLOCALEのルールに合わせてカウントする
Utility utility = new Utility() {};
System.out.println(utility.countOf("あいうえおかきくけこ", Locale.JAPANESE));
>実行結果:
>10
・配列内の文字列から最大の文字数を返却する
Utility utility = new Utility() {};
String [] target = {"a","bc",null,"ddd","eeeee"};
System.out.println(utility.maxCountOf(target));
>実行結果:
>5
・{n}を任意の文字列を置き換える
Utility utility = new Utility() {};
String message = "明日の天気は{0}のち{1}です。";
Object[] args = new Object[]{"晴れ","曇り"};
System.out.println(utility.format(message, args));
>実行結果:
>明日の天気は晴れのち曇りです。
置き換え文字をフォーマットする場合
Utility utility = new Utility() {};
String message = "相模原市の人口は{0}人です。";
Object[] args = new Object[]{720000};
System.out.println(utility.format(message, args,t -> toComma((int)t)));
>実行結果:
>相模原市の人口は700,000人です。
日付フォーマットを利用する場合
Utility utility = new Utility() {};
Date date = new Date();
String message = "現在の日時は、{0,date,yyyy年MM月dd日} {0,time,HH時mm分ss秒}です。";
System.out.println(utility.format(message, date));
>実行結果:
>現在の日時は、2024年07月21日 21時42分38秒です。
・URLをエンコード/デコードする
// エンコーディング
String EncUrl = urlEncode("https://simpl.net/index.html?aaa=テスト", "utf-8");
System.out.println(EncUrl);
//デコーディング
System.out.println(urlDecode(EncUrl, "utf-8"));
>実行結果:
>https%3A%2F%2Fsimpl.net%2Findex.html%3Faaa%3D%E3%83%86%E3%82%B9%E3%83%88
>https://simpl.net/index.html?aaa=テスト
・base64で文字をエンコードする
Utility utility = new Utility() {};
System.out.println(utility.base64Encode("https://simpl.net/index.html"));
>実行結果:
>aHR0cHM6Ly9zaW1wbC5uZXQvaW5kZXguaHRtbA==
・base64で文字をデコードする
Utility utility = new Utility() {};
System.out.println(utility.base64Decode("aHR0cHM6Ly9zaW1wbC5uZXQvaW5kZXguaHRtbA=="));
>実行結果:
>https://simpl.net/index.html
・UNICODE(16進表記)に変換する(数値文字参照)
Utility utility = new Utility() {};
System.out.println(utility.toHtmlNCR("testParam"));
>実行結果:
>testPar
・対象をシリアライズする
Utility utility = new Utility() {};
System.out.println(java.util.Arrays.toString(utility.serialize("my.simpl.Utility")));
>実行結果:
>[-84, -19, 0, 5, 116, 0, 16, 109, 121, 46, 115, 105, 109, 112, 108, 46, 85, 116, 105, 108, 105, 116, 121]
・対象をデシリアライズする
Utility utility = new Utility() {};
byte[] byteArray = { -84, -19, 0, 5, 116, 0, 16, 109, 121, 46, 115, 105, 109, 112, 108, 46, 85, 116, 105, 108, 105, 116, 121 };
System.out.println(utility.deserialize(byteArray));
>実行結果:
>my.simpl.Utility
・指定した回数分、処理を実行する
int count = 0;
Utility utility = new Utility() {};
utility.loop(5, () -> {
count++;
System.out.println(count);
});
>実行結果:
>1
>2
>3
>4
>5
・クラスのインスタンス化を行う
Utility utility = new Utility() {};
System.out.println(utility.newInstance("my.simpl.Result").getClass().getName());
>実行結果:
>my.simpl.Result
・指定したクラスのメソッドを実行する
String trimString = " ←の空白をトリム";
Utility utility = new Utility() {};
System.out.println(call(utility, "ltrim", new Class<?>[] { String.class }, new Object[]{trimString}));
>実行結果:
>←の空白をトリム
・インスタンスメソッドを実行する
Utility utility = new Utility() {};
System.out.println(utility.invoke(utility, "greaterEqual", new Object[] {new BigDecimal("5.32"), new BigDecimal("10.32")}));
>実行結果:
>false
・指定したクラスを返却する
Utility utility = new Utility() {};
System.out.println(utility.clazz("my.simpl.Args").getSimpleName());
>実行結果:
>Args
・FunctionalInterfaceオブジェクトを取得する
Utility utility = new Utility() {};
utility.lambda(() -> {
System.out.println("lambda run");
}).run();
>実行結果:
>lambda run
・検査例外についてのメソッドを実行する
Utility utility = new Utility() {};
utility.quiet(() -> {
System.out.println("quiet run");
}, (e)->{}).run();
>実行結果:
>quiet run
・要素を指定して、リストを作成する
Utility utility = new Utility() {};
utility.list("arg1","arg2","arg3").forEach((arg)->{
System.out.println(arg);
});
>実行結果:
>arg1
>arg2
>arg3
・キー、値を指定してマップを作成する
Utility utility = new Utility() {};
utility.map("arg1", "val1", "arg2", "val2", "arg3", "val3").forEach((key, val) -> {
System.out.println("key:" + key + " val:" + val);
});
>実行結果:
>key:arg1 val:val1
>key:arg2 val:val2
>key:arg3 val:val3
・リストをマージする
Listの場合
Utility utility = new Utility() {};
List<String> list1 = new ArrayList<String>();
list1.add("l1 val1");
list1.add("l1 val2");
list1.add("l1 val3");
list1.add("l1 val4");
String[] list2 = { "l2 val1", "l2 val2" };
for (Object object : utility.merge(list1, list2)) {
System.out.println(object);
}
>実行結果:
>l1 val1
>l1 val2
>l1 val3
>l1 val4
>l2 val1
>l2 val2
Mapの場合
Utility utility = new Utility() {};
Map<Object, Object> map1 = new LinkedHashMap<Object, Object>();
map1.put("col1", "val1");
map1.put("col11", "val11");
Map<Object, Object> map2 = new LinkedHashMap<Object, Object>();
map1.put("col2", "val2");
map1.put("col22", "val22");
System.out.println(utility.merge(map1, map2));
>実行結果:
>{col1=val1, col11=val11, col2=val2, col22=val22}
・対象をZonedDateTime型へ変換する
Utility utility = new Utility() {};
System.out.println(utility.toZonedDateTime(LocalDateTime.now()));
>実行結果:
>2019-02-27T15:46:45.415409+08:00[Asia/Shanghai]
・対象をLocalDateTime型へ変換する
Utility utility = new Utility() {};
System.out.println(utility.toLocalDateTime((ZonedDateTime.now())));
>実行結果:
>2019-02-27T15:48:55.829914
・対象をLocalDate型へ変換する
Utility utility = new Utility() {};
System.out.println(utility.toLocalDate((ZonedDateTime.now())));
>実行結果:
>2019-02-27
・対象をLocalTime型へ変換する
Utility utility = new Utility() {};
System.out.println(utility.toLocalTime((ZonedDateTime.now())));
>実行結果:
>15:50:38.864704
・対象を指定したクラス型へ変換する
Utility utility = new Utility() {};
System.out.println(utility.to(5,String.class).getClass().getName());
>実行結果:
>java.lang.String
・対象をNumber型へ変換する
Utility utility = new Utility() {};
System.out.println(utility.toNumber("5",Integer.class,0).getClass().getName());
>実行結果:
>java.lang.Integer
・対象をString型へ変換する
Utility utility = new Utility() {};
System.out.println(utility.toString(5).getClass().getName());
>実行結果:
>java.lang.String
・対象を指定したクラスにキャストする。キャストできない場合、nullで返す
Utility utility = new Utility() {};
System.out.println(utility.as("abcd", Integer.class));
System.out.println(utility.as(new DataDefault(), Data.class));
>実行結果:
>null
>my.simpl.DataDefault@3b07d329
・メモリの使用状況を取得する
Utility utility = new Utility() {};
System.out.println(utility.jvmInfoAsMB().get());
>実行結果:
>total:128 MB used:9.15 MB (7.15 %) max=2,048 MB
・指定されたバイト数を、指定した単位に変換する
Utility utility = new Utility() {};
//単位はB,KB,MB.GB,TB,PBを指定可能
System.out.println(utility.calculateSize(new BigDecimal(1000000),"MB"));
>実行結果:
>0.95
・Exceptionを返却する
Utility utility = new Utility() {};
System.out.println(utility.ex("error message").getMessage());
>実行結果:
>error message
・ファイル名として禁則文字が使われていないことをチェックする
List<String> lsStrings = new ArrayList<>();
lsStrings.add("FileName.txt");
System.out.println(isValidFilePathElements(lsStrings));
lsStrings.add("FileName<.txt");
System.out.println(isValidFilePathElements(lsStrings));
>実行結果:
>true
>false
・ファイル名を生成する (ファイル名.拡張子)
String name = "simpl";
String extension = "txt";
System.out.println(fileName(name, extension));
>実行結果:
>simpl.txt
・ファイル名から拡張子を抽出する
String fileName = "simpl.txt";
System.out.println(extention(fileName));
// .が複数含まれている場合
fileName = "simpl.1.2.txt";
System.out.println(extention(fileName));
>実行結果:
>txt
>txt
・ファイルをオープンして、inputStreamを使ってファイル内容を読み込む
Utility utility = new Utility() {};
// テスト用ファイル作成
String filePath = "C:\\temp\\test.txt";
Files.write(Paths.get(filePath), "this is a test file".getBytes(), StandardOpenOption.CREATE);
// 読み取り専用でファイルをオープンして、inputStreamを取得する
InputStream is = utility.inputStream(filePath, StandardOpenOption.READ);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
System.out.println(br.readLine());
>実行結果:
>this is a test file
・ファイルをオープンして、リーダーを使ってファイル内容を読み込む
Utility utility = new Utility() {};
String filePath = "C:\\temp\\test.txt";
Files.write(Paths.get(filePath), "this is a test file".getBytes(), StandardOpenOption.CREATE);
char[] text = new char[1024];
// ファイルをオープンして、ファイルリーダーを取得する
Reader reader = utility.reader(new FileInputStream(new File(filePath)), "UTF-8");
// ファイル内容を取得する
int len = reader.read(text);
System.out.println(new String(text, 0, len));
>実行結果:
>this is a test file
・outputStreamを使って、内容をファイル出力する
Utility utility = new Utility() {};
String filePath = "C:\\temp\\test.txt";
// ファイルを出力するためのアウトプットストリームを作成する
OutputStream out = utility.outputStream(filePath, StandardOpenOption.CREATE);
// 内容を出力する
out.write("this is a out test file".getBytes());
out.close();
>実行結果:
>「this is a out test file」が「C:\temp\test.txt」に出力される
・bufferedOutputStreamを使って、内容をファイルに出力する
Utility utility = new Utility() {};
String filePath = "C:\\temp\\test.txt";
// ファイルを出力するためのBufferedOutputStreamを作成する
BufferedOutputStream out = utility.bufferedOutputStream(filePath, StandardOpenOption.CREATE);
// 内容を出力する
out.write("this is a BufferedOutputStream test file".getBytes());
out.close();
>実行結果:
>「this is a BufferedOutputStream test file」が「C:\temp\test.txt」に出力される
・指定したディレクトリをzipファイル化する。
{code
Utility utility = new Utility() {};
// 出力先ファイルパス
Object outputFilePath = "C:\\work\\ziptest.zip";
// 圧縮対象のパス
Path targetPath = Paths.get("C:\\work\\zip");
//正常終了時はファイルサイズを返却
System.out.println(utility.zip(outputFilePath,targetPath));
>実行結果:
>272
>「C:\work」に「ziptest.zip」が出力される
・zipファイルを解凍する。
Utility utility = new Utility() {};
// 解凍先のパス
Object unZipPath = "C:\\work\\unzip";
// 解凍対象のzipファイル
Object zipFilePath = "C:\\work\\ziptest.zip";
// 正常終了時は解凍後のファイルパスを返却
System.out.println(utility.unzip(unZipPath,"ms932",zipFilePath).toString());
>実行結果:
>[work\unzip\ziptest.zip\zip\ziptest1.txt,work\unzip\ziptest.zip\zip\ziptest2.txt]
>「C:\work\unzip」に「ziptest.zip」が解凍される