Category Archives: Java

「Java」Introspector.getBeanInfo()でオブジェクト(object)をMapに相互変換するサンプルコード

Javaコード
public Map<String,Object> obj2Map(Object obj) throws Exception{
Map<String,Object> map=new HashMap<String, Object>();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.compareToIgnoreCase(“class”) == 0) {
continue;
}
Method getter = property.getReadMethod();
Object value = getter!=null ? getter.invoke(obj) : null;
map.put(key, value);
}
return map;
}

public Object map2Obj(Map<String,Object> map,Class<?> clz) throws Exception{
if (map == null)
return null;
Object obj = clz.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = property.getWriteMethod();
if (setter != null) {
setter.invoke(obj, map.get(property.getName()));
}
}
return obj;
}

「Java」getClass().getDeclaredFields()でオブジェクト(object)をMapに相互変換するサンプルコード

Javaコード
public Map<String,Object> Obj2Map(Object obj) throws Exception{
Map<String,Object> map=new HashMap<String, Object>();
Field[] fields = obj.getClass().getDeclaredFields();
for(Field field:fields){
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
public Object map2Obj(Map<String,Object> map,Class<?> clz) throws Exception{
Object obj = clz.newInstance();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for(Field field:declaredFields){
int mod = field.getModifiers();
if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
return obj;
}

「Java」org.apache.commons.beanutilsでオブジェクト(object)をMapに相互変換するコード

Javaコード:
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass)
throws Exception {
if (map == null)
return null;
Object obj = beanClass.newInstance();
org.apache.commons.beanutils.BeanUtils.populate(obj, map);
return obj;
}

public static Map<?, ?> objectToMap(Object obj) {
if (obj == null) {
return null;
}
return new org.apache.commons.beanutils.BeanMap(obj);
}

「Java」sessionのremoveAttribute()とinvalidate()の書き方

セッションキーに対応する値を削除
request.getSession().removeAttribute(“userSession”);

セッションの破棄
request.getSession().invalidate();

「Java」 java.net.Socketでクライアント側、サーバー側のscoketを操作する

1.Client側
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SockClientDemo {
public static void main(String args[]) {
try {
// 4700ポートにリクエスト
Socket socket = new Socket(“127.0.0.1”, 4700);
// PrintWriterオブジェクト
PrintWriter os = new PrintWriter(socket.getOutputStream());
// BufferedReaderオブジェクト
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
os.println(“it is a test demo”);
os.flush();
os.close();
is.close();
socket.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}

 

2.Server側
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SockServerDemo {

public static void main(String args[]) {
try {
ServerSocket server = null;
//4700ポートをListen
server = new ServerSocket(4700);
Socket socket = null;
//accept()
socket = server.accept();
//BufferedReaderオブジェクト
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//PrintWriterオブジェクト
PrintWriter os = new PrintWriter(socket.getOutputStream());
System.out.println(“server:” + is.readLine());
os.close();
is.close();
socket.close();
server.close();
} catch (Exception e) {
e.getStackTrace();
}

}
}

「Java」org.apache.struts2.interceptor.SessionAwareを実装するサンプルコード

Javaコード:
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
public class SessionDemoAction extends ActionSupport implements SessionAware {
private Map session;
public void setSession(Map session) {
this.session = session;
}
public String execute() {
this.session.put(“USER_NAME”, “yamada_user”);
return SUCCESS;
}
}

「java」Struts2のの複数条件の書き方

例1
<s:if test=”条件1″>
<s:if test=”条件2″>
</s:if>
</s:if>

例2
<s:if test=”条件&&条件2″>

「Java」BeanUtils.describe()を利用するコサンプルコード

Javaコード
SampleObject a = new SampleObject();
a.setDisplay(“this is a test data”);
a.setName(“A”);
a.setNum(5);
a.setWords(“goto”.toCharArray());

SampleObjectA b = new SampleObjectA();
b.setDisplay(“ta bi bi property”);
b.setNum(new Double(2.0));
b.setName(“sampleA”);
a.setSample(b);
try {
Map cftMap = BeanUtils.describe(a);
System.out.println(cftMap);
}

「java」テキストファイルを読み込むサンプルコード

Javaコード
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ReadWriteDeno {

public void writeFile() {
String str = “test prpgrame”;
try {
FileOutputStream out = new FileOutputStream(“c:/tiantian/ReadWrite2.txt”);
out.write(str.getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public void readFile() {
try {
FileInputStream in = new FileInputStream(“c:/tiantian/read22.txt”);
byte bs[] = new byte[in.available()];
in.read(bs);
System.out.println(“file content=\n” + new String(bs));
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
ReadWriteDeno t = new ReadWriteDeno();
t.readFile();
t.writeFile();

}

「java」Log4jログにRolling FileとSocket Appenderを設定するサンプルコード

########################
# Rolling File
########################
log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE.Threshold=ERROR
log4j.appender.ROLLING_FILE.File=rolling.log
log4j.appender.ROLLING_FILE.Append=true
log4j.appender.ROLLING_FILE.MaxFileSize=10KB
log4j.appender.ROLLING_FILE.MaxBackupIndex=1
log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d – %c -%-4r [%t] %-5p %c %x – %m%n

 

####################
# Socket Appender
####################
log4j.appender.SOCKET=org.apache.log4j.RollingFileAppender
log4j.appender.SOCKET.RemoteHost=localhost
log4j.appender.SOCKET.Port=5001
log4j.appender.SOCKET.LocationInfo=true
# Set up for Log Facter 5
log4j.appender.SOCKET.layout=org.apache.log4j.PatternLayout
log4j.appender.SOCET.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD]%n%c[CATEGORY]%n%m[MESSAGE]%n%n

 

########################
# Log Factor 5 Appender
########################
log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender
log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000