Skip to content
Open
2 changes: 2 additions & 0 deletions OWNER.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Айнулин Ринат Рафикович

82 changes: 74 additions & 8 deletions src/main/java/track/container/Container.java
Original file line number Diff line number Diff line change
@@ -1,34 +1,100 @@
package track.container;

import java.lang.reflect.Field;
import java.util.Arrays;
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 Map<String, Bean> beanById;
private Map<String, Bean> beanByClassName;
private Map<String, Object> objByName;
private Map<String, Object> objByClassName;

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

beanById = new HashMap<>();
beanByClassName = new HashMap<>();
objByName = new HashMap<>();
objByClassName = new HashMap<>();
for (Bean bean : beans) {
beanById.put(bean.getId(), bean);
beanByClassName.put(bean.getClassName(), bean);
}
}

/**
* Вернуть объект по имени бина из конфига
* Например, Car car = (Car) container.getById("carBean")
* Вернуть объект по имени бина из конфига
* Например, Car car = (Car) container.getById("carBean")
*/
public Object getById(String id) {
return null;
public Object getById(String id) throws ClassNotFoundException, InvalidConfigurationException, IllegalAccessException,
InstantiationException, NoSuchFieldException {
if (objByName.containsKey(id)) {
return objByName.get(id);
} else {
Bean bean = beanById.get(id);
if (bean == null) {
throw new InvalidConfigurationException("There are not bean with this id");
}
Class clazz = Class.forName(bean.getClassName());
Object object = clazz.newInstance();
for (Map.Entry<String, Property> entry : bean.getProperties().entrySet()) {
Property property = entry.getValue();
Field field = clazz.getDeclaredField(property.getName());
field.setAccessible(true);
if (property.getType().equals(ValueType.VAL)) {
Object value = Integer.parseInt(property.getValue());
field.set(object, value);
} else if (property.getType().equals(ValueType.REF)) {
String depClassName = beanById.get(property.getValue()).getClassName();
if (!objByClassName.containsKey(depClassName)) {
Class depClazz = Class.forName(depClassName);
if (isCircularDependency(bean.getClassName(), depClazz.getDeclaredFields())) {
throw new InvalidConfigurationException("There is a circular dependency");
} else {
Object value = getByClass(depClassName);
field.set(object, value);
}
} else {
field.set(object, objByClassName.get(depClassName));
}
}
}
objByClassName.put(bean.getClassName(), object);
objByName.put(bean.getId(), object);
return object;
}
}

private boolean isCircularDependency(String className, Field[] declaredFields) {
for (Field field : declaredFields) {
if (field.getType().getName().equals(className)) {
return true;
}
}
return false;
}

/**
* Вернуть объект по имени класса
* Например, Car car = (Car) container.getByClass("track.container.beans.Car")
*/
public Object getByClass(String className) {
return null;
public Object getByClass(String className) throws ClassNotFoundException, NoSuchFieldException,
InstantiationException, InvalidConfigurationException, IllegalAccessException {
if (objByClassName.containsKey(className)) {
return objByClassName.get(className);
} else {
return getById(beanByClassName.get(className).getId());
}
}
}
43 changes: 39 additions & 4 deletions src/main/java/track/container/JsonConfigReader.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package track.container;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

/**
* TODO: Реализовать
Expand All @@ -14,6 +19,36 @@ public class JsonConfigReader implements ConfigReader {

@Override
public List<Bean> parseBeans(File configFile) throws InvalidConfigurationException {
return null;
ObjectMapper mapper = new ObjectMapper();
List<Bean> beans = new ArrayList<>();
try {
JsonNode root = mapper.readTree(configFile).path("beans");
for (JsonNode currentNode : root) {
String id = currentNode.path("id").asText();
String className = currentNode.path("className").asText();
Map<String, Property> properties = createPropertyMap(currentNode.path("properties"));
beans.add(new Bean(id, className, properties));
}
return beans;
} catch (IOException e) {
throw new InvalidConfigurationException("Invalid configuration");
}
}

private Map<String, Property> createPropertyMap(JsonNode jsonNode) throws InvalidConfigurationException {
Map<String, Property> properties = new HashMap<>();
for (JsonNode currentNode : jsonNode) {
String name = currentNode.path("name").asText();
Property property = null;
if (currentNode.has("ref")) {
property = new Property(name, currentNode.path("ref").asText(), ValueType.REF);
} else if (currentNode.has("val")) {
property = new Property(name, currentNode.path("val").asText(), ValueType.VAL);
} else {
throw new InvalidConfigurationException("There are not value for " + name);
}
properties.put(name, property);
}
return properties;
}
}
29 changes: 22 additions & 7 deletions src/main/java/track/container/Main.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
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.util.List;

/**
*
*/
Expand All @@ -13,13 +21,20 @@ 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();
try {
File file = new File(JsonConfigReader.class.getClassLoader().getResource("config.json").getFile());
List<Bean> beans = reader.parseBeans(file);
System.out.println(beans);
Container container = new Container(beans);

Car car = (Car) container.getByClass("track.container.beans.Car");
car = (Car) container.getById("carBean");

System.out.println(car);
} catch (Exception e) {
e.printStackTrace();
}


}
Expand Down
12 changes: 9 additions & 3 deletions src/main/java/track/lessons/lesson2/Document.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
package track.lessons.lesson2;

import java.util.Arrays;
/**
*
*/

public class Document {
String[] tokens;

public Document(String[] tokens) {
this.tokens = tokens;
}

String[] getTokens() {
return null;
return tokens;
}

int getTokenCount() {
return 0;
return tokens.length;
}

boolean hasToken(String token) {
return false;
return Arrays.asList(tokens).contains(token);
}
}
17 changes: 13 additions & 4 deletions src/main/java/track/lessons/lesson2/Parser.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,35 @@

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;

/**
*
*/
public class Parser {

Document parse(String data) {
return null;
return new Document(data.split(" "));
}

public static void main(String[] args) throws Exception {

String path = "path/to/file";
String path = "test.txt";
BufferedReader reader = new BufferedReader(new FileReader(path));

// reader умеет читать по строкам с помощью метода readLine()
StringBuilder stringBuilder = new StringBuilder();

Parser parser = new Parser();
// Создайте объект Parser
String currentString = reader.readLine();
while (currentString != null) {
stringBuilder.append(currentString);
currentString = reader.readLine();
}

// Получите объект Document, реализовав метод parse()


Document document = parser.parse(stringBuilder.toString());
System.out.println(Arrays.toString(document.getTokens()));
}
}
80 changes: 79 additions & 1 deletion src/main/java/track/lessons/lesson3/DynamicList.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,85 @@
package track.lessons.lesson3;

import java.util.Arrays;

/**
*
*/
public class DynamicList {
public class DynamicList extends List {

private static final int DEFAULT_CAPACITY = 10;
private int[] elements;
private int size;

public DynamicList() {
elements = new int[DEFAULT_CAPACITY];
}

public DynamicList(int capacity) {
if (capacity >= 0) {
elements = new int[capacity];
} else {
throw new IllegalArgumentException("Invalid capacity");
}
}

@Override
public void add(int item) {
if (size == elements.length) {
resize(2 * elements.length);
}
elements[size++] = item;
}

private void resize(int capacity) {
int[] copy = new int[capacity];
System.arraycopy(elements, 0, copy, 0, size);
elements = copy;
}

@Override
public int remove(int idx) {
if (!isValidId(idx)) {
throw new IndexOutOfBoundsException("Invalid index");
}
final int item = elements[idx];
System.arraycopy(elements, idx + 1, elements, idx, (size - 1) - idx);
size--;
if (size > 0 && size == elements.length / 4) {
resize(elements.length / 2);
}
return item;
}

@Override
public int get(int idx) {
if (!isValidId(idx)) {
throw new IndexOutOfBoundsException("Invalid index");
}
return elements[idx];
}

@Override
public int size() {
return size;
}

public int capacity() {
return elements.length;
}

private boolean isValidId(int id) {
return id >= 0 || id < size;
}

@Override
public String toString() {
int[] elems = new int[size];
System.arraycopy(elements, 0, elems, 0, size);
return "DynamicList{" +
"elements=" + Arrays.toString(elems) +
", size=" + size +
", capacity=" + elements.length +
'}';
}
}
Loading