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 OWNER.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Anton Gerasimenko Vyacheslavovich
90 changes: 71 additions & 19 deletions src/main/java/track/container/Container.java
Original file line number Diff line number Diff line change
@@ -1,34 +1,86 @@
package track.container;

import java.util.List;
import java.lang.reflect.Field;
import java.util.*;

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

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

private Map<String, Bean> beanId;
private Map<String, Bean> beanClass;
private Map<String, Object> objByName;
private Map<String, Object> objByClassName;

// Реализуйте этот конструктор, используется в тестах!
public Container(List<Bean> beans) {
beanId = new HashMap<>();
beanClass = new HashMap<>();
objByClassName = new HashMap<>();
objByName = new HashMap<>();
for (Bean bean : beans) {
beanId.put(bean.getId(), bean);
beanClass.put(bean.getClassName(), bean);
}
}

public Object getById(String id) throws IllegalAccessException, InstantiationException, NoSuchFieldException, InvalidConfigurationException, ClassNotFoundException {
if (objByName.containsKey(id)) {
return objByName.get(id);
} else {
if (beanId.get(id) == null) {
throw new InvalidConfigurationException("No id");
}
Class clazz = Class.forName(beanId.get(id).getClassName());
Object obj = clazz.newInstance();
for (Map.Entry<String, Property> entry : beanClass.get(id).getProperties().entrySet()) {
Property prop = entry.getValue();
Field field = clazz.getDeclaredField(prop.getName());
field.setAccessible(true);
if (prop.getType().equals(ValueType.VAL)) {
Object value = Integer.parseInt(prop.getValue());
field.set(obj, value);
Copy link
Collaborator

Choose a reason for hiding this comment

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

В задании указано, что значения полей в объекте выставлять через методы setValue()

} else {
if (prop.getType().equals(ValueType.REF)) {
String className = beanId.get(prop.getValue()).getClassName();
if (!objByClassName.containsKey(className)) {
Class classN = Class.forName(className);
if (isDepend(beanId.get(id).getClassName(), classN.getDeclaredFields())) {
throw new InvalidConfigurationException("No dependency");
} else {
Object value = getByClass(className);
field.set(obj, value);
}
} else {
field.set(obj, objByClassName.get(className));
}
}
}
}
objByClassName.put(beanId.get(id).getClassName(), obj);
objByName.put(beanId.get(id).getId(), obj);
return obj;
}
}

/**
* Вернуть объект по имени бина из конфига
* Например, Car car = (Car) container.getById("carBean")
*/
public Object getById(String id) {
return null;
public boolean isDepend(String classN, Field[] declaredF) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

метод лучше сделать приватным. доступ к нему снаружи не нужен

for (Field field : declaredF) {
if (field.getType().getName().equals(classN)) {
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(beanClass.get(className).getId());
Copy link
Collaborator

Choose a reason for hiding this comment

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

здесь тест падает с NPE. нужна проверка на существование бина

}
}
}
}
49 changes: 40 additions & 9 deletions src/main/java/track/container/JsonConfigReader.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,50 @@
package track.container;

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

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: Реализовать
*/
public class JsonConfigReader implements ConfigReader {

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

public Map<String, Property> createProperty(JsonNode jsonNode) throws InvalidConfigurationException {
Map<String, Property> properties = new HashMap<>();
for (JsonNode indexNode : jsonNode) {
String name = indexNode.path("name").asText();
Property property = null;
if (indexNode.has("ref")) {
property = new Property(name, indexNode.path("ref").asText(), ValueType.REF);
} else {
if (indexNode.has("val")) {
property = new Property(name, indexNode.path("val").asText(), ValueType.VAL);
} else {
throw new InvalidConfigurationException("Not value");
}
}
properties.put(name, property);
}
return properties;
}
}
40 changes: 20 additions & 20 deletions src/main/java/track/container/Main.java
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
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;

public class Main {

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> bean = reader.parseBeans(file);
System.out.println(bean);
Container container = new Container(bean);
Car car = (Car) container.getByClass("track.container.beans.Car");
car = (Car) container.getById("carBean");
System.out.println(car);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
17 changes: 10 additions & 7 deletions src/main/java/track/lessons/lesson2/Document.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
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);
}
}
}
27 changes: 14 additions & 13 deletions src/main/java/track/lessons/lesson2/Parser.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,27 @@

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()

// Создайте объект Parser

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


StringBuilder stringBuilder = new StringBuilder();
Parser parser = new Parser();
String currentString = reader.readLine();
while (currentString != null) {
stringBuilder.append(currentString);
currentString = reader.readLine();
}

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

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

private static int defaultsize = 10;
private int[] array;
private int size;

public DynamicList(int size) {
if (size > 0) {
array = new int[size];
} else {
array = new int[defaultsize];
}
this.size = 0;
}

public DynamicList() {
array = new int[defaultsize];
size = 0;
}


@Override
void add(int item) {
if (size == array.length) {
int[] newArray = new int[array.length * 2];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
array[size++] = item;
}

@Override
int remove(int idx) {
int value;
if (!isRange(idx)) {
value = array[idx];
System.arraycopy(array, idx + 1, array, idx, size - idx - 1);
size--;
} else {
value = -1;
}
return value;
}

private boolean isRange(int idx) {
return idx < 0 || idx > size - 1;
}

@Override
int get(int idx) {
if (!isRange(idx)) {
return array[idx];
} else {
throw new IndexOutOfBoundsException("Index is incorrect");
}
}

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