ライブラリ
Apache Commons
〇Commons Lang
org.apache.commons.lang.StringUtils
isAllLowerCase
isAllUpperCase
isAlpha
isAlphanumeric
isAlphanumericSpace
isAlphaSpace
isAsciiPrintable
isBlank
isEmpty
isNotBlank
isNotEmpty
isNumeric
isNumbericSpace
isWhitespace
StringUtils.isEmpty(str); // nullと"":true
StringUtils.isNumeric(str);
StringUtils.left(str, 2);
String repeated = StringUtils.repeat(str, 3);
int n = StringUtils.countMatches("11112222", "1"); // 文字列の数をカウント
WordUtils.capialize("ab de"); // Ab De
String j = StringUtils.join(new String[] { "a", "b", "c" }, ", "); // a, b, c
org.apache.commons.lang.StringEscapeUtils
escapeCsv
escapeHtml
escapeJava
escapeJavaScript
escapeSql
escapeXml
unescapeCsv
unescapeHtml
unescapeJava
unescapeJavaScript
unescapeXml
org.apache.commons.lang.RandomStringUtils
randomAlphabetic
randomAlphanumeric
randomAscii
random
RandomStringUtils.randomAlphabetic(10); // 長さ10のアルファベット文字列
RandomStringUtils.randomAscii(10); // 長さ10のASCII文字列
org.apache.commons.lang.ArrayUtils
arr = ArrayUtils.add(arr, 3);
arr = ArrayUtils.remove(arr, 2);
arr = ArrayUtils.subarray(arr, 1, 3);
arr = (String[]) ArrayUtils.clone(arr); // shallow
result = ArrayUtils.contains(arr, "xxx");
result = ArrayUtils.indexOf(arr, "xxx");
result = ArrayUtils.lastIndexOf(arr, "xxx");
result = ArrayUtils.isEmpty(arr);
result = ArrayUtils.isSameLength(arr1, arr2);
result = ArrayUtils.isEquals(arr1, arr2);
ArrayUtils.EMPTY_OBJECT_ARRAY
result = ArrayUtils.toPrimitive(arr); // Integer[]⇒int[]
result = ArrayUtils.toObject(arr); // int[]⇒Integer[]
String[][] countries = { { "Japan", "Tokyo" }, { "France", "Paris" } };
Map countryCapital = ArrayUtils.toMap(countries);
int[] combinedIntArray = ArrayUtils.addAll(intArray1, intArray2);
ArrayUtils.reverse(intArray);
int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
org.apache.commons.lang.math.NumberUtils
num = NumberUtils.toInt(str);
num = NumberUtils.toInt(str, -1); // 失敗時に指定
num = NumberUtils.max(arr);
num = NumberUtils.min(arr);
org.apache.commons.lang.math.RandomUtils
num = RandomUtils.nextInt(10); // 0~9
org.apache.commons.lang.builder.*
class Person{
private String name;
private int age;
// getter/setter
@Override
public String toString() {
return new ToStringBuilder(this)
.append("名前", this.name)
.append("年齢", this.age)
.toString();
// 或いは
return ReflectionToStringBuilder.toString(this);
return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object obj) {
if(obj == null){
return false;
}
if(obj == this){
return true;
}
if(obj.getClass() != getClass()){
return false;
}
Person p = (Person)obj;
return new EqualsBuilder()
//.appendSuper(super.equals(obj))
.append(this.name, p.name)
.append(this.age, p.age)
.isEquals();
// 或いは
return EqualsBuilder.reflectionEquals(this, other);
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.appand(this.name)
.appand(this.age)
.toHashCode();
// 或いは
return HashCodeBuilder.reflectionHashCode(this);
}
}
public class Employee implements Comparable<Employee> {
...
@Override
public int compareTo(Employee other) {
return new CompareToBuilder()
.appand(this.id, other.id)
.appand(this.name, other.name)
.toComparison();
// 或いは
return CompareToBuilder.reflectionCompare(this, other);
}
}
org.apache.commons.lang.time.DateUtils、DateFormatUtils
isSameDay(date1, date2)
date = DateUtils.parseDate("2013/01/01 12:45:36", new String[]{"yyyy/MM/dd HH:mm:ss"});
DateFormatUtils.format(new Date(), "yyyy/MM/dd HH:mm:ss");
org.apache.commons.lang.SystemUtils
System.getProperty("os.name");
↓
SystemUtils.OS_NAME
org.apache.commons.lang.ClassUtils
packageName = ClassUtils.getPackageName(String.class);
className = ClassUtils.getShortClassName(String.class);
List<Class> interfaces = ClassUtils.getAllInterfaces(String.class);
List<Class> superClass = ClassUtils.getAllSuperclasses(String.class);
org.apache.commons.lang.reflect.*
long time = ...;
Constructor<Date> constructor = Date.class.getConstructor(Long.TYPE);
Date date = constructor.newInstance(time);
↓
Date date = (Date) ConstructorUtils.invokeConstructor(Date.class, time);
Method method = Date.class.getMethod("after", Date.class);
boolean result = (boolean) method.invoke(date1, date2);
↓
boolean result = MethodUtils.invokeMethod(date1, "after", date2);
// staticメソッドの場合:invokeStaticMethod
Employee emp = new Employee();
Field field = Employee.class.getField("name");
field.set(emp, "Andy");
String name = (String) field.get(emp);
↓
FieldUtils.writeField(emp, "name", "Andy");
String name = (String) FieldUtils.readField(emp, "name");
org.apache.commons.lang.SerializationUtils
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(person);
byte[] date = out.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(date);
ObjectInputStream objIn = ObjectInputStream(in);
Person result = (Person) objIn.readObject();
↓
byte[] date = SerializationUtils.serialize(person);
Person result = (Person) SerializationUtils.deserialize(data);
org.apache.commons.lang.exception.ExceptionUtils
String stackTrace = ExceptionUtils.getStackTrace(ex);
String rootMessage = ExceptionUtils.getRootCauseMessage(ex);
Throwable t = ExceptionUtils.getRootCause(ex);
〇Commons BeanUtils
org.apache.commons.beanutils.BeanUtils
BeanUtils.setProperty(bean, "name", "Andy");
String name = BeanUtils.getProperty(bean, "name");
String[] elements = BeanUtils.getArrayProperty(bean, "array");
String element = BeanUtils.getIndexedProperty(bean, "array", 1);
String element = BeanUtils.getProperty(bean, "array[1]");
String element = BeanUtils.getMappedProperty(bean, "map", "key");
String element = BeanUtils.getProperty(bean, "map.key");
BeanUtils.copyProperties(dest, bean);
Employee clone = (Employee) BeanUtils.cloneBean(bean);
Map<String, String> map = BeanUtils.describe(bean); // bean⇒Map
BeanUtils.populate(bean, map); // Map⇒bean
※BeanUtils:アクセサメソッドに向け
※S2Util:publicフィールドに向け
〇Commons Collections
ListUtils, MapUtil
Seasar2のユーティリティ
〇S2BeanUtils(JavaBean、Mapなどをコピー)
org.seasar.framework.beans.util.Beans
SrcBean src = new SrcBean();
DestBean dest = new DestBean();
Beans.copy(src, dest).execute();
DestBean dest = Beans.createAndCopy(DestBean.class, src).execute();
Beans.copy(src, dest).excludes("foo", "bar").excludesNull().excludesWhitespace().execute();
Beans.copy(src, dest).includes("foo", "bar").execute();
Beans.copy(src, dest).prefix("to").execute();
DestBean dest = Beans.createAndCopy(DestBean.class, src).dateConverter("yyyy/MM/dd", "updateDate").execute();
dateConverter java.util.Date
sqlDateConverter java.sql.Date
timeConverter java.sql.Time
timestampConverter java.sql.Timestamp
numberConverter
〇HTTP関連
org.seasar.struts.util.RequestUtil、ResponseUtil、ServletContextUtil
HttpServletRequest getRequest()
String getPath()
HttpServletResponse getResponse()
void download(String fileName, byte[] data)
void download(String fileName, InputStream in)
void download(String fileName, InputStream in, int length)
void write(String text)
void write(String text, String contentType)
void write(String text, String contentType, String encoding)
ServletContextUtil getServlietContext()
String getViewPrefix()
〇文字列
org.seasar.framework.util.StringUtil
camelize / decamelize:USER_ID ⇔ UserId
capitalize / decapitalize:userId ⇔ UserId
contains
startsWithIgnoreCase / endsWithIgnoreCase
equals / equalsIgnoreCase
isBlank / isNotBlank
isEmpty / isNotEmpty
isNumber
ltrim / ltrim(String text, String trimText)
rtrim / rtrim(String text, String trimText)
replace
split
substringFromLast / substringToLast
trimPrefix / trimSuffix
〇配列
org.seasar.framework.util.ArrayUtil
add:配列にオブジェクト・配列を追加
contains
equalsIgnoreSequence
indexOf
isEmpty
remove
toList
toObjectArray
toString
〇コレクション
org.seasar.framework.util.tiger.Maps、Pair、Tuple3、Tuple4、Tuple5
Map<String, String> map = Maps.map("k1", "v1").$("k2", "v2").$("k3", "v3").$();
Pair<String, String> pair = Pair.pair("aaa", "bbb");
String first = pair.getFirst();
String second = pair.getSecond();
pair.setFirst("xxx");
pair.setSecond("yyy");
org.seasar.framework.util.tiger.IterableAdapter、EnumerationAdapter
Enumeration ⇔ Iterable・Iterator
for(String name : new IterableAdapter<String>(request.getParameterNames())) {
...
}
〇入出力関係
org.seasar.framework.util.FileUtil
void copy(File src, File dest)
byte[] getBytes(File file)
URL toURL(File file)
void write(String path, byte[] data)
void write(String path, byte[] data, int offset, int length)
byte[] data = FileUtil.getBytes(file);
FileUtil.write("D:/test.txt", data);
org.seasar.framework.util.InputStreamUtil、OutputStreamUtilなど
void close(InputStream is)
void copy(InputStream is, OutputStream os)
byte[] getBytes(InputStream is)
void reset(InputStream is)
〇リソース関連
org.seasar.framework.util.ResourceUtil
File bin = ResourceUtil.getBuildDir(XXX.class);
File jar = ResourceUtil.getBuildDir(S2Container.class); // Jarファイル
if(ResourceUtil.isExist("app.dicon")) {
File file = ResourceUtil.getResourceAsFile("app.dicon");
InputStream in = ResourceUtil.getResourceAsStream("app.dicon");
...
}
org.seasar.framework.util.MimeTypeUtil
String mimeType = MimeTypeUtil.guessContentType("env.txt");
org.seasar.framework.util.TextUtil
String readText(File file)
String readText(String path)
String readUTF8(File file)
String readUTF8(String path)
〇リフレクション関係
org.seasar.framework.util.ClassUtil、MethodUtil、FieldUtil
Method method = ClassUtil.getMethod(Hoge.class, "methodName", null);
Object result = MethodUtil.invoke(method, hoge, null);
Field field = ClassUtil.getField(Hoge.class, "fieldName");
FieldUtil.set(field, hoge, "xxx");]
org.seasar.framework.util.ReflectionUtil
Field field = ReflectionUtil.getDeclareField(this.getClass(), "fieldName");
Class<?> clazz = ReflectionUtil.getElementTypeOfCollectionFromFieldType(field);
org.seasar.framework.util.AnnotationUtil
Annotation[] annotations = obj.getClass().getAnnotations();
for(Annotation annotation : annotations) {
if(annotation.annotationType().getName().equals("xxx")) {
Map<String, Object> props = AnnotationUtil.getProperties(annotation);
...
}
}
〇その他
org.seasar.framework.util.Base64Util
String encoded = Base64Util.encode(data);
byte[] decoded = Base64Util.decode(encoded);
Lombok
Eclipseで利用方法:
Step 1.java -jar lombok-1.12.2.jar
Step 2.Specify location: $ECLIPSE_HOME/eclipse
Step 3.Click Install/Update
Step 4.Restart Eclipse
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.12.2</version>
<scope>provided</scope>
</dependency>
import com.google.common.collect.Lists;
import lombok.*;
@ToString(exclude="id")
@EqualsAndHashCode(exclude="id")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Test {
private final long id = 0L;
@Getter @Setter
private String name;
@Getter(AccessLevel.PROTECTED)
private int phone;
@Delegate
List<String> list = new ArrayList<String>();
val list = Lists.newArrayList();
public void hoge(String inputFile, String outputFile)
throws IOException {
@Cleanup InputStream in = new FileInputStream(inputFile);
@Cleanup OutputStream out = new FileOutputStream(outputFile);
...
}
@Synchronized
@SneakyThrows //発生する例外を非検査例外として扱う
public void read() {
FileReader in = new FileReader("data.txt");
...
}
}
注意点
@ToString
class Foo{
List<FooDetail> details;
}
@ToString(exclude="parent") // 循環参照を切る
class FooDetail{
Foo parent;
}
lombokで生成されたソースを出力する方法
<plugin>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-maven-plugin</artifactId>
<version>1.14.8.0</version>
<executions>
<execution>
<id>delombok</id>
<phase>generate-sources</phase>
<goals>
<goal>delombok</goal>
</goals>
<configuration>
<encoding>UTF-8</encoding>
<addOutputDirectory>false</addOutputDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
</configuration>
</execution>
<execution>
<id>test-delombok</id>
<phase>generate-test-sources</phase>
<goals>
<goal>testDelombok</goal>
</goals>
<configuration>
<encoding>UTF-8</encoding>
<addOutputDirectory>false</addOutputDirectory>
<sourceDirectory>src/test/java</sourceDirectory>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>sun.jdk</groupId>
<artifactId>tools</artifactId>
<version>1.7</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
</dependencies>
</plugin>
RxJava
Functional Reactive Programming
https://github.com/Netflix/RxJava/wiki
ModelMapper
http://modelmapper.org/user-manual/
Deltaspike
CDIを拡張