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
Binary file added .OWNER.md.swo
Binary file not shown.
Binary file added .OWNER.md.swp
Binary file not shown.
1 change: 1 addition & 0 deletions OWNER.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Alyona Pasevyeva
78 changes: 72 additions & 6 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.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
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 List<Bean> beans;
private Map<String, Bean> beanById;
private Map<String, Bean> beanByClassName;
private Map<String, Object> objByClassName;
Copy link
Owner

Choose a reason for hiding this comment

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

зачем?


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

this.beans = beans;
beanById = new HashMap<>();
beanByClassName = 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")
*/
public Object getById(String id) {
return null;
public Object getById(String id) throws ClassNotFoundException, IllegalAccessException, InstantiationException,
Copy link
Owner

Choose a reason for hiding this comment

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

Слишком сложная сигнатура, как этим методом пользоваться будем? Давайте бросать какое-то одно кастомное исключение на все ошибки

InvalidConfigurationException, InvocationTargetException, NoSuchFieldException, NoSuchMethodException {
if (beanById.containsKey(id)) {
Bean bean = beanById.get(id);
Copy link
Owner

Choose a reason for hiding this comment

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

так его можно и вернуть?

if (objByClassName.containsKey(bean.getClassName())) {
return objByClassName.get(bean.getClassName());
}
Class clazz = Class.forName(bean.getClassName());
Object object = clazz.newInstance();
for (Map.Entry<String, Property> propertyPair: bean.getProperties().entrySet()) {
Property property = propertyPair.getValue();
Field field = clazz.getDeclaredField(property.getName());
field.setAccessible(true);
Object value;
if (property.getType() == ValueType.VAL) {
value = stringToPrimitive(field.getType(), property.getValue());
} else {
value = getByClass(field.getType().getName());
}
field.set(object, value);
Copy link
Owner

Choose a reason for hiding this comment

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

В задании нужно сделать через метод setField()

field.setAccessible(false);
}
objByClassName.put(bean.getClassName(), object);
return object;
}
throw new InvalidConfigurationException("Invalid configuration");
}


/**
* Вернуть объект по имени класса
* Например, Car car = (Car) container.getByClass("track.container.beans.Car")
*/
public Object getByClass(String className) {
return null;
public Object getByClass(String className) throws ClassNotFoundException, IllegalAccessException,
Copy link
Owner

Choose a reason for hiding this comment

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

ТОже с сигнатурой

InstantiationException, InvalidConfigurationException, InvocationTargetException, NoSuchFieldException,
NoSuchMethodException {
if (beanByClassName.containsKey(className)) {
return getById(beanByClassName.get(className).getId());
}
throw new InvalidConfigurationException("Invalid configuration");
}

private Object stringToPrimitive(Type type, String value) {
switch (type.getTypeName()) {
case ("byte") : return Byte.parseByte(value);
Copy link
Owner

Choose a reason for hiding this comment

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

А если Byte/Integer/Long?

case ("short") : return Short.parseShort(value);
case("int") : return Integer.parseInt(value);
case ("long") : return Long.parseLong(value);
case ("boolean") : return Boolean.parseBoolean(value);
case ("float") : return Float.parseFloat(value);
case ("double") : return Double.parseDouble(value);
case ("char") : return value.charAt(0);
default: return null;
}
}
}

42 changes: 37 additions & 5 deletions src/main/java/track/container/JsonConfigReader.java
Original file line number Diff line number Diff line change
@@ -1,19 +1,51 @@
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.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;
List<Bean> beansList = new ArrayList<Bean>();
try {
Iterator<JsonNode> nodeIterator = new ObjectMapper().readTree(configFile).path("beans").elements();
while (nodeIterator.hasNext()) {
JsonNode currentNode = nodeIterator.next();
beansList.add(new Bean(currentNode.path("id").asText(), currentNode.path("className").asText(),
asMap(currentNode.path("properties"))));

}
} catch (IOException e) {
throw new InvalidConfigurationException(e.getMessage());
}
return beansList;
}

private Map<String, Property> asMap(JsonNode jsonNode) throws InvalidConfigurationException {
Map<String, Property> properties = new HashMap<>();
Iterator<JsonNode> jsonNodeIterator = jsonNode.elements();
while (jsonNodeIterator.hasNext()) {
JsonNode currentNode = jsonNodeIterator.next();
if (currentNode.has("ref")) {
properties.put(currentNode.path("name").asText(),new Property(currentNode.path("name").asText(),
currentNode.path("ref").asText(), ValueType.REF));
} else if (currentNode.has("val")) {
properties.put(currentNode.path("name").asText(), new Property(currentNode.path("name").asText(),
currentNode.path("val").asText(), ValueType.VAL));
} else {
throw new InvalidConfigurationException("Invalid configuration");
}
}
return properties;
}
}
33 changes: 29 additions & 4 deletions src/main/java/track/container/Main.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
package track.container;


import track.container.beans.Car;
import track.container.beans.Engine;
import track.container.beans.Gear;
import track.container.config.Bean;
import track.container.config.InvalidConfigurationException;

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

/**
*
*/
public class Main {

public static void main(String[] args) {
public static void main(String[] args) throws InvalidConfigurationException {
File file = new File("src\\main\\resources\\config.json");
List<Bean> beans = new JsonConfigReader().parseBeans(file);
for (Bean bean: beans) {
System.out.println(bean.toString());
}

/*

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

// // При чтении нужно обработать исключение
// ConfigReader reader = new JsonReader();
// List<Bean> beans = reader.parseBeans("config.json");
// 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");

Container container = new Container(beans);
try {
Gear gear = (Gear) container.getById("gearBean");
System.out.print(gear);
Engine engine = (Engine) container.getById("engineBean");
System.out.print(engine);
Car car = (Car) container.getById("carBean");
System.out.print(car);
} catch (Exception e) {
e.printStackTrace();
}

}
}
13 changes: 11 additions & 2 deletions src/main/java/track/lessons/lesson2/Document.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,24 @@
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) {
for (int i = 0; i < tokens.length; i++) {
if (token != null && tokens[i].equals(token)) {
return true;
}
}
return false;
}
}
16 changes: 14 additions & 2 deletions src/main/java/track/lessons/lesson2/Parser.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,25 @@
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 = "D:\\new.txt";
BufferedReader reader = new BufferedReader(new FileReader(path));

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

// Создайте объект Parser
Parser parser = new Parser();
String str;
StringBuilder sb = new StringBuilder("");
while ((str = reader.readLine()) != null) {
sb.append(str);
sb.append(" ");
}
Document doc = parser.parse(sb.toString());
// reader умеет читать по строкам с помощью метода readLine()

// Создайте объект Parser
Expand Down
54 changes: 53 additions & 1 deletion src/main/java/track/lessons/lesson3/DynamicList.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,57 @@
/**
*
*/
public class DynamicList {
public class DynamicList extends List {
public static final int DEFAULT_CAPACITY = 10;
private int[] list;

public DynamicList(int size) {
int capacity = DEFAULT_CAPACITY;
if (size > 0) {
capacity = size;
}
list = new int[capacity];
}

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

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

@Override
public int remove(int idx) {
if (idx < 0) {
System.out.println("The index can't be less than 0");
return -1;
}
if (idx > size - 1) {
System.out.println("Index out of range");
return -1;
}
int item = list[idx];
System.arraycopy(list, idx + 1, list, idx, --size - idx);
return item;
}

@Override
public int get(int idx) {
if (idx < 0) {
System.out.println("The index can't be less than 0");
return -1;
}
if (idx > size - 1) {
System.out.println("Index out of range");
return -1;
}
return list[idx];
}
}
Loading