Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ target/
classes/
*.iml
.idea
target/classes/google_checkstyle.xml
1 change: 1 addition & 0 deletions OWNER.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fazlytdinov Rishat
37 changes: 37 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{"beans": [
{
"id": "carBean",
"className": "track.container.beans.Car",
"properties": [
{
"name": "gear",
"ref": "gearBean"
},
{
"name": "engine",
"ref": "engineBean"
}
]
},
{
"id": "gearBean",
"className": "track.container.beans.Gear",
"properties": [
{
"name": "count",
"val": "6"
}
]
},
{
"id": "engineBean",
"className": "track.container.beans.Engine",
"properties": [
{
"name": "power",
"val": "200"
}
]
}
]
}
34 changes: 34 additions & 0 deletions messenger.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.12" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-log4j12:1.7.5" level="project" />
<orderEntry type="library" name="Maven: log4j:log4j:1.2.17" level="project" />
<orderEntry type="module-library">
<library name="Maven: com.oracle:ojdbc:14">
<CLASSES>
<root url="jar://$MODULE_DIR$/lib/ojdbc6.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="library" name="Maven: org.mockito:mockito-all:1.10.19" level="project" />
<orderEntry type="library" name="Maven: org.postgresql:postgresql:9.4-1204-jdbc42" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.8.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.8.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.8.3" level="project" />
</component>
</module>
10 changes: 10 additions & 0 deletions src/main/java/track/Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package track;

/**
* Created by major on 27.10.16.
*/
public class Test {
public static void main(String[] args) {

}
}
146 changes: 144 additions & 2 deletions src/main/java/track/container/Container.java
Original file line number Diff line number Diff line change
@@ -1,26 +1,47 @@
package track.container;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import track.container.config.Bean;
import track.container.config.InvalidConfigurationException;
import track.container.config.Property;
import track.container.config.ValueType;

/**
* Основной класс контейнера
* У него определено 2 публичных метода, можете дописывать свои методы и конструкторы
*/
public class Container {

private static final String INT = "int";

private Map<String, Bean> beansById;
private Map<String, Bean> beansByClassName;

// Реализуйте этот конструктор, используется в тестах!
public Container(List<Bean> beans) {
beansById = new HashMap<>();
beansByClassName = new HashMap<>();

for (Bean bean : beans) {
this.beansById.put(bean.getId(), bean);
this.beansByClassName.put(bean.getClassName(), bean);
}
}

/**
* Вернуть объект по имени бина из конфига
* Например, Car car = (Car) container.getById("carBean")
* Вернуть объект по имени бина из конфига
* Например, Car car = (Car) container.getById("carBean")
*/
public Object getById(String id) {
try {
return makeRequiredObject(beansById.get(id));
} catch (InvalidConfigurationException e) {
System.out.println(e.getMessage());
}
return null;
}

Expand All @@ -29,6 +50,127 @@ public Object getById(String id) {
* Например, Car car = (Car) container.getByClass("track.container.beans.Car")
*/
public Object getByClass(String className) {
try {
return makeRequiredObject(beansByClassName.get(className));
} catch (InvalidConfigurationException e) {
System.out.println(e.getMessage());
}
return null;
}

public Object makeRequiredObject(Bean bean) throws InvalidConfigurationException {
try {
Class beanClass = Class.forName(bean.getClassName());
Object object = beanClass.getConstructor().newInstance();
for (Property property : bean.getProperties()) {
Object propertyValue = null;
if (property.getType().equals(ValueType.VAL)) {
propertyValue = property.getVal();
}
if (property.getType().equals(ValueType.REF)) {
propertyValue = getById(property.getVal());
}
char[] properyNameCharSet = property.getName().toCharArray();
properyNameCharSet[0] = Character.toUpperCase(properyNameCharSet[0]);
String properyName = new String(properyNameCharSet);
for (Method method : object.getClass().getDeclaredMethods()) {
if (method.getName().equals("set" + properyName)) {
for (Primitives primitive : Primitives.values()) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

интересное решение. Единственное, я бы хранил все примитивы в мапе, чтобы вытаскивать их по типу за одно действие (а не в цикле)

if (method.getParameterTypes()[0].getName().equals(primitive.getType())) {
propertyValue = primitive.parse((String) propertyValue);
}
}
method.invoke(object, propertyValue);
}
}
}
return object;
} catch (Exception e) {
InvalidConfigurationException ex = new InvalidConfigurationException("Invalid config");
throw ex;
}
}


private enum Primitives {
BOOLEAN {
private String type = "boolean";

public Boolean parse(String value) {
return Boolean.parseBoolean(value);
}

@Override
public String getType() {
return type;
}
},
SHORT {
private String type = "short";

public Short parse(String value) {
return Short.parseShort(value);
}

@Override
public String getType() {
return type;
}
},
INTEGER {
private String type = "int";

public Integer parse(String value) {
return Integer.parseInt(value);
}

@Override
public String getType() {
return type;
}
},
LONG {
private String type = "long";

public Long parse(String value) {
return Long.parseLong(value);
}

@Override
public String getType() {
return type;
}

},
DOUBLE {
private String type = "double";

public Double parse(String value) {
return Double.parseDouble(value);
}

@Override
public String getType() {
return type;
}
},
FLOAT {
private String type = "float";

public Float parse(String value) {
return Float.parseFloat(value);
}

@Override
public String getType() {
return type;
}
};

public abstract Object parse(String value);

public abstract String getType();

}

}
22 changes: 16 additions & 6 deletions src/main/java/track/container/JsonConfigReader.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,29 @@
package track.container;

import java.io.File;
import java.util.List;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

import track.container.config.Bean;
import track.container.config.ConfigReader;
import track.container.config.InvalidConfigurationException;
import com.fasterxml.jackson.databind.ObjectMapper;
import track.container.config.*;

/**
* TODO: Реализовать
*/
public class JsonConfigReader implements ConfigReader {

@Override
public List<Bean> parseBeans(File configFile) throws InvalidConfigurationException {
return null;
public List<Bean> parseBeans(File configFile) throws InvalidConfigurationException, IOException {
ObjectMapper mapper = new ObjectMapper();
Root root;
try {
root = mapper.readValue(configFile,Root.class);
} catch (IOException e) {
throw new InvalidConfigurationException(e.getMessage());
}

return root.getBeans();
}
}
26 changes: 18 additions & 8 deletions src/main/java/track/container/Main.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
package track.container;

import track.container.beans.Car;
import track.container.config.Bean;
import track.container.config.ConfigReader;
import track.container.config.InvalidConfigurationException;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
*
*/
public class Main {

public static void main(String[] args) {
public static void main(String[] args) throws InvalidConfigurationException, IOException {

/*

Expand All @@ -14,13 +23,14 @@ public static void main(String[] args) {
*/

// // При чтении нужно обработать исключение
// ConfigReader reader = new JsonReader();
// List<Bean> beans = reader.parseBeans("config.json");
// Container container = new Container(beans);
//
// Car car = (Car) container.getByClass("track.container.beans.Car");
// car = (Car) container.getById("carBean");

ConfigReader reader = new JsonConfigReader();
List<Bean> beans = reader.parseBeans(new File("config.json"));
Container container = new Container(beans);

Car car = (Car) container.getByClass("track.container.beans.Car");
System.out.println(car.toString());
car = (Car) container.getById("carBean");
System.out.println(car.toString());

}
}
13 changes: 9 additions & 4 deletions src/main/java/track/container/config/Bean.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package track.container.config;

import java.util.List;
import java.util.Map;

/**
* Представляет тег bean из конфига
*/
public class Bean {

public Bean() {
}

private String id; // Уникальный ID бина
private String className; // Класс бина

Expand All @@ -17,19 +21,20 @@ public class Bean {
put(key, value) - поместить значение с заданным ключом
get(key) - получить значение по ключу (или null, если не найдено)
*/
private Map<String, Property> properties; // Набор полей бина ИмяПоля-Значение
private List<Property> properties; // Набор полей бина ИмяПоля-Значение


public Bean(String id, String className, Map<String, Property> properties) {
public Bean(String id, String className, List<Property> properties) {
this.id = id;
this.className = className;
this.properties = properties;
}

public Map<String, Property> getProperties() {
public List<Property> getProperties() {
return properties;
}

public void setProperties(Map<String, Property> properties) {
public void setProperties(List<Property> properties) {
this.properties = properties;
}

Expand Down
Loading