Skip to content

Commit d476f33

Browse files
committed
Примеры по аннотациям, сериализации и многопоточности
1 parent 6d9f359 commit d476f33

12 files changed

Lines changed: 418 additions & 0 deletions

File tree

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.idea
2+
*.iml

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,11 @@
11
# fizteh-java-2015-ext
2+
3+
Для запуска примеров в IDE нужно включить поддержку обработчиков аннотаций
4+
> для IntelliJ IDEA: File | Settings | Build, Execution, Deployment | Compiler | Annotation Processors |
5+
флаг Enable annotation processing)
6+
7+
## Ссылки на примеры
8+
* Репозиторий проекта: https://github.com/schebotarev/fizteh-java-2015-ext
9+
* Использование аннотаций для конфигурирования библиотеки: http://jcommander.org/
10+
* Приложение визуальной демонстрации возможностей многопоточности в Java:
11+
http://sourceforge.net/projects/javaconcurrenta/

samples/pom.xml

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
5+
<groupId>ru.mipt.diht.samples</groupId>
6+
<artifactId>fizteh-java-2015-ext</artifactId>
7+
<packaging>jar</packaging>
8+
<version>1.0</version>
9+
10+
<name>fizteh-java-2015-ext</name>
11+
<url>https://github.com/schebotarev/fizteh-java-2015-ext</url>
12+
13+
<properties>
14+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15+
<jackson_lib_ver>2.1.4</jackson_lib_ver>
16+
</properties>
17+
18+
<build>
19+
<plugins>
20+
<plugin>
21+
<groupId>org.apache.maven.plugins</groupId>
22+
<artifactId>maven-compiler-plugin</artifactId>
23+
<version>3.3</version>
24+
<!--<configuration>-->
25+
<!--<compilerVersion>1.8</compilerVersion>-->
26+
<!--<source>1.8</source>-->
27+
<!--<target>1.8</target>-->
28+
<!--</configuration>-->
29+
</plugin>
30+
</plugins>
31+
</build>
32+
33+
<dependencies>
34+
<!-- Common -->
35+
<dependency>
36+
<groupId>org.projectlombok</groupId>
37+
<artifactId>lombok</artifactId>
38+
<version>1.16.6</version>
39+
<scope>provided</scope>
40+
</dependency>
41+
<dependency>
42+
<groupId>org.slf4j</groupId>
43+
<artifactId>slf4j-simple</artifactId>
44+
<version>1.7.12</version>
45+
</dependency>
46+
47+
<!-- Serialization -->
48+
<dependency>
49+
<groupId>com.fasterxml.jackson.core</groupId>
50+
<artifactId>jackson-core</artifactId>
51+
<version>${jackson_lib_ver}</version>
52+
</dependency>
53+
<dependency>
54+
<groupId>com.fasterxml.jackson.core</groupId>
55+
<artifactId>jackson-databind</artifactId>
56+
<version>${jackson_lib_ver}</version>
57+
</dependency>
58+
<dependency>
59+
<groupId>com.fasterxml.jackson.core</groupId>
60+
<artifactId>jackson-annotations</artifactId>
61+
<version>${jackson_lib_ver}</version>
62+
</dependency>
63+
64+
<dependency>
65+
<groupId>junit</groupId>
66+
<artifactId>junit</artifactId>
67+
<version>4.8.1</version>
68+
<scope>test</scope>
69+
</dependency>
70+
</dependencies>
71+
</project>
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package ru.mipt.diht.samples.model;
2+
3+
import lombok.Data;
4+
5+
import javax.xml.bind.annotation.XmlRootElement;
6+
import java.util.Date;
7+
8+
/**
9+
* @author s.chebotarev
10+
* @since 05.11.2015
11+
*/
12+
@XmlRootElement
13+
@Data
14+
public class Car {
15+
private String id;
16+
private String model;
17+
private Date dateOfManufacture;
18+
private int priceRur;
19+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package ru.mipt.diht.samples.serialization.json;
2+
3+
import com.fasterxml.jackson.core.JsonProcessingException;
4+
import com.fasterxml.jackson.databind.ObjectMapper;
5+
6+
import java.io.IOException;
7+
8+
/**
9+
* @author s.chebotarev
10+
* @since 05.11.2015
11+
*/
12+
public class JsonSerializer {
13+
private final ObjectMapper mapper;
14+
15+
public JsonSerializer() {
16+
mapper = new ObjectMapper();
17+
}
18+
19+
public String toJson(Object object) {
20+
try {
21+
return mapper.writeValueAsString(object);
22+
} catch (JsonProcessingException e) {
23+
throw new RuntimeException("failed to create json from: " + object, e);
24+
}
25+
}
26+
27+
public <T> T fromJson(String json, Class<T> type) {
28+
try {
29+
return mapper.readValue(json, type);
30+
} catch (IOException e) {
31+
throw new RuntimeException("failed to read object from json: " + json, e);
32+
}
33+
}
34+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package ru.mipt.diht.samples.serialization.xml;
2+
3+
import lombok.SneakyThrows;
4+
5+
import javax.xml.bind.JAXBContext;
6+
import javax.xml.bind.Marshaller;
7+
import javax.xml.bind.Unmarshaller;
8+
import java.io.StringReader;
9+
import java.io.StringWriter;
10+
11+
/**
12+
* @author s.chebotarev
13+
* @since 05.11.2015
14+
*/
15+
public class XmlSerializer {
16+
@SneakyThrows
17+
public String toXml(Object object) {
18+
JAXBContext context = JAXBContext.newInstance(object.getClass());
19+
Marshaller marshaller = context.createMarshaller();
20+
StringWriter writer = new StringWriter();
21+
marshaller.marshal(object, writer);
22+
return writer.toString();
23+
}
24+
25+
@SneakyThrows
26+
public <T> T fromXml(String xml, Class<T> type) {
27+
JAXBContext context = JAXBContext.newInstance(type);
28+
Unmarshaller unmarshaller = context.createUnmarshaller();
29+
Object result = unmarshaller.unmarshal(new StringReader(xml));
30+
return type.cast(result);
31+
}
32+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package ru.mipt.diht.samples.utils;
2+
3+
import java.text.ParseException;
4+
import java.text.SimpleDateFormat;
5+
import java.util.Date;
6+
7+
/**
8+
* @author s.chebotarev
9+
* @since 05.11.2015
10+
*/
11+
public class Utils {
12+
/*
13+
* Возвращает объект Date с указанной в формате "yyyy.MM.dd" датой.
14+
**/
15+
public static Date parseDate(String dateStr) {
16+
try {
17+
return new SimpleDateFormat("yyyy.MM.dd").parse(dateStr);
18+
} catch (ParseException e) {
19+
throw new RuntimeException("illegal date: " + dateStr, e);
20+
}
21+
}
22+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"id": "id5342",
3+
"model": "IBM 2101",
4+
"dateOfManufacture": 348872400000,
5+
"priceRur": 0
6+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?xmlversion= "1.0" encoding= "UTF-8" ?>
2+
<root xmlns:fivt="http://fivt.fizteh.ru/common">
3+
<element attribute="attributevalue&quot; ">
4+
text
5+
<!--comment-->
6+
<![CDATA[
7+
<escaped_text/>
8+
<![CDATA[
9+
<escaped_text/>
10+
]] >
11+
<!-- no escape for "]] >" w/o space -->
12+
]]>
13+
</element>
14+
<fivt:element/>
15+
</root>
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
package ru.mipt.diht.samples.reflection;
2+
3+
import lombok.extern.slf4j.Slf4j;
4+
import org.junit.Test;
5+
import ru.mipt.diht.samples.model.Car;
6+
7+
import java.lang.reflect.Constructor;
8+
import java.lang.reflect.Field;
9+
import java.lang.reflect.Method;
10+
import java.util.ArrayList;
11+
import java.util.Collection;
12+
13+
import static org.junit.Assert.*;
14+
15+
/**
16+
* @author s.chebotarev
17+
* @since 05.11.2015
18+
*/
19+
@Slf4j
20+
public class SimpleReflectionTest {
21+
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
22+
private Collection<Car> carsHolder = new ArrayList<>();
23+
24+
@Test
25+
public void testGeneratedMethods() throws Exception {
26+
Class<?> enrichedType = Car.class;
27+
Method[] methods = enrichedType.getDeclaredMethods();
28+
for (Method method : methods) {
29+
log.info("{}({}): {}", method.getName(), method.getParameterTypes(), method.getReturnType().getSimpleName());
30+
}
31+
assertTrue("there are generated methods", methods.length > 0);
32+
}
33+
34+
@Test
35+
public void testFields() {
36+
Field[] fields = Car.class.getDeclaredFields();
37+
for (Field field : fields) {
38+
log.info("{}: {}", field.getName(), field.getType().getSimpleName());
39+
}
40+
assertTrue("there are some fields", fields.length > 0);
41+
}
42+
43+
@Test
44+
public void testConstuctors() {
45+
Constructor[] constructors = Car.class.getDeclaredConstructors();
46+
for (Constructor constructor : constructors) {
47+
log.info("{}", constructor);
48+
}
49+
assertTrue("there are some constructors", constructors.length > 0);
50+
}
51+
52+
@Test
53+
public void testDynamicObjectClass() {
54+
Object obj = new Car();
55+
assertEquals("car class", Car.class, obj.getClass());
56+
assertSame("car class", Car.class, obj.getClass());
57+
assertEquals("string class", String.class, "123".getClass());
58+
assertSame("string class", String.class, "123".getClass());
59+
}
60+
61+
@Test
62+
public void testParentClasses() {
63+
Class type = Car.class;
64+
Class parent = type.getSuperclass();
65+
assertNotNull("Car.super", parent);
66+
67+
log.info("inspecting Car.class superclasses");
68+
for (; type != null; type = type.getSuperclass()) {
69+
log.info("=> {}", type.getSimpleName());
70+
}
71+
72+
log.info("inspecting Class.class superclasses");
73+
type = Class.class;
74+
for (; type != null; type = type.getSuperclass()) {
75+
log.info("=> {}", type.getSimpleName());
76+
}
77+
}
78+
79+
@Test
80+
public void testGenericsInfo() throws Exception {
81+
log.info("{}", getClass().getDeclaredField("carsHolder").getGenericType());
82+
log.info("{}", carsHolder.getClass().getTypeParameters());
83+
}
84+
85+
@Test
86+
public void testPublicAccess() throws Exception {
87+
Car car = new Car();
88+
car.setId("id123");
89+
Object res = Car.class.getMethod("getId").invoke(car);
90+
log.info("call res: {}", res);
91+
}
92+
93+
@Test(expected = IllegalAccessException.class)
94+
public void testIllegalPrivateAccess() throws Exception {
95+
Car car = new Car();
96+
car.setId("id123");
97+
Object res = Car.class.getDeclaredField("id").get(car);
98+
log.info("field access res: {}", res);
99+
}
100+
101+
@Test
102+
public void testSetAccessible() throws Exception {
103+
Car car = new Car();
104+
car.setId("id123");
105+
Field field = Car.class.getDeclaredField("id");
106+
field.setAccessible(true); // only for this instance
107+
Object res = field.get(car);
108+
log.info("field access res: {}", res);
109+
}
110+
111+
@Test
112+
public void testConstructor() throws Exception {
113+
Car car1 = new Car();
114+
Car car2 = Car.class.newInstance();
115+
assertNotNull(car2);
116+
assertEquals(car1, car2);
117+
assertNotSame(car1, car2);
118+
}
119+
120+
@Test
121+
public void testAnnotation() throws Exception {
122+
Test annotation = getClass().getMethod("testIllegalPrivateAccess").getAnnotation(Test.class);
123+
assertNotNull(annotation);
124+
assertEquals("expected exception", IllegalAccessException.class, annotation.expected());
125+
assertEquals("timeout", 0, annotation.timeout());
126+
assertEquals("timeout", 0L, annotation.annotationType().getMethod("timeout").getDefaultValue());
127+
}
128+
129+
@Test
130+
public void testClassForName() throws Exception {
131+
assertEquals("Car class found by name", Car.class, Class.forName("ru.mipt.diht.samples.model.Car"));
132+
}
133+
}

0 commit comments

Comments
 (0)