Skip to content

Commit dcc0380

Browse files
committed
initial commit
0 parents  commit dcc0380

File tree

12 files changed

+322
-0
lines changed

12 files changed

+322
-0
lines changed

.classpath

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<classpath>
3+
<classpathentry kind="src" path="src"/>
4+
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
5+
<classpathentry kind="lib" path="libs/commons-codec-1.7.jar"/>
6+
<classpathentry kind="output" path="bin"/>
7+
</classpath>

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
bin/
2+
.settings/

.project

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<projectDescription>
3+
<name>JavaSnippets</name>
4+
<comment></comment>
5+
<projects>
6+
</projects>
7+
<buildSpec>
8+
<buildCommand>
9+
<name>org.eclipse.jdt.core.javabuilder</name>
10+
<arguments>
11+
</arguments>
12+
</buildCommand>
13+
</buildSpec>
14+
<natures>
15+
<nature>org.eclipse.jdt.core.javanature</nature>
16+
</natures>
17+
</projectDescription>

README.txt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
JavaSnippets: Snippets of useful/interesting Java code
2+
- Java: 1.6
3+
4+
VERSION HISTORY
5+
6+
v1.0
7+
- Serializing and encoding
8+
- Example of printing the date
9+
- Using reflection to make a dynamic object
10+

libs/commons-codec-1.7.jar

254 KB
Binary file not shown.

src/benblack86/date/FormatDate.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package benblack86.date;
2+
3+
import java.text.SimpleDateFormat;
4+
import java.util.Calendar;
5+
import java.util.TimeZone;
6+
7+
public class FormatDate {
8+
9+
public static void main(String args[]) {
10+
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HH:mm:ss.SSS");
11+
sdf.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("GMT")));
12+
13+
System.out.println("NOW: "+sdf.format(System.currentTimeMillis()));
14+
}
15+
}

src/benblack86/dynamic/ObjA.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package benblack86.dynamic;
2+
3+
public class ObjA extends RequestObject {
4+
public String name;
5+
public String location;
6+
7+
@Override
8+
public void execute() {
9+
System.out.printf("%s\n", this.toString());
10+
}
11+
12+
}

src/benblack86/dynamic/ObjB.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package benblack86.dynamic;
2+
3+
public class ObjB extends RequestObject {
4+
public String name;
5+
public double height;
6+
public double width;
7+
8+
@Override
9+
public void execute() {
10+
System.out.printf("%s|area:%s\n", this.toString(), height*width);
11+
}
12+
13+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package benblack86.dynamic;
2+
3+
import java.lang.reflect.Field;
4+
import java.util.HashMap;
5+
import java.util.Map;
6+
7+
public class RequestHandler {
8+
public static void main(String[] args) {
9+
RequestHandler requestHandler = new RequestHandler();
10+
11+
requestHandler.processRequest("ObjA|name:Ben|location:NYC").execute();
12+
requestHandler.processRequest("ObjB|name:Chen|width:40|height:182").execute();
13+
requestHandler.processRequest("ObjB|name:Izo|height:100").execute();
14+
}
15+
16+
public RequestObject processRequest(String input) {
17+
try {
18+
String[] components = input.split("\\|");
19+
20+
// create the object requested and get its fields
21+
Class<?> requestClass = Class.forName("benblack86.dynamic." + components[0]);
22+
RequestObject object = (RequestObject) requestClass.newInstance();
23+
Field[] fields = requestClass.getFields();
24+
25+
// create a map for quick access (should cache in real system)
26+
Map<String, Field> nameToField = new HashMap<String, Field>();
27+
for(int i = 0; i< fields.length; i++) {
28+
nameToField.put(fields[i].getName(), fields[i]);
29+
}
30+
31+
// loop over components and set value on to object
32+
for(int i = 1; i < components.length; i++) {
33+
int split = components[i].indexOf(":");
34+
String variable = components[i].substring(0, split);
35+
String value = components[i].substring(split+1);
36+
37+
Field field = nameToField.get(variable);
38+
39+
if(field != null) {
40+
field.set(object, stringToObject(field.getType(), value));
41+
}
42+
43+
}
44+
45+
46+
return object;
47+
} catch(Exception e) {
48+
e.printStackTrace();
49+
}
50+
51+
return null;
52+
}
53+
54+
private Object stringToObject(Class<?> parameter, String value) {
55+
if(parameter == String.class) {
56+
return value;
57+
} else if(parameter == boolean.class || parameter == Boolean.class) {
58+
return Boolean.valueOf(value);
59+
} else if(parameter == int.class || parameter == Integer.class) {
60+
return Integer.valueOf(value);
61+
} else if(parameter == double.class || parameter == Double.class) {
62+
return Double.valueOf(value);
63+
} else if(parameter == long.class || parameter == Long.class) {
64+
return Long.valueOf(value);
65+
} else if(parameter == short.class || parameter == Short.class) {
66+
return Short.valueOf(value);
67+
} else if(parameter == float.class || parameter == Float.class) {
68+
return Float.valueOf(value);
69+
} else if(parameter == byte.class || parameter == Byte.class) {
70+
return Byte.valueOf(value);
71+
}
72+
73+
return null;
74+
}
75+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package benblack86.dynamic;
2+
3+
import java.lang.reflect.Field;
4+
5+
public abstract class RequestObject {
6+
public String toString() {
7+
StringBuffer prop = new StringBuffer(this.getClass().getSimpleName());
8+
try {
9+
Class<?> requestClass = this.getClass();
10+
Field[] fields = requestClass.getFields();
11+
12+
for(int i = 0; i < fields.length; i++ ) {
13+
prop.append("|").append(fields[i].getName()).append(":").append(fields[i].get(this));
14+
}
15+
} catch (Exception e) {
16+
e.printStackTrace();
17+
}
18+
19+
20+
return prop.toString();
21+
}
22+
23+
public abstract void execute();
24+
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
package benblack86.properties;
2+
3+
import java.beans.Introspector;
4+
import java.beans.PropertyDescriptor;
5+
import java.lang.reflect.Method;
6+
import java.util.HashMap;
7+
import java.util.Map;
8+
9+
public enum PropertiesManager {
10+
INSTANCE;
11+
12+
public static void main(String[] args) {
13+
System.out.printf("Prop1:%s\n", PropertiesManager.INSTANCE.isProp1());
14+
System.out.printf("Prop2:%s\n", PropertiesManager.INSTANCE.getProp2());
15+
System.out.printf("Prop3:%s\n", PropertiesManager.INSTANCE.getProp3());
16+
}
17+
18+
19+
private boolean prop1;
20+
private String prop2;
21+
private int prop3;
22+
23+
private PropertiesManager() {
24+
try {
25+
Map<String, Method> methods = new HashMap<String, Method>();
26+
27+
for(PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors()){
28+
if(propertyDescriptor.getWriteMethod() != null) {
29+
String name = propertyDescriptor.getWriteMethod().getName();
30+
31+
// cut off "set" from method name
32+
if(name.startsWith("set")) {
33+
methods.put(name.substring(3), propertyDescriptor.getWriteMethod());
34+
}
35+
}
36+
}
37+
38+
// normally this data would be loaded from somewhere
39+
Map<String, String> properties = new HashMap<String, String>();
40+
properties.put("Prop1", "true");
41+
properties.put("Prop2", "hello");
42+
properties.put("Prop3", "34");
43+
44+
for(String property : properties.keySet()) {
45+
if(methods.containsKey(property)) {
46+
Method method = methods.get(property);
47+
48+
Class<?> parameter = method.getParameterTypes()[0];
49+
50+
if(parameter == String.class) {
51+
method.invoke(this, properties.get(property));
52+
} else if(parameter == boolean.class || parameter == Boolean.class) {
53+
method.invoke(this, Boolean.valueOf(properties.get(property)));
54+
} else if(parameter == int.class || parameter == Integer.class) {
55+
method.invoke(this, Integer.valueOf(properties.get(property)));
56+
} else if(parameter == double.class || parameter == Double.class) {
57+
method.invoke(this, Double.valueOf(properties.get(property)));
58+
} else if(parameter == long.class || parameter == Long.class) {
59+
method.invoke(this, Long.valueOf(properties.get(property)));
60+
} else if(parameter == short.class || parameter == Short.class) {
61+
method.invoke(this, Short.valueOf(properties.get(property)));
62+
} else if(parameter == float.class || parameter == Float.class) {
63+
method.invoke(this, Float.valueOf(properties.get(property)));
64+
} else if(parameter == byte.class || parameter == Byte.class) {
65+
method.invoke(this, Byte.valueOf(properties.get(property)));
66+
}
67+
} else {
68+
throw new Exception("property "+property+" not definned in PropertiesManager");
69+
}
70+
}
71+
} catch(Exception e) {
72+
e.printStackTrace();
73+
}
74+
}
75+
76+
public boolean isProp1() {
77+
return prop1;
78+
}
79+
80+
public void setProp1(boolean prop1) {
81+
this.prop1 = prop1;
82+
}
83+
84+
public String getProp2() {
85+
return prop2;
86+
}
87+
88+
public void setProp2(String prop2) {
89+
this.prop2 = prop2;
90+
}
91+
92+
public int getProp3() {
93+
return prop3;
94+
}
95+
96+
public void setProp3(int prop3) {
97+
this.prop3 = prop3;
98+
}
99+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package benblack86.serialize;
2+
3+
import java.io.ByteArrayInputStream;
4+
import java.io.ByteArrayOutputStream;
5+
import java.io.IOException;
6+
import java.io.ObjectInputStream;
7+
import java.io.ObjectOutputStream;
8+
9+
import org.apache.commons.codec.binary.Base64;
10+
11+
/**
12+
* Requires commons-codec for the encoding/decoding
13+
*
14+
*/
15+
public class SerializeEncoder {
16+
17+
public static void main(String[] args) {
18+
try {
19+
String example = "Hello world";
20+
21+
String encode = SerializeEncoder.seralizeAndEncode(example);
22+
String decode = SerializeEncoder.decodeAndDesealize(encode);
23+
24+
System.out.printf("Encode: %s\n", encode);
25+
System.out.printf("Decode: %s\n", decode);
26+
27+
} catch(Exception e) {
28+
e.printStackTrace();
29+
}
30+
}
31+
32+
33+
public static String seralizeAndEncode(String value) throws IOException {
34+
ByteArrayOutputStream baos = new ByteArrayOutputStream();
35+
ObjectOutputStream oos = new ObjectOutputStream(baos);
36+
oos.writeObject(value);
37+
oos.close();
38+
return new String(Base64.encodeBase64(baos.toByteArray()));
39+
}
40+
41+
public static String decodeAndDesealize(String value) throws IOException, ClassNotFoundException {
42+
byte data[] = Base64.decodeBase64(value);
43+
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
44+
Object o = ois.readObject();
45+
ois.close();
46+
return (String)o;
47+
}
48+
}

0 commit comments

Comments
 (0)