Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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 @@
Макеев Иван Алексеевич, СА-11
85 changes: 72 additions & 13 deletions src/main/java/track/container/Container.java
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,41 +1,100 @@
package track.container;

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

import track.container.beans.Engine;
import track.container.config.Bean;
import track.container.config.Property;
import track.container.config.ValueType;

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

Map<String, Object> map = new HashMap<>();
private Map<String, Object> idMap;
private List<Bean> beans;

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

idMap = new HashMap<String, Object>();
this.beans = beans;
}


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

}

/**
* Вернуть объект по имени бина из конфига
* Например, Car car = (Car) container.getById("carBean")
*/
public Object getById(String id) {
return null;
public Object getById(String id) throws ReflectiveOperationException, NoSuchElementException {
if (idMap.containsKey(id)) {
return idMap.get(id);
} else {

// Ищем запрашиваемый кдасс среди бинов. Если не находим, выбрасывается NoSuchElementException
Bean bean;
Iterator<Bean> iterator = beans.iterator();
do {
bean = iterator.next();
} while (!bean.getId().equals(id));

// Создаем объект класса и вносим его в мап
Class clazz = Class.forName(bean.getClassName());
Object obj = clazz.newInstance();
idMap.put(bean.getId(), obj);

// Пробегаемся по всем характеристикам (properties) и устанавливаем нужные значения
// для соответствующих полей создаваемого класса
Map<String, Property> properties = bean.getProperties();
for (Map.Entry<String, Property> entry : properties.entrySet()) {
Property property = entry.getValue();
Field field = clazz.getDeclaredField(property.getName());
field.setAccessible(true);
// Обработка примитивных типов
if (property.getType() == ValueType.VAL) {
switch (field.getType().toString()) {
case "int" : field.setInt(obj, Integer.parseInt(property.getValue()));
break;
case "byte" : field.setByte(obj, Byte.parseByte(property.getValue()));
break;
case "short" : field.setShort(obj, Short.parseShort(property.getValue()));
break;
case "long" : field.setLong(obj, Long.parseLong(property.getValue()));
break;
case "float" : field.setFloat(obj, Float.parseFloat(property.getValue()));
break;
case "double" : field.setDouble(obj, Double.parseDouble(property.getValue()));
break;
case "char" : field.setChar(obj, property.getValue().charAt(0));
break;
case "string" : field.set(obj, property.getValue());
break;
default:
System.out.println("Неверное имя примитивного типа");
}
// Обработка ссылочных типов
} else {
field.set(obj, getById(property.getValue()));
}
}
return obj;
}
}

/**
* Вернуть объект по имени класса
* Например, Car car = (Car) container.getByClass("track.container.beans.Car")
*/
public Object getByClass(String className) {
return null;
public Object getByClass(String className) throws ReflectiveOperationException, NoSuchElementException {
// Ищем запрашиваемый кдасс среди бинов. Если не находим, выбрасывается NoSuchElementException
Bean bean;
Iterator<Bean> iterator = beans.iterator();
do {
bean = iterator.next();
} while (!bean.getClassName().equals(className));

return getById(bean.getId());
}
}
12 changes: 11 additions & 1 deletion src/main/java/track/container/JsonConfigReader.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package track.container;

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

import com.fasterxml.jackson.databind.ObjectMapper;
import track.container.config.Bean;
import track.container.config.ConfigReader;
import track.container.config.InvalidConfigurationException;
import track.container.config.Root;
import track.lections.lection4.Person;

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

@Override
public List<Bean> parseBeans(File configFile) throws InvalidConfigurationException {
return null;
ObjectMapper mapper = new ObjectMapper();
try {
Root root = mapper.readValue(configFile, Root.class);
return root.getBeans();
} catch (IOException ex) {
throw new InvalidConfigurationException("");
}
}
}
39 changes: 39 additions & 0 deletions src/main/java/track/container/Main.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,51 @@
package track.container;

import com.fasterxml.jackson.databind.ObjectMapper;
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 track.container.config.Root;
import track.lections.lection4.Item;
import track.lections.lection4.Person;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

/**
*
*/
public class Main {

public static void main(String[] args) {
JsonConfigReader reader = new JsonConfigReader();
List<Bean> beans;
try {
beans = reader.parseBeans(new File("src/main/resources/config.json"));
Container container = new Container(beans);
Car car = (Car) container.getByClass("track.container.beans.Car");
car = (Car) container.getById("carBean");
System.out.print("gear_count = " + car.getGear().getCount());
System.out.println(", engine_power = " + car.getEngine().getPower());

} catch (ReflectiveOperationException ex) {
System.out.println("Проблемы с рефлекшн");
} catch (InvalidConfigurationException ex) {
System.out.println("Ошибка чтения конфигурационного файла");
} catch (NoSuchElementException ex) {
System.out.println("Нет такого бина");;
} catch (ClassCastException ex) {
System.out.println("Неправильное приведение классов");
} catch (Exception ex) {
System.out.println("Exception");
}
/*

ПРИМЕР ИСПОЛЬЗОВАНИЯ
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/track/container/config/Bean.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ public class Bean {
*/
private Map<String, Property> properties; // Набор полей бина ИмяПоля-Значение

public Bean(){

}

public Bean(String id, String className, Map<String, Property> properties) {
this.id = id;
this.className = className;
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/track/container/config/Property.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ public class Property {
private String value; // Значение поля
private ValueType type; // Метка ссылочное значение или примитив

public Property(){

}

public Property(String name, String value, ValueType type) {
this.name = name;
this.value = value;
Expand Down
112 changes: 56 additions & 56 deletions src/main/java/track/lections/NIOExamples.java
Original file line number Diff line number Diff line change
@@ -1,56 +1,56 @@
package com.company;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOExamples {
public static void main(String[] args) {

}

public void BasicChannel() throws IOException {
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
FileChannel inChannel = aFile.getChannel();

ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = inChannel.read(buf);
while (bytesRead != -1) {

System.out.println("Read " + bytesRead);
buf.flip();

while(buf.hasRemaining()){
System.out.print((char) buf.get());
}

buf.clear();
bytesRead = inChannel.read(buf);
}
aFile.close();
}

public void BasicBufferUsage() throws IOException {
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
FileChannel inChannel = aFile.getChannel();

//create buffer with capacity of 48 bytes
ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = inChannel.read(buf); //read into buffer.
while (bytesRead != -1) {

buf.flip(); //make buffer ready for read

while(buf.hasRemaining()){
System.out.print((char) buf.get()); // read 1 byte at a time
}

buf.clear(); //make buffer ready for writing
bytesRead = inChannel.read(buf);
}
aFile.close();
}
}
//package com.company;
//
//import java.io.IOException;
//import java.io.RandomAccessFile;
//import java.nio.ByteBuffer;
//import java.nio.channels.FileChannel;
//
//public class NIOExamples {
// public static void main(String[] args) {
//
// }
//
// public void BasicChannel() throws IOException {
// RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
// FileChannel inChannel = aFile.getChannel();
//
// ByteBuffer buf = ByteBuffer.allocate(48);
//
// int bytesRead = inChannel.read(buf);
// while (bytesRead != -1) {
//
// System.out.println("Read " + bytesRead);
// buf.flip();
//
// while (buf.hasRemaining()){
// System.out.print((char) buf.get());
// }
//
// buf.clear();
// bytesRead = inChannel.read(buf);
// }
// aFile.close();
// }
//
// public void BasicBufferUsage() throws IOException {
// RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
// FileChannel inChannel = aFile.getChannel();
//
////create buffer with capacity of 48 bytes
// ByteBuffer buf = ByteBuffer.allocate(48);
//
// int bytesRead = inChannel.read(buf); //read into buffer.
// while (bytesRead != -1) {
//
// buf.flip(); //make buffer ready for read
//
// while (buf.hasRemaining()){
// System.out.print((char) buf.get()); // read 1 byte at a time
// }
//
// buf.clear(); //make buffer ready for writing
// bytesRead = inChannel.read(buf);
// }
// aFile.close();
// }
//}
Loading